1package cmd
2
3import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "io"
9 "log/slog"
10 "os"
11 "path/filepath"
12 "strconv"
13 "strings"
14
15 tea "charm.land/bubbletea/v2"
16 "charm.land/lipgloss/v2"
17 "github.com/charmbracelet/colorprofile"
18 "github.com/charmbracelet/crush/internal/app"
19 "github.com/charmbracelet/crush/internal/config"
20 "github.com/charmbracelet/crush/internal/db"
21 "github.com/charmbracelet/crush/internal/event"
22 "github.com/charmbracelet/crush/internal/projects"
23 "github.com/charmbracelet/crush/internal/ui/common"
24 ui "github.com/charmbracelet/crush/internal/ui/model"
25 "github.com/charmbracelet/crush/internal/version"
26 "github.com/charmbracelet/fang"
27 uv "github.com/charmbracelet/ultraviolet"
28 "github.com/charmbracelet/x/ansi"
29 "github.com/charmbracelet/x/exp/charmtone"
30 "github.com/charmbracelet/x/term"
31 "github.com/spf13/cobra"
32)
33
34func init() {
35 rootCmd.PersistentFlags().StringP("cwd", "c", "", "Current working directory")
36 rootCmd.PersistentFlags().StringP("data-dir", "D", "", "Custom crush data directory")
37 rootCmd.PersistentFlags().BoolP("debug", "d", false, "Debug")
38 rootCmd.Flags().BoolP("help", "h", false, "Help")
39 rootCmd.Flags().BoolP("yolo", "y", false, "Automatically accept all permissions (dangerous mode)")
40
41 rootCmd.AddCommand(
42 runCmd,
43 dirsCmd,
44 projectsCmd,
45 updateProvidersCmd,
46 logsCmd,
47 schemaCmd,
48 loginCmd,
49 statsCmd,
50 )
51}
52
53var rootCmd = &cobra.Command{
54 Use: "crush",
55 Short: "An AI assistant for software development",
56 Long: "An AI assistant for software development and similar tasks with direct access to the terminal",
57 Example: `
58# Run in interactive mode
59crush
60
61# Run with debug logging
62crush -d
63
64# Run with debug logging in a specific directory
65crush -d -c /path/to/project
66
67# Run with custom data directory
68crush -D /path/to/custom/.crush
69
70# Print version
71crush -v
72
73# Run a single non-interactive prompt
74crush run "Explain the use of context in Go"
75
76# Run in dangerous mode (auto-accept all permissions)
77crush -y
78 `,
79 RunE: func(cmd *cobra.Command, args []string) error {
80 app, err := setupAppWithProgressBar(cmd)
81 if err != nil {
82 return err
83 }
84 defer app.Shutdown()
85
86 event.AppInitialized()
87
88 // Set up the TUI.
89 var env uv.Environ = os.Environ()
90
91 com := common.DefaultCommon(app)
92 model := ui.New(com)
93
94 program := tea.NewProgram(
95 model,
96 tea.WithEnvironment(env),
97 tea.WithContext(cmd.Context()),
98 tea.WithFilter(ui.MouseEventFilter), // Filter mouse events based on focus state
99 )
100 go app.Subscribe(program)
101
102 if _, err := program.Run(); err != nil {
103 // ErrProgramKilled is returned when the program is terminated externally
104 // (e.g., terminal closed, parent process died). This is not a crash.
105 if errors.Is(err, tea.ErrProgramKilled) {
106 return nil
107 }
108 event.Error(err)
109 slog.Error("TUI run error", "error", err)
110 return errors.New("Crush crashed. If metrics are enabled, we were notified about it. If you'd like to report it, please copy the stacktrace above and open an issue at https://github.com/charmbracelet/crush/issues/new?template=bug.yml") //nolint:staticcheck
111 }
112 return nil
113 },
114}
115
116var heartbit = lipgloss.NewStyle().Foreground(charmtone.Dolly).SetString(`
117 ▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄
118 ███████████ ███████████
119████████████████████████████
120████████████████████████████
121██████████▀██████▀██████████
122██████████ ██████ ██████████
123▀▀██████▄████▄▄████▄██████▀▀
124 ████████████████████████
125 ████████████████████
126 ▀▀██████████▀▀
127 ▀▀▀▀▀▀
128`)
129
130// copied from cobra:
131const defaultVersionTemplate = `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}}
132`
133
134func Execute() {
135 // NOTE: very hacky: we create a colorprofile writer with STDOUT, then make
136 // it forward to a bytes.Buffer, write the colored heartbit to it, and then
137 // finally prepend it in the version template.
138 // Unfortunately cobra doesn't give us a way to set a function to handle
139 // printing the version, and PreRunE runs after the version is already
140 // handled, so that doesn't work either.
141 // This is the only way I could find that works relatively well.
142 if term.IsTerminal(os.Stdout.Fd()) {
143 var b bytes.Buffer
144 w := colorprofile.NewWriter(os.Stdout, os.Environ())
145 w.Forward = &b
146 _, _ = w.WriteString(heartbit.String())
147 rootCmd.SetVersionTemplate(b.String() + "\n" + defaultVersionTemplate)
148 }
149 if err := fang.Execute(
150 context.Background(),
151 rootCmd,
152 fang.WithVersion(version.Version),
153 fang.WithNotifySignal(os.Interrupt),
154 ); err != nil {
155 os.Exit(1)
156 }
157}
158
159// supportsProgressBar tries to determine whether the current terminal supports
160// progress bars by looking into environment variables.
161func supportsProgressBar() bool {
162 if !term.IsTerminal(os.Stderr.Fd()) {
163 return false
164 }
165 termProg := os.Getenv("TERM_PROGRAM")
166 _, isWindowsTerminal := os.LookupEnv("WT_SESSION")
167
168 return isWindowsTerminal || strings.Contains(strings.ToLower(termProg), "ghostty")
169}
170
171func setupAppWithProgressBar(cmd *cobra.Command) (*app.App, error) {
172 app, err := setupApp(cmd)
173 if err != nil {
174 return nil, err
175 }
176
177 // Check if progress bar is enabled in config (defaults to true if nil)
178 progressEnabled := app.Config().Options.Progress == nil || *app.Config().Options.Progress
179 if progressEnabled && supportsProgressBar() {
180 _, _ = fmt.Fprintf(os.Stderr, ansi.SetIndeterminateProgressBar)
181 defer func() { _, _ = fmt.Fprintf(os.Stderr, ansi.ResetProgressBar) }()
182 }
183
184 return app, nil
185}
186
187// setupApp handles the common setup logic for both interactive and non-interactive modes.
188// It returns the app instance, config, cleanup function, and any error.
189func setupApp(cmd *cobra.Command) (*app.App, error) {
190 debug, _ := cmd.Flags().GetBool("debug")
191 yolo, _ := cmd.Flags().GetBool("yolo")
192 dataDir, _ := cmd.Flags().GetString("data-dir")
193 ctx := cmd.Context()
194
195 cwd, err := ResolveCwd(cmd)
196 if err != nil {
197 return nil, err
198 }
199
200 cfg, err := config.Init(cwd, dataDir, debug)
201 if err != nil {
202 return nil, err
203 }
204
205 if cfg.Permissions == nil {
206 cfg.Permissions = &config.Permissions{}
207 }
208 cfg.Permissions.SkipRequests = yolo
209
210 if err := createDotCrushDir(cfg.Options.DataDirectory); err != nil {
211 return nil, err
212 }
213
214 // Register this project in the centralized projects list.
215 if err := projects.Register(cwd, cfg.Options.DataDirectory); err != nil {
216 slog.Warn("Failed to register project", "error", err)
217 // Non-fatal: continue even if registration fails
218 }
219
220 // Connect to DB; this will also run migrations.
221 conn, err := db.Connect(ctx, cfg.Options.DataDirectory)
222 if err != nil {
223 return nil, err
224 }
225
226 appInstance, err := app.New(ctx, conn, cfg)
227 if err != nil {
228 slog.Error("Failed to create app instance", "error", err)
229 return nil, err
230 }
231
232 if shouldEnableMetrics(cfg) {
233 event.Init()
234 }
235
236 return appInstance, nil
237}
238
239func shouldEnableMetrics(cfg *config.Config) bool {
240 if v, _ := strconv.ParseBool(os.Getenv("CRUSH_DISABLE_METRICS")); v {
241 return false
242 }
243 if v, _ := strconv.ParseBool(os.Getenv("DO_NOT_TRACK")); v {
244 return false
245 }
246 if cfg.Options.DisableMetrics {
247 return false
248 }
249 return true
250}
251
252func MaybePrependStdin(prompt string) (string, error) {
253 if term.IsTerminal(os.Stdin.Fd()) {
254 return prompt, nil
255 }
256 fi, err := os.Stdin.Stat()
257 if err != nil {
258 return prompt, err
259 }
260 // Check if stdin is a named pipe ( | ) or regular file ( < ).
261 if fi.Mode()&os.ModeNamedPipe == 0 && !fi.Mode().IsRegular() {
262 return prompt, nil
263 }
264 bts, err := io.ReadAll(os.Stdin)
265 if err != nil {
266 return prompt, err
267 }
268 return string(bts) + "\n\n" + prompt, nil
269}
270
271func ResolveCwd(cmd *cobra.Command) (string, error) {
272 cwd, _ := cmd.Flags().GetString("cwd")
273 if cwd != "" {
274 err := os.Chdir(cwd)
275 if err != nil {
276 return "", fmt.Errorf("failed to change directory: %v", err)
277 }
278 return cwd, nil
279 }
280 cwd, err := os.Getwd()
281 if err != nil {
282 return "", fmt.Errorf("failed to get current working directory: %v", err)
283 }
284 return cwd, nil
285}
286
287func createDotCrushDir(dir string) error {
288 if err := os.MkdirAll(dir, 0o700); err != nil {
289 return fmt.Errorf("failed to create data directory: %q %w", dir, err)
290 }
291
292 gitIgnorePath := filepath.Join(dir, ".gitignore")
293 if _, err := os.Stat(gitIgnorePath); os.IsNotExist(err) {
294 if err := os.WriteFile(gitIgnorePath, []byte("*\n"), 0o644); err != nil {
295 return fmt.Errorf("failed to create .gitignore file: %q %w", gitIgnorePath, err)
296 }
297 }
298
299 return nil
300}