elvish/pkg/eval/pwd.go

46 lines
1.1 KiB
Go
Raw Normal View History

2016-02-21 19:58:20 +08:00
package eval
import (
"os"
"src.elv.sh/pkg/eval/vars"
)
2016-02-21 19:58:20 +08:00
2020-09-05 05:32:41 +08:00
// NewPwdVar returns a variable who value is synchronized with the path of the
// current working directory.
func NewPwdVar(ev *Evaler) vars.Var { return pwdVar{ev} }
// pwdVar is a variable whose value always reflects the current working
2016-02-21 19:58:20 +08:00
// directory. Setting it changes the current working directory.
2020-09-05 05:32:41 +08:00
type pwdVar struct {
ev *Evaler
}
2016-02-21 19:58:20 +08:00
2020-09-05 05:32:41 +08:00
var _ vars.Var = pwdVar{}
2016-02-21 19:58:20 +08:00
// Getwd allows for unit test error injection.
var Getwd func() (string, error) = os.Getwd
// Get returns the current working directory. It returns "/unknown/pwd" when
// it cannot be determined.
func (pwdVar) Get() any {
pwd, err := Getwd()
2018-09-27 08:48:44 +08:00
if err != nil {
// This should really use the path separator appropriate for the
// platform but in practice this hardcoded string works fine. Both
// because MS Windows supports forward slashes and this will very
// rarely occur.
2018-09-27 08:48:44 +08:00
return "/unknown/pwd"
}
return pwd
2016-02-21 19:58:20 +08:00
}
2019-04-19 05:15:34 +08:00
// Set changes the current working directory.
func (pwd pwdVar) Set(v any) error {
path, ok := v.(string)
2016-02-21 19:58:20 +08:00
if !ok {
return vars.ErrPathMustBeString
2016-02-21 19:58:20 +08:00
}
return pwd.ev.Chdir(path)
2016-02-21 19:58:20 +08:00
}