root.go 8.7 KB

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