fix: Treat a quote after an even number of backslashes as unescaped. (#138) `findQuote` treated any quote preceded by a backslash as escaped, so in `"\\"` the closing quote didn't end the string. With `block=yes`, keep-sorted then kept grouping lines until it found another quote, gluing unrelated elements into one line group (which then never got sorted). Count the consecutive backslashes before a quote instead: the quote is escaped only if there's an odd number of them. New test: `TestLineGrouping/Block_EscapedBackslashBeforeQuote`, which fails without the fix. Internal regression test (~230k files using keep-sorted): the only differences were 6 files that are reported as sorted today and would be re-sorted. Each contains `"\\"` or `'\\'` inside a `block=yes` block, so the current version glues the following lines into one group and never sorts them; the new order is correct. This is the first of two PRs splitting up a fix for https://github.com/google/keep-sorted/issues/33; the second (trailing comments, blank lines, and split string literals in comma-separated lists) builds on it.
diff --git a/keepsorted/keep_sorted_test.go b/keepsorted/keep_sorted_test.go index fb397f2..878d729 100644 --- a/keepsorted/keep_sorted_test.go +++ b/keepsorted/keep_sorted_test.go
@@ -1593,6 +1593,21 @@ }, }, { + name: "Block_EscapedBackslashBeforeQuote", + opts: blockOptions{ + Block: true, + }, + + want: []lineGroupContent{ + {lines: []string{ + `foo("\\")`, + }}, + {lines: []string{ + "bar", + }}, + }, + }, + { name: "Block_IgnoresQuotesWithinQuotes", opts: blockOptions{ Block: true,
diff --git a/keepsorted/line_group.go b/keepsorted/line_group.go index 3afb005..acf538c 100644 --- a/keepsorted/line_group.go +++ b/keepsorted/line_group.go
@@ -388,7 +388,7 @@ if len(s[i:]) < len(q) { continue } - if len(q) == 1 && i > 0 && string(s[i-1]) == `\` { + if len(q) == 1 && isEscaped(s, i) { // Ignore quote literals (\", \', \`) continue } @@ -399,6 +399,16 @@ return "" } +// isEscaped reports whether the byte at index i in s is escaped by an odd +// number of preceding backslashes. +func isEscaped(s string, i int) bool { + escaped := false + for j := i - 1; j >= 0 && s[j] == '\\'; j-- { + escaped = !escaped + } + return escaped +} + func (lg *lineGroup) append(s string) { lg.access = accessRecorder{} lg.lines[len(lg.lines)-1] = lg.lines[len(lg.lines)-1] + s