builtin_fn_fs.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package eval
  2. import (
  3. "src.elv.sh/pkg/eval/errs"
  4. "src.elv.sh/pkg/fsutil"
  5. )
  6. // Filesystem commands.
  7. func init() {
  8. addBuiltinFns(map[string]any{
  9. // Directory
  10. "cd": cd,
  11. // Path
  12. "tilde-abbr": tildeAbbr,
  13. })
  14. }
  15. //elvdoc:fn cd
  16. //
  17. // ```elvish
  18. // cd $dirname
  19. // ```
  20. //
  21. // Changes directory.
  22. //
  23. // This affects the entire process, including parallel tasks that are started
  24. // implicitly (such as prompt functions) or explicitly (such as one started by
  25. // [`peach`](#peach)).
  26. //
  27. // Note that Elvish's `cd` does not support `cd -`.
  28. //
  29. // @cf pwd
  30. func cd(fm *Frame, args ...string) error {
  31. var dir string
  32. switch len(args) {
  33. case 0:
  34. var err error
  35. dir, err = getHome("")
  36. if err != nil {
  37. return err
  38. }
  39. case 1:
  40. dir = args[0]
  41. default:
  42. return errs.ArityMismatch{What: "arguments", ValidLow: 0, ValidHigh: 1, Actual: len(args)}
  43. }
  44. return fm.Evaler.Chdir(dir)
  45. }
  46. //elvdoc:fn tilde-abbr
  47. //
  48. // ```elvish
  49. // tilde-abbr $path
  50. // ```
  51. //
  52. // If `$path` represents a path under the home directory, replace the home
  53. // directory with `~`. Examples:
  54. //
  55. // ```elvish-transcript
  56. // ~> echo $E:HOME
  57. // /Users/foo
  58. // ~> tilde-abbr /Users/foo
  59. // ▶ '~'
  60. // ~> tilde-abbr /Users/foobar
  61. // ▶ /Users/foobar
  62. // ~> tilde-abbr /Users/foo/a/b
  63. // ▶ '~/a/b'
  64. // ```
  65. func tildeAbbr(path string) string {
  66. return fsutil.TildeAbbr(path)
  67. }