2
0

root.go 8.6 KB

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