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
|
|
|
|
2021-01-27 09:28:38 +08:00
|
|
|
"src.elv.sh/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
|
|
|
|
2022-06-20 06:56:18 +08:00
|
|
|
// Can be mutated in tests.
|
|
|
|
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.
|
2022-03-20 23:50:25 +08:00
|
|
|
func (pwdVar) Get() any {
|
2022-06-20 06:56:18 +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.
|
2022-03-20 23:50:25 +08:00
|
|
|
func (pwd pwdVar) Set(v any) error {
|
2018-01-25 09:40:15 +08:00
|
|
|
path, ok := v.(string)
|
2016-02-21 19:58:20 +08:00
|
|
|
if !ok {
|
2021-01-05 12:07:35 +08:00
|
|
|
return vars.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
|
|
|
}
|