fix: ensure new line at end of non-interactive output (#132)

Carlos Alexandro Becker created

* fix: ensure new line at end of non-interactive output

* fix: err handling

* fix: caller uses println so this is not needed

Change summary

internal/app/app.go       |  7 +++++--
internal/format/format.go | 20 ++++++--------------
2 files changed, 11 insertions(+), 16 deletions(-)

Detailed changes

internal/app/app.go 🔗

@@ -149,10 +149,13 @@ func (a *App) RunNonInteractive(ctx context.Context, prompt string, outputFormat
 		content = result.Message.Content().String()
 	}
 
-	fmt.Println(format.FormatOutput(content, outputFormat))
+	out, err := format.FormatOutput(content, outputFormat)
+	if err != nil {
+		return err
+	}
 
+	fmt.Println(out)
 	slog.Info("Non-interactive run completed", "session_id", sess.ID)
-
 	return nil
 }
 

internal/format/format.go 🔗

@@ -57,11 +57,10 @@ func GetHelpText() string {
 }
 
 // FormatOutput formats the AI response according to the specified format
-func FormatOutput(content string, formatStr string) string {
+func FormatOutput(content string, formatStr string) (string, error) {
 	format, err := Parse(formatStr)
 	if err != nil {
-		// Default to text format on error
-		return content
+		format = Text
 	}
 
 	switch format {
@@ -70,12 +69,12 @@ func FormatOutput(content string, formatStr string) string {
 	case Text:
 		fallthrough
 	default:
-		return content
+		return content, nil
 	}
 }
 
 // formatAsJSON wraps the content in a simple JSON object
-func formatAsJSON(content string) string {
+func formatAsJSON(content string) (string, error) {
 	// Use the JSON package to properly escape the content
 	response := struct {
 		Response string `json:"response"`
@@ -85,15 +84,8 @@ func formatAsJSON(content string) string {
 
 	jsonBytes, err := json.MarshalIndent(response, "", "  ")
 	if err != nil {
-		// In case of an error, return a manually formatted JSON
-		jsonEscaped := strings.ReplaceAll(content, "\\", "\\\\")
-		jsonEscaped = strings.ReplaceAll(jsonEscaped, "\"", "\\\"")
-		jsonEscaped = strings.ReplaceAll(jsonEscaped, "\n", "\\n")
-		jsonEscaped = strings.ReplaceAll(jsonEscaped, "\r", "\\r")
-		jsonEscaped = strings.ReplaceAll(jsonEscaped, "\t", "\\t")
-
-		return fmt.Sprintf("{\n  \"response\": \"%s\"\n}", jsonEscaped)
+		return "", fmt.Errorf("failed to marshal output into JSON: %w", err)
 	}
 
-	return string(jsonBytes)
+	return string(jsonBytes), nil
 }