]> ruderich.org/simon Gitweb - safcm/safcm.git/blob - cmd/safcm/term.go
Improve and add comments
[safcm/safcm.git] / cmd / safcm / term.go
1 // Functions for terminal output
2
3 // Copyright (C) 2021  Simon Ruderich
4 //
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 // GNU General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program.  If not, see <http://www.gnu.org/licenses/>.
17
18 package main
19
20 import (
21         "fmt"
22         "regexp"
23 )
24
25 type Color int
26
27 const (
28         _ Color = iota
29         ColorRed
30         ColorGreen
31         ColorCyan
32         ColorMagenta
33 )
34
35 func ColorString(isTTY bool, color Color, x string) string {
36         if !isTTY {
37                 return x
38         }
39
40         var code string
41         switch color {
42         case ColorRed:
43                 code = "31"
44         case ColorGreen:
45                 code = "32"
46         case ColorMagenta:
47                 code = "35"
48         case ColorCyan:
49                 code = "36"
50         default:
51                 panic(fmt.Sprintf("invalid color %v", color))
52         }
53         // TODO: check terminal support
54         return "\033[" + code + "m" + x + "\033[0m"
55 }
56
57 var escapeRegexp = regexp.MustCompile(`[\x00-\x08\x0B-\x1F\x7F]`)
58
59 // EscapeControlCharacters escapes all ASCII control characters (except
60 // newline and tab) by replacing them with their hex value. If the output is
61 // to a TTY then the escaped characters are colored.
62 //
63 // This function must be used when displaying any input from remote hosts to
64 // prevent terminal escape code injections.
65 func EscapeControlCharacters(isTTY bool, x string) string {
66         return escapeRegexp.ReplaceAllStringFunc(x, func(x string) string {
67                 if len(x) != 1 {
68                         panic("invalid escapeRegexp")
69                 }
70                 if x == "\r" {
71                         x = "\\r" // occurs often and more readable than \x0D
72                 } else {
73                         x = fmt.Sprintf("\\x%02X", x[0])
74                 }
75                 return ColorString(isTTY, ColorMagenta, x)
76         })
77 }