@cryptotaxi247 / kubo / commits / 267d6fc4f

Modify escaping

gammazero committed Jan 12, 2021 at 14:54 UTC 267d6fc4fe476afa819bb9cd40bf599e0bceb3e4
1 file changed +17 -3
core/commands/cmdenv/env.go
+17 -3
@@ -72,13 +72,27 @@ func GetConfigRoot(env cmds.Environment) (string, error) {
72 return ctx.ConfigRoot, nil
73 }
74
75 -// EscNonPrint converts control characters and non-printable characters into Go
75 +// EscNonPrint converts non-printable characters and backslash into Go
76 // escape sequences, if the given string contains any.
77 func EscNonPrint(s string) string {
78 + // First see if escaping is needed, to avoid creating garbage.
79 + if !needEscape(s) {
80 + return s
81 + }
82 +
83 + esc := strconv.Quote(s)
84 + // Remove first and last quote, and unescape quotes.
85 + return strings.ReplaceAll(esc[1:len(esc)-1], `\"`, `"`)
86 +}
87 +
88 +func needEscape(s string) bool {
89 + if strings.ContainsRune(s, '\\') {
90 + return true
91 + }
92 for _, r := range s {
93 if !strconv.IsPrint(r) {
80 - return strings.Trim(strconv.Quote(s), "\"")
94 + return true
95 }
96 }
83 - return s
97 + return false
98 }