on main help sign in
chore(noninteractive): accept a writer for output
commit389a6ab86b752a989b6f55b0d05c20afe284efde authorChristian Rocha <christian@rocha.is> dateSun 2 Nov 2025, 08:29 (1 year ago) parent2fd5ab2
2 files changed+12−7
internal/app/app.go+4−3 internal/cmd/run.go+8−4
internal/app/app.go+4−3
@@ -5,6 +5,7 @@ import (
55 "database/sql"
66 "errors"
77 "fmt"
8+ "io"
89 "log/slog"
910 "sync"
1011 "time"
@@ -103,7 +104,7 @@ func (app *App) Config() *config.Config {
103104
104105// RunNonInteractive runs the application in non-interactive mode with the
105106// given prompt, printing to stdout.
106−func (app *App) RunNonInteractive(ctx context.Context, prompt string, quiet bool) error {
107+func (app *App) RunNonInteractive(ctx context.Context, output io.Writer, prompt string, quiet bool) error {
107108 slog.Info("Running in non-interactive mode")
108109
109110 ctx, cancel := context.WithCancel(ctx)
@@ -170,7 +171,7 @@ func (app *App) RunNonInteractive(ctx context.Context, prompt string, quiet bool
170171
171172 // Always print a newline at the end. If output is a TTY this will
172173 // prevent the prompt from overwriting the last line of output.
173− _, _ = fmt.Print('\n')
174+ _, _ = fmt.Fprintln(output)
174175 }()
175176
176177 for {
@@ -204,7 +205,7 @@ func (app *App) RunNonInteractive(ctx context.Context, prompt string, quiet bool
204205 }
205206
206207 part := content[readBytes:]
207− fmt.Print(part)
208+ fmt.Fprint(output, part)
208209 messageReadBytes[msg.ID] = len(content)
209210 }
210211
internal/cmd/run.go+8−4
@@ -3,6 +3,7 @@ package cmd
33import (
44 "fmt"
55 "log/slog"
6+ "os"
67 "strings"
78
89 "github.com/spf13/cobra"
@@ -18,10 +19,13 @@ The prompt can be provided as arguments or piped from stdin.`,
1819crush run Explain the use of context in Go
1920
2021# Pipe input from stdin
21−echo "What is this code doing?" | crush run
22+curl https://charm.land | crush run "Summarize this website"
2223
23−# Run with quiet mode (no spinner)
24−crush run -q "Generate a README for this project"
24+# Read from a file
25+crush run "What is this code doing?" <<< prrr.go
26+
27+# Run in quiet mode (hide the spinner)
28+crush run --quiet "Generate a README for this project"
2529 `,
2630 RunE: func(cmd *cobra.Command, args []string) error {
2731 quiet, _ := cmd.Flags().GetBool("quiet")
@@ -54,7 +58,7 @@ crush run -q "Generate a README for this project"
5458 // echo "Do something fancy" | crush run > output.txt
5559 //
5660 // TODO: We currently need to press ^c twice to cancel. Fix that.
57− return app.RunNonInteractive(cmd.Context(), prompt, quiet)
61+ return app.RunNonInteractive(cmd.Context(), os.Stdout, prompt, quiet)
5862 },
5963}
6064