X-Git-Url: https://ruderich.org/simon/gitweb/?a=blobdiff_plain;f=cmd%2Fsafcm%2Fterm.go;fp=cmd%2Fsafcm%2Fterm.go;h=d7568e47c4d6dd7b80576011d1aa19e446bb14ba;hb=f2f2bc47e8729548f3c10117f7f008b547c4afc5;hp=0000000000000000000000000000000000000000;hpb=dc0d431a778a50e6732b9eb91384a07a207b772d;p=safcm%2Fsafcm.git diff --git a/cmd/safcm/term.go b/cmd/safcm/term.go new file mode 100644 index 0000000..d7568e4 --- /dev/null +++ b/cmd/safcm/term.go @@ -0,0 +1,76 @@ +// Functions for terminal output + +// Copyright (C) 2021 Simon Ruderich +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +package main + +import ( + "fmt" + "regexp" +) + +type Color int + +const ( + _ Color = iota + ColorRed + ColorGreen + ColorCyan + ColorMagenta +) + +func ColorString(isTTY bool, color Color, x string) string { + if !isTTY { + return x + } + + var code string + switch color { + case ColorRed: + code = "31" + case ColorGreen: + code = "32" + case ColorMagenta: + code = "35" + case ColorCyan: + code = "36" + default: + panic(fmt.Sprintf("invalid color %v", color)) + } + // TODO: check terminal support + return "\033[" + code + "m" + x + "\033[0m" +} + +var escapeRegexp = regexp.MustCompile(`[\x00-\x08\x0B-\x1F\x7F]`) + +// EscapeControlCharacters escapes all ASCII control characters (except +// newline and tab) by replacing them with their hex value. +// +// This function must be used when displaying any input from remote hosts to +// prevent terminal escape code injections. +func EscapeControlCharacters(isTTY bool, x string) string { + return escapeRegexp.ReplaceAllStringFunc(x, func(x string) string { + if len(x) != 1 { + panic("invalid escapeRegexp") + } + if x == "\r" { + x = "\\r" // occurs often and more readable than \x0D + } else { + x = fmt.Sprintf("\\x%02X", x[0]) + } + return ColorString(isTTY, ColorMagenta, x) + }) +}