Harden safecsv against whitespace formula tricks

Ignore leading Unicode space when detecting formula cells,
extend starter runes, and document export usage in package
doc.

Signed-off-by: Cursor Agent <cursoragent@cursor.com>

Co-authored-by: Bryan FRIMIN <bryan@frimin.fr>
This commit is contained in:
Cursor Agent
2026-07-30 06:42:47 +00:00
parent fc54faa263
commit 90b3258f32
3 changed files with 59 additions and 4 deletions

View File

@@ -20,6 +20,12 @@
package safecsv
import (
"strings"
"unicode"
"unicode/utf8"
)
// SanitizeRecord returns a copy of record with spreadsheet-safe cell values.
func SanitizeRecord(record []string) []string {
if len(record) == 0 {
@@ -35,15 +41,31 @@ func SanitizeRecord(record []string) []string {
}
// SanitizeCell prefixes values that spreadsheet tools may interpret as formulas.
// Leading Unicode whitespace (including newlines) is ignored for detection only;
// the written cell keeps the original text with a leading single-quote escape.
func SanitizeCell(value string) string {
if value == "" {
return value
}
switch value[0] {
case '=', '+', '-', '@', '\t', '\r':
return "'" + value
default:
trimmed := strings.TrimLeftFunc(value, unicode.IsSpace)
if trimmed == "" {
return value
}
r, _ := utf8.DecodeRuneInString(trimmed)
if formulaLeadingRune(r) {
return "'" + value
}
return value
}
func formulaLeadingRune(r rune) bool {
switch r {
case '=', '+', '-', '@', '\\', '|', '%':
return true
default:
return false
}
}