on main help sign in
fix: ensure new line at end of non-interactive output (#132)

* fix: ensure new line at end of non-interactive output * fix: err handling * fix: caller uses println so this is not needed

commite1fab86cd260b67e1ff4b7f7aee2076a6ee32d33 authorCarlos Alexandro Becker <caarlos0@users.noreply.github.com> dateThu 10 Jul 2025, 16:12 (1 year ago) parent4f145e5
2 files changed+11−16
internal/app/app.go+5−2 internal/format/format.go+6−14
internal/app/app.go+5−2
@@ -149,10 +149,13 @@ func (a *App) RunNonInteractive(ctx context.Context, prompt string, outputFormat
149149 content = result.Message.Content().String()
150150 }
151151
152− fmt.Println(format.FormatOutput(content, outputFormat))
152+ out, err := format.FormatOutput(content, outputFormat)
153+ if err != nil {
154+ return err
155+ }
153156
157+ fmt.Println(out)
154158 slog.Info("Non-interactive run completed", "session_id", sess.ID)
155−
156159 return nil
157160}
158161
internal/format/format.go+6−14
@@ -57,11 +57,10 @@ func GetHelpText() string {
5757}
5858
5959// FormatOutput formats the AI response according to the specified format
60−func FormatOutput(content string, formatStr string) string {
60+func FormatOutput(content string, formatStr string) (string, error) {
6161 format, err := Parse(formatStr)
6262 if err != nil {
63− // Default to text format on error
64− return content
63+ format = Text
6564 }
6665
6766 switch format {
@@ -70,12 +69,12 @@ func FormatOutput(content string, formatStr string) string {
7069 case Text:
7170 fallthrough
7271 default:
73− return content
72+ return content, nil
7473 }
7574}
7675
7776// formatAsJSON wraps the content in a simple JSON object
78−func formatAsJSON(content string) string {
77+func formatAsJSON(content string) (string, error) {
7978 // Use the JSON package to properly escape the content
8079 response := struct {
8180 Response string `json:"response"`
@@ -85,15 +84,8 @@ func formatAsJSON(content string) string {
8584
8685 jsonBytes, err := json.MarshalIndent(response, "", " ")
8786 if err != nil {
88− // In case of an error, return a manually formatted JSON
89− jsonEscaped := strings.ReplaceAll(content, "\\", "\\\\")
90− jsonEscaped = strings.ReplaceAll(jsonEscaped, "\"", "\\\"")
91− jsonEscaped = strings.ReplaceAll(jsonEscaped, "\n", "\\n")
92− jsonEscaped = strings.ReplaceAll(jsonEscaped, "\r", "\\r")
93− jsonEscaped = strings.ReplaceAll(jsonEscaped, "\t", "\\t")
94−
95− return fmt.Sprintf("{\n \"response\": \"%s\"\n}", jsonEscaped)
87+ return "", fmt.Errorf("failed to marshal output into JSON: %w", err)
9688 }
9789
98− return string(jsonBytes)
90+ return string(jsonBytes), nil
9991}