github.com/krzko/gosh@v0.0.0-20241128233202-5abd4ef06633/internal/shell/builtins/cd.go (about)

     1  // internal/shell/builtins/cd.go
     2  package builtins
     3  
     4  import (
     5  	"os"
     6  	"path/filepath"
     7  )
     8  
     9  type CdCommand struct{}
    10  
    11  func (c *CdCommand) Execute(args []string) error {
    12  	var dir string
    13  	if len(args) == 0 {
    14  		homeDir, err := os.UserHomeDir()
    15  		if err != nil {
    16  			return err
    17  		}
    18  		dir = homeDir
    19  	} else {
    20  		dir = args[0]
    21  
    22  		// Handle ".." special case
    23  		if dir == ".." {
    24  			currentDir, err := os.Getwd()
    25  			if err != nil {
    26  				return err
    27  			}
    28  			dir = filepath.Dir(currentDir)
    29  		}
    30  	}
    31  
    32  	// Clean the path to resolve any .. or . in the middle of paths
    33  	dir = filepath.Clean(dir)
    34  
    35  	// Expand ~ to home directory if it's the first character
    36  	if len(dir) > 0 && dir[0] == '~' {
    37  		homeDir, err := os.UserHomeDir()
    38  		if err != nil {
    39  			return err
    40  		}
    41  		dir = filepath.Join(homeDir, dir[1:])
    42  	}
    43  
    44  	return os.Chdir(dir)
    45  }
    46  
    47  func (c *CdCommand) Help() string {
    48  	return `cd: Change the current directory
    49  Usage: cd [directory]
    50  
    51  Special paths:
    52    ..    Move to parent directory
    53    ~     Move to home directory
    54    .     Stay in current directory`
    55  }