github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/utils/cd/cd.go (about)

     1  package cd
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/lmorg/murex/debug"
     8  	"github.com/lmorg/murex/lang"
     9  	"github.com/lmorg/murex/lang/types"
    10  	"github.com/lmorg/murex/utils/cd/cache"
    11  )
    12  
    13  // GlobalVarName is the name of the path history variable that `cd` writes to
    14  const GlobalVarName = "PWDHIST"
    15  
    16  // Chdir changes the current working directory and updates the global working
    17  // environment
    18  func Chdir(p *lang.Process, path string) error {
    19  	if pwd, _ := os.Getwd(); pwd == path {
    20  		return nil
    21  	}
    22  
    23  	err := os.Chdir(path)
    24  	if err != nil {
    25  		return err
    26  	}
    27  
    28  	pwd, err := os.Getwd()
    29  	if err != nil {
    30  		p.Stderr.Writeln([]byte(err.Error()))
    31  		pwd = path
    32  	}
    33  
    34  	if lang.Interactive {
    35  		go cache.GatherFileCompletions(pwd)
    36  	}
    37  
    38  	// Update $PWD environmental variable for compatibility reasons
    39  	err = os.Setenv("PWD", pwd)
    40  	if err != nil {
    41  		p.Stderr.Writeln([]byte(err.Error()))
    42  	}
    43  
    44  	// Update $PWDHIST murex variable - a more idiomatic approach to PWD
    45  	pwdHist, err := lang.GlobalVariables.GetValue(GlobalVarName)
    46  	if err != nil {
    47  		return err
    48  	}
    49  
    50  	switch pwdHist.(type) {
    51  	case []string:
    52  		pwdHist = append(pwdHist.([]string), pwd)
    53  	case []interface{}:
    54  		pwdHist = append(pwdHist.([]interface{}), pwd)
    55  	default:
    56  		debug.Log(fmt.Sprintf("$%s has become corrupt (%T) so regenerating", GlobalVarName, pwdHist))
    57  		pwdHist = []string{pwd}
    58  	}
    59  
    60  	err = lang.GlobalVariables.Set(p, GlobalVarName, pwdHist, types.Json)
    61  	return err
    62  }