github.com/krzko/gosh@v0.0.0-20241128233202-5abd4ef06633/internal/shell/executor/executor.go (about) 1 // internal/shell/executor/executor.go 2 package executor 3 4 import ( 5 "os" 6 "os/exec" 7 8 "github.com/krzko/gosh/internal/shell/builtins" 9 "github.com/krzko/gosh/internal/shell/command" 10 ) 11 12 type Command struct { 13 Name string 14 Args []string 15 Pipe *Command 16 } 17 18 type Executor struct { 19 builtins map[string]command.BuiltinCommand 20 } 21 22 func New() *Executor { 23 return &Executor{ 24 builtins: registerBuiltins(), 25 } 26 } 27 28 func (e *Executor) Execute(cmd *Command) error { 29 if builtin, ok := e.builtins[cmd.Name]; ok { 30 return builtin.Execute(cmd.Args) 31 } 32 33 return e.executeExternal(cmd) 34 } 35 36 func (e *Executor) executeExternal(cmd *Command) error { 37 if cmd.Pipe != nil { 38 return e.executePipeline(cmd) 39 } 40 41 command := exec.Command(cmd.Name, cmd.Args...) 42 command.Stdin = os.Stdin 43 command.Stdout = os.Stdout 44 command.Stderr = os.Stderr 45 return command.Run() 46 } 47 48 func (e *Executor) executePipeline(first *Command) error { 49 var commands []*exec.Cmd 50 current := first 51 52 for current != nil { 53 cmd := exec.Command(current.Name, current.Args...) 54 commands = append(commands, cmd) 55 current = current.Pipe 56 } 57 58 // Connect the pipeline 59 for i := 0; i < len(commands)-1; i++ { 60 pipe, err := commands[i].StdoutPipe() 61 if err != nil { 62 return err 63 } 64 commands[i+1].Stdin = pipe 65 } 66 67 // Start all commands 68 for _, cmd := range commands { 69 if err := cmd.Start(); err != nil { 70 return err 71 } 72 } 73 74 // Wait for all commands 75 for _, cmd := range commands { 76 if err := cmd.Wait(); err != nil { 77 return err 78 } 79 } 80 81 return nil 82 } 83 84 func (e *Executor) GetBuiltins() map[string]command.BuiltinCommand { 85 return e.builtins 86 } 87 88 func registerBuiltins() map[string]command.BuiltinCommand { 89 builtinMap := map[string]command.BuiltinCommand{ 90 "ls": builtins.NewLsCommand(), 91 "cd": &builtins.CdCommand{}, 92 "http": &builtins.HttpCommand{}, 93 "https": &builtins.HttpsCommand{}, 94 "exit": &builtins.ExitCommand{}, 95 "pwd": &builtins.PwdCommand{}, 96 "ver": &builtins.VerCommand{}, 97 } 98 99 // Aliases 100 builtinMap["ll"] = &builtins.AliasCommand{ 101 Cmd: builtinMap["ls"], 102 Args: []string{"-la"}, 103 } 104 105 builtinMap["help"] = builtins.NewHelpCommand(builtinMap) 106 107 return builtinMap 108 }