github.com/markusbkk/elvish@v0.0.0-20231204143114-91dc52438621/pkg/eval/pwd.go (about)

     1  package eval
     2  
     3  import (
     4  	"os"
     5  
     6  	"github.com/markusbkk/elvish/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  // Getwd allows for unit test error injection.
    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() interface{} {
    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 interface{}) error {
    40  	path, ok := v.(string)
    41  	if !ok {
    42  		return vars.ErrPathMustBeString
    43  	}
    44  	return pwd.ev.Chdir(path)
    45  }