Skip to content

Commit

Permalink
Adjust heuristics for using raw literals (#48)
Browse files Browse the repository at this point in the history
Rather than searching for escape sequences, a better measure of whether
to use raw literals or not is whether the raw literal form is shorter
than the quoted string encoding.
The assumption is that shorter string length is more readable,
which is a reasonable (except for non-printable characters).
  • Loading branch information
dsnet committed Oct 3, 2017
1 parent 8ebdfab commit 47d4c62
Showing 1 changed file with 14 additions and 6 deletions.
20 changes: 14 additions & 6 deletions cmp/internal/value/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,14 +165,22 @@ func formatAny(v reflect.Value, conf formatConfig, visited map[uintptr]bool) str
}

func formatString(s string) string {
// Avoid performing quote-escaping if the string is already escaped.
hasEscapes := strings.ContainsAny(s, `\`)
allPrintable := strings.IndexFunc(s, unicode.IsPrint) >= 0
rawAllowed := !strings.ContainsAny(s, "`\n")
if hasEscapes && allPrintable && rawAllowed {
// Use quoted string if it the same length as a raw string literal.
// Otherwise, attempt to use the raw string form.
qs := strconv.Quote(s)
if len(qs) == 1+len(s)+1 {
return qs
}

// Disallow newlines to ensure output is a single line.
// Only allow printable runes for readability purposes.
rawInvalid := func(r rune) bool {
return r == '`' || r == '\n' || !unicode.IsPrint(r)
}
if strings.IndexFunc(s, rawInvalid) < 0 {
return "`" + s + "`"
}
return strconv.Quote(s)
return qs
}

func formatPrimitive(t reflect.Type, v interface{}, conf formatConfig) string {
Expand Down

0 comments on commit 47d4c62

Please sign in to comment.