readAndSanitizeFile reads the file at path, capping the read at maxBytes to avoid unbounded memory allocation. It sanitizes the content (strips HTML comments and invisible Unicode) and returns the result. Returns false if the file cannot be read.
(path string, maxBytes int64)
| 273 | // the content (strips HTML comments and invisible Unicode) and |
| 274 | // returns the result. Returns false if the file cannot be read. |
| 275 | func readAndSanitizeFile(path string, maxBytes int64) (content string, truncated bool, ok bool) { |
| 276 | f, err := os.Open(path) |
| 277 | if err != nil { |
| 278 | return "", false, false |
| 279 | } |
| 280 | defer f.Close() |
| 281 | |
| 282 | // Read at most maxBytes+1 to detect truncation without |
| 283 | // allocating the entire file into memory. |
| 284 | raw, err := io.ReadAll(io.LimitReader(f, maxBytes+1)) |
| 285 | if err != nil { |
| 286 | return "", false, false |
| 287 | } |
| 288 | |
| 289 | truncated = int64(len(raw)) > maxBytes |
| 290 | if truncated { |
| 291 | raw = raw[:maxBytes] |
| 292 | } |
| 293 | |
| 294 | s := sanitizeInstructionMarkdown(string(raw)) |
| 295 | if s == "" { |
| 296 | return "", truncated, true |
| 297 | } |
| 298 | return s, truncated, true |
| 299 | } |
| 300 | |
| 301 | // sanitizeInstructionMarkdown strips HTML comments, invisible |
| 302 | // Unicode characters, and CRLF line endings from instruction |
no test coverage detected