on main help sign in
fix: ensure new line at end of non-interactive output (#132)
e1fab86Carlos Alexandro Becker
internal/app/app.go+5−2
@@ -149,10 +149,13 @@ func (a *App) RunNonInteractive(ctx context.Context, prompt string, outputFormat
149 content = result.Message.Content().String()
149 content = result.Message.Content().String()
150 }
150 }
151
151
152− fmt.Println(format.FormatOutput(content, outputFormat))
152+ out, err := format.FormatOutput(content, outputFormat)
153+ if err != nil {
154+ return err
155+ }
153
156
157+ fmt.Println(out)
154 slog.Info("Non-interactive run completed", "session_id", sess.ID)
158 slog.Info("Non-interactive run completed", "session_id", sess.ID)
155−
156 return nil
159 return nil
157}
160}
158
161
internal/format/format.go+6−14
@@ -57,11 +57,10 @@ func GetHelpText() string {
57}
57}
58
58
59// FormatOutput formats the AI response according to the specified format
59// 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) {
61 format, err := Parse(formatStr)
61 format, err := Parse(formatStr)
62 if err != nil {
62 if err != nil {
63− // Default to text format on error
63+ format = Text
64− return content
65 }
64 }
66
65
67 switch format {
66 switch format {
@@ -70,12 +69,12 @@ func FormatOutput(content string, formatStr string) string {
70 case Text:
69 case Text:
71 fallthrough
70 fallthrough
72 default:
71 default:
73− return content
72+ return content, nil
74 }
73 }
75}
74}
76
75
77// formatAsJSON wraps the content in a simple JSON object
76// formatAsJSON wraps the content in a simple JSON object
78−func formatAsJSON(content string) string {
77+func formatAsJSON(content string) (string, error) {
79 // Use the JSON package to properly escape the content
78 // Use the JSON package to properly escape the content
80 response := struct {
79 response := struct {
81 Response string `json:"response"`
80 Response string `json:"response"`
@@ -85,15 +84,8 @@ func formatAsJSON(content string) string {
85
84
86 jsonBytes, err := json.MarshalIndent(response, "", " ")
85 jsonBytes, err := json.MarshalIndent(response, "", " ")
87 if err != nil {
86 if err != nil {
88− // In case of an error, return a manually formatted JSON
87+ return "", fmt.Errorf("failed to marshal output into JSON: %w", err)
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)
96 }
88 }
97
89
98− return string(jsonBytes)
90+ return string(jsonBytes), nil
99}
91}