github.com/krzko/gosh@v0.0.0-20241128233202-5abd4ef06633/internal/shell/shell.go (about) 1 // internal/shell/shell.go 2 package shell 3 4 import ( 5 "fmt" 6 "os" 7 8 "github.com/krzko/gosh/internal/shell/completion" 9 "github.com/krzko/gosh/internal/shell/executor" 10 "github.com/krzko/gosh/internal/shell/history" 11 "github.com/krzko/gosh/internal/shell/parser" 12 "github.com/krzko/gosh/internal/shell/prompt" 13 ) 14 15 type Shell struct { 16 prompt *prompt.Manager 17 parser *parser.Parser 18 executor *executor.Executor 19 completer *completion.Completer 20 history *history.Manager 21 } 22 23 // internal/shell/shell.go 24 func New() (*Shell, error) { 25 // Initialize history first 26 hist, err := history.NewManager(".gosh_history") 27 if err != nil { 28 return nil, fmt.Errorf("failed to initialize history: %w", err) 29 } 30 31 // Initialize executor to get builtins 32 executor := executor.New() 33 34 // Initialize completer 35 completer := completion.NewCompleter() 36 37 // Initialize prompt with history and builtins 38 promptManager, err := prompt.NewManager(completer, executor.GetBuiltins()) 39 if err != nil { 40 return nil, fmt.Errorf("failed to initialize prompt: %w", err) 41 } 42 43 // Create shell instance 44 sh := &Shell{ 45 prompt: promptManager, 46 parser: parser.New(), 47 executor: executor, 48 completer: completer, 49 history: hist, 50 } 51 52 return sh, nil 53 } 54 55 func (s *Shell) Run() error { 56 defer s.cleanup() 57 58 for { 59 input, err := s.prompt.Read() 60 if err != nil { 61 if err.Error() == "EOF" { 62 return nil // Clean exit on Ctrl+D 63 } 64 return err 65 } 66 67 if input == "" { 68 continue 69 } 70 71 // Add to history 72 if err := s.history.Add(input); err != nil { 73 fmt.Fprintf(os.Stderr, "Failed to add to history: %v\n", err) 74 } 75 76 // Parse the command 77 cmd, err := s.parser.Parse(input) 78 if err != nil { 79 fmt.Fprintf(os.Stderr, "Parse error: %v\n", err) 80 continue 81 } 82 83 // Execute the command 84 if err := s.executor.Execute(cmd); err != nil { 85 fmt.Fprintf(os.Stderr, "Execution error: %v\n", err) 86 } 87 } 88 } 89 90 func (s *Shell) cleanup() { 91 if s.prompt != nil { 92 s.prompt.Close() 93 } 94 if s.history != nil { 95 s.history.Close() 96 } 97 }