]> ruderich.org/simon Gitweb - safcm/safcm.git/blob - frontend/term.go
Use SPDX license identifiers
[safcm/safcm.git] / frontend / term.go
1 // Frontend: Functions for terminal output
2
3 // SPDX-License-Identifier: GPL-3.0-or-later
4 // Copyright (C) 2021-2024  Simon Ruderich
5
6 package frontend
7
8 import (
9         "fmt"
10         "regexp"
11 )
12
13 type Color int
14
15 const (
16         _ Color = iota
17         ColorRed
18         ColorGreen
19         ColorCyan
20         ColorMagenta
21 )
22
23 func ColorString(isTTY bool, color Color, x string) string {
24         if !isTTY {
25                 return x
26         }
27
28         var code string
29         switch color {
30         case ColorRed:
31                 code = "31"
32         case ColorGreen:
33                 code = "32"
34         case ColorMagenta:
35                 code = "35"
36         case ColorCyan:
37                 code = "36"
38         default:
39                 panic(fmt.Sprintf("invalid color %v", color))
40         }
41         // TODO: check terminal support
42         return "\033[" + code + "m" + x + "\033[0m"
43 }
44
45 var escapeRegexp = regexp.MustCompile(`[\x00-\x08\x0B-\x1F\x7F]`)
46
47 // EscapeControlCharacters escapes all ASCII control characters (except
48 // newline and tab) by replacing them with their hex value. If the output is
49 // to a TTY then the escaped characters are colored.
50 //
51 // This function must be used when displaying any input from remote hosts to
52 // prevent terminal escape code injections.
53 func EscapeControlCharacters(isTTY bool, x string) string {
54         return escapeRegexp.ReplaceAllStringFunc(x, func(x string) string {
55                 if len(x) != 1 {
56                         panic("invalid escapeRegexp")
57                 }
58                 if x == "\r" {
59                         x = "\\r" // occurs often and more readable than \x0D
60                 } else {
61                         x = fmt.Sprintf("\\x%02X", x[0])
62                 }
63                 return ColorString(isTTY, ColorMagenta, x)
64         })
65 }