|
| 1 | +package term |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "strings" |
| 7 | +) |
| 8 | + |
| 9 | +const ( |
| 10 | + CHAR_UNSPECIFIED = 0 |
| 11 | + CHAR_COLOR_SEQUENCE = 1 |
| 12 | + CHAR_CONTROL = 2 |
| 13 | +) |
| 14 | + |
| 15 | +var ( |
| 16 | + charIndex = []byte{ |
| 17 | + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, |
| 18 | + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, |
| 19 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 20 | + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, |
| 21 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 22 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 23 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 24 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, |
| 25 | + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, |
| 26 | + 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, |
| 27 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 28 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 29 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 30 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 31 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 32 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 33 | + } |
| 34 | +) |
| 35 | + |
| 36 | +// https://github.com/gitgitgadget/git/pull/1853 |
| 37 | +// https://public-inbox.org/git/Z4bqMYKRP7Gva5St@tapette.crustytoothpaste.net/T/#t |
| 38 | +func handleAnsiColorSequence(b *strings.Builder, text []byte, allowColor bool) int { |
| 39 | + /* |
| 40 | + * Valid ANSI color sequences are of the form |
| 41 | + * |
| 42 | + * ESC [ [<n> [; <n>]*] m |
| 43 | + */ |
| 44 | + if len(text) < 3 || text[0] != '\x1b' || text[1] != '[' { |
| 45 | + return 0 |
| 46 | + } |
| 47 | + for i := 2; i < len(text); i++ { |
| 48 | + c := text[i] |
| 49 | + if c == 'm' { |
| 50 | + if allowColor { |
| 51 | + _, _ = b.Write(text[:i+1]) |
| 52 | + } |
| 53 | + return i |
| 54 | + } |
| 55 | + if charIndex[c] != CHAR_COLOR_SEQUENCE { |
| 56 | + break |
| 57 | + } |
| 58 | + } |
| 59 | + return 0 |
| 60 | +} |
| 61 | + |
| 62 | +func SanitizeANSI(content string, allowColor bool) string { |
| 63 | + b := &strings.Builder{} |
| 64 | + text := []byte(content) |
| 65 | + b.Grow(len(text)) |
| 66 | + for i := 0; i < len(text); i++ { |
| 67 | + c := text[i] |
| 68 | + if charIndex[c] != CHAR_CONTROL || c == '\t' || c == '\n' { |
| 69 | + _ = b.WriteByte(c) |
| 70 | + continue |
| 71 | + } |
| 72 | + if j := handleAnsiColorSequence(b, text[i:], allowColor); j != 0 { |
| 73 | + i += j |
| 74 | + continue |
| 75 | + } |
| 76 | + _ = b.WriteByte('^') |
| 77 | + _ = b.WriteByte(c + 0x40) |
| 78 | + } |
| 79 | + return b.String() |
| 80 | +} |
| 81 | + |
| 82 | +func SanitizedF(format string, a ...any) (int, error) { |
| 83 | + content := fmt.Sprintf(format, a...) |
| 84 | + return os.Stderr.WriteString(SanitizeANSI(content, StderrLevel != LevelNone)) |
| 85 | +} |
0 commit comments