ToFile exports session data to an HTML file. If filename is empty, a default name based on the title and timestamp is used. Returns the absolute path of the created file.
(data SessionData, filename string)
| 125 | // If filename is empty, a default name based on the title and timestamp is used. |
| 126 | // Returns the absolute path of the created file. |
| 127 | func ToFile(data SessionData, filename string) (string, error) { |
| 128 | if len(data.Messages) == 0 { |
| 129 | return "", errors.New("session is empty") |
| 130 | } |
| 131 | |
| 132 | // Generate filename if not provided |
| 133 | if filename == "" { |
| 134 | title := data.Title |
| 135 | if title == "" { |
| 136 | title = "cagent-session" |
| 137 | } |
| 138 | title = sanitizeFilename(title) |
| 139 | filename = fmt.Sprintf("%s-%s.html", title, time.Now().Format("2006-01-02-150405")) |
| 140 | } |
| 141 | |
| 142 | // Ensure .html extension |
| 143 | if !strings.HasSuffix(strings.ToLower(filename), ".html") { |
| 144 | filename += ".html" |
| 145 | } |
| 146 | |
| 147 | htmlContent, err := Generate(data) |
| 148 | if err != nil { |
| 149 | return "", fmt.Errorf("failed to generate HTML: %w", err) |
| 150 | } |
| 151 | |
| 152 | if err := os.WriteFile(filename, []byte(htmlContent), 0o644); err != nil { //nolint:gosec // exported HTML is meant to be readable by browsers/users |
| 153 | return "", fmt.Errorf("failed to write file: %w", err) |
| 154 | } |
| 155 | |
| 156 | absPath, err := filepath.Abs(filename) |
| 157 | if err != nil { |
| 158 | return filename, nil |
| 159 | } |
| 160 | return absPath, nil |
| 161 | } |
| 162 | |
| 163 | func sanitizeFilename(name string) string { |
| 164 | replacer := strings.NewReplacer( |
no test coverage detected