code review changes
gammazero committed
Jan 14, 2021 at 02:29 UTC
20132a83eff4e6acccb78f2ca53bf152e8b56a7e
2 files changed
+52
-3
core/commands/cmdenv/env.go
+4
-3
@@ -72,10 +72,11 @@ func GetConfigRoot(env cmds.Environment) (string, error) {
72
return ctx.ConfigRoot, nil
73
}
74
75
-// EscNonPrint converts non-printable characters and backslash into Go
76
-// escape sequences, if the given string contains any.
75
+// EscNonPrint converts non-printable characters and backslash into Go escape
76
+// sequences. This is done to display all characters in a string, including
77
+// those that would otherwise not be displayed or have an undesirable effect on
78
+// the display.
79
func EscNonPrint(s string) string {
78
- // First see if escaping is needed, to avoid creating garbage.
80
if !needEscape(s) {
81
return s
82
}
core/commands/cmdenv/env_test.go
new
+48
@@ -0,0 +1,48 @@
1
+package cmdenv
2
+
3
+import (
4
+ "strconv"
5
+ "testing"
6
+)
7
+
8
+func TestEscNonPrint(t *testing.T) {
9
+ b := []byte("hello")
10
+ b[2] = 0x7f
11
+ s := string(b)
12
+ if !needEscape(s) {
13
+ t.Fatal("string needs escaping")
14
+ }
15
+ if !hasNonPrintable(s) {
16
+ t.Fatal("expected non-printable")
17
+ }
18
+ if hasNonPrintable(EscNonPrint(s)) {
19
+ t.Fatal("escaped string has non-printable")
20
+ }
21
+ if EscNonPrint(`hel\lo`) != `hel\\lo` {
22
+ t.Fatal("backslash not escaped")
23
+ }
24
+
25
+ s = `hello`
26
+ if needEscape(s) {
27
+ t.Fatal("string does not need escaping")
28
+ }
29
+ if EscNonPrint(s) != s {
30
+ t.Fatal("string should not have changed")
31
+ }
32
+ s = `"hello"`
33
+ if EscNonPrint(s) != s {
34
+ t.Fatal("string should not have changed")
35
+ }
36
+ if EscNonPrint(`"hel\"lo"`) != `"hel\\"lo"` {
37
+ t.Fatal("did not get expected escaped string")
38
+ }
39
+}
40
+
41
+func hasNonPrintable(s string) bool {
42
+ for _, r := range s {
43
+ if !strconv.IsPrint(r) {
44
+ return true
45
+ }
46
+ }
47
+ return false
48
+}