]> ruderich.org/simon Gitweb - safcm/safcm.git/blob - cmd/safcm/term.go
d7568e47c4d6dd7b80576011d1aa19e446bb14ba
[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.
61 //
62 // This function must be used when displaying any input from remote hosts to
63 // prevent terminal escape code injections.
64 func EscapeControlCharacters(isTTY bool, x string) string {
65         return escapeRegexp.ReplaceAllStringFunc(x, func(x string) string {
66                 if len(x) != 1 {
67                         panic("invalid escapeRegexp")
68                 }
69                 if x == "\r" {
70                         x = "\\r" // occurs often and more readable than \x0D
71                 } else {
72                         x = fmt.Sprintf("\\x%02X", x[0])
73                 }
74                 return ColorString(isTTY, ColorMagenta, x)
75         })
76 }