File tree Expand file tree Collapse file tree 2 files changed +52
-3
lines changed
Expand file tree Collapse file tree 2 files changed +52
-3
lines changed Original file line number Diff line number Diff line change @@ -72,10 +72,11 @@ func GetConfigRoot(env cmds.Environment) (string, error) {
7272 return ctx .ConfigRoot , nil
7373}
7474
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.
7779func EscNonPrint (s string ) string {
78- // First see if escaping is needed, to avoid creating garbage.
7980 if ! needEscape (s ) {
8081 return s
8182 }
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments