src.elv.sh@v0.21.0-dev.0.20240515223629-06979efb9a2a/pkg/eval/pwd.go (about) 1 package eval 2 3 import ( 4 "os" 5 6 "src.elv.sh/pkg/eval/vars" 7 ) 8 9 // NewPwdVar returns a variable who value is synchronized with the path of the 10 // current working directory. 11 func NewPwdVar(ev *Evaler) vars.Var { return pwdVar{ev} } 12 13 // pwdVar is a variable whose value always reflects the current working 14 // directory. Setting it changes the current working directory. 15 type pwdVar struct { 16 ev *Evaler 17 } 18 19 var _ vars.Var = pwdVar{} 20 21 // Can be mutated in tests. 22 var getwd func() (string, error) = os.Getwd 23 24 // Get returns the current working directory. It returns "/unknown/pwd" when 25 // it cannot be determined. 26 func (pwdVar) Get() any { 27 pwd, err := getwd() 28 if err != nil { 29 // This should really use the path separator appropriate for the 30 // platform but in practice this hardcoded string works fine. Both 31 // because MS Windows supports forward slashes and this will very 32 // rarely occur. 33 return "/unknown/pwd" 34 } 35 return pwd 36 } 37 38 // Set changes the current working directory. 39 func (pwd pwdVar) Set(v any) error { 40 path, ok := v.(string) 41 if !ok { 42 return vars.ErrPathMustBeString 43 } 44 return pwd.ev.Chdir(path) 45 }