2016-02-21 19:58:20 +08:00
|
|
|
package eval
|
|
|
|
|
2017-06-25 00:08:47 +08:00
|
|
|
import (
|
|
|
|
"os"
|
2018-01-01 04:31:45 +08:00
|
|
|
|
2019-12-24 04:00:59 +08:00
|
|
|
"github.com/elves/elvish/pkg/eval/vars"
|
2017-06-25 00:08:47 +08:00
|
|
|
)
|
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 {
|
2018-03-22 04:51:08 +08:00
|
|
|
ev *Evaler
|
2017-06-25 00:08:47 +08:00
|
|
|
}
|
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
|
|
|
|
2020-08-17 03:18:20 +08:00
|
|
|
// Getwd allows for unit test error injection.
|
2020-10-17 10:35:38 +08:00
|
|
|
var Getwd func() (string, error) = os.Getwd
|
2020-08-17 03:18:20 +08:00
|
|
|
|
|
|
|
// Get returns the current working directory. It returns "/unknown/pwd" when
|
|
|
|
// it cannot be determined.
|
2020-09-05 05:32:41 +08:00
|
|
|
func (pwdVar) Get() interface{} {
|
2020-10-17 10:35:38 +08:00
|
|
|
pwd, err := Getwd()
|
2018-09-27 08:48:44 +08:00
|
|
|
if err != nil {
|
2020-10-17 10:35:38 +08:00
|
|
|
// 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"
|
|
|
|
}
|
2018-01-25 09:40:15 +08:00
|
|
|
return pwd
|
2016-02-21 19:58:20 +08:00
|
|
|
}
|
|
|
|
|
2019-04-19 05:15:34 +08:00
|
|
|
// Set changes the current working directory.
|
2020-09-05 05:32:41 +08:00
|
|
|
func (pwd pwdVar) Set(v interface{}) error {
|
2018-01-25 09:40:15 +08:00
|
|
|
path, ok := v.(string)
|
2016-02-21 19:58:20 +08:00
|
|
|
if !ok {
|
2018-01-03 10:04:14 +08:00
|
|
|
return ErrPathMustBeString
|
2016-02-21 19:58:20 +08:00
|
|
|
}
|
2018-03-22 04:51:08 +08:00
|
|
|
return pwd.ev.Chdir(path)
|
2016-02-21 19:58:20 +08:00
|
|
|
}
|