format.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package format
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. )
  7. // OutputFormat represents the output format type for non-interactive mode
  8. type OutputFormat string
  9. const (
  10. // Text format outputs the AI response as plain text.
  11. Text OutputFormat = "text"
  12. // JSON format outputs the AI response wrapped in a JSON object.
  13. JSON OutputFormat = "json"
  14. )
  15. // String returns the string representation of the OutputFormat
  16. func (f OutputFormat) String() string {
  17. return string(f)
  18. }
  19. // SupportedFormats is a list of all supported output formats as strings
  20. var SupportedFormats = []string{
  21. string(Text),
  22. string(JSON),
  23. }
  24. // Parse converts a string to an OutputFormat
  25. func Parse(s string) (OutputFormat, error) {
  26. s = strings.ToLower(strings.TrimSpace(s))
  27. switch s {
  28. case string(Text):
  29. return Text, nil
  30. case string(JSON):
  31. return JSON, nil
  32. default:
  33. return "", fmt.Errorf("invalid format: %s", s)
  34. }
  35. }
  36. // IsValid checks if the provided format string is supported
  37. func IsValid(s string) bool {
  38. _, err := Parse(s)
  39. return err == nil
  40. }
  41. // GetHelpText returns a formatted string describing all supported formats
  42. func GetHelpText() string {
  43. return fmt.Sprintf(`Supported output formats:
  44. - %s: Plain text output (default)
  45. - %s: Output wrapped in a JSON object`,
  46. Text, JSON)
  47. }
  48. // FormatOutput formats the AI response according to the specified format
  49. func FormatOutput(content string, formatStr string) (string, error) {
  50. format, err := Parse(formatStr)
  51. if err != nil {
  52. format = Text
  53. }
  54. switch format {
  55. case JSON:
  56. return formatAsJSON(content)
  57. case Text:
  58. fallthrough
  59. default:
  60. return content, nil
  61. }
  62. }
  63. // formatAsJSON wraps the content in a simple JSON object
  64. func formatAsJSON(content string) (string, error) {
  65. // Use the JSON package to properly escape the content
  66. response := struct {
  67. Response string `json:"response"`
  68. }{
  69. Response: content,
  70. }
  71. jsonBytes, err := json.MarshalIndent(response, "", " ")
  72. if err != nil {
  73. return "", fmt.Errorf("failed to marshal output into JSON: %w", err)
  74. }
  75. return string(jsonBytes), nil
  76. }