You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

652 line
19 KiB

  1. // Copyright 2022 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. //
  14. // It provides tools to compare sequences of strings and generate textual diffs.
  15. //
  16. // Maintaining `GetUnifiedDiffString` here because original repository
  17. // (https://github.com/pmezard/go-difflib) is no loger maintained.
  18. package internal
  19. import (
  20. "bufio"
  21. "bytes"
  22. "fmt"
  23. "io"
  24. "strings"
  25. )
  26. func min(a, b int) int {
  27. if a < b {
  28. return a
  29. }
  30. return b
  31. }
  32. func max(a, b int) int {
  33. if a > b {
  34. return a
  35. }
  36. return b
  37. }
  38. func calculateRatio(matches, length int) float64 {
  39. if length > 0 {
  40. return 2.0 * float64(matches) / float64(length)
  41. }
  42. return 1.0
  43. }
  44. type Match struct {
  45. A int
  46. B int
  47. Size int
  48. }
  49. type OpCode struct {
  50. Tag byte
  51. I1 int
  52. I2 int
  53. J1 int
  54. J2 int
  55. }
  56. // SequenceMatcher compares sequence of strings. The basic
  57. // algorithm predates, and is a little fancier than, an algorithm
  58. // published in the late 1980's by Ratcliff and Obershelp under the
  59. // hyperbolic name "gestalt pattern matching". The basic idea is to find
  60. // the longest contiguous matching subsequence that contains no "junk"
  61. // elements (R-O doesn't address junk). The same idea is then applied
  62. // recursively to the pieces of the sequences to the left and to the right
  63. // of the matching subsequence. This does not yield minimal edit
  64. // sequences, but does tend to yield matches that "look right" to people.
  65. //
  66. // SequenceMatcher tries to compute a "human-friendly diff" between two
  67. // sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
  68. // longest *contiguous* & junk-free matching subsequence. That's what
  69. // catches peoples' eyes. The Windows(tm) windiff has another interesting
  70. // notion, pairing up elements that appear uniquely in each sequence.
  71. // That, and the method here, appear to yield more intuitive difference
  72. // reports than does diff. This method appears to be the least vulnerable
  73. // to synching up on blocks of "junk lines", though (like blank lines in
  74. // ordinary text files, or maybe "<P>" lines in HTML files). That may be
  75. // because this is the only method of the 3 that has a *concept* of
  76. // "junk" <wink>.
  77. //
  78. // Timing: Basic R-O is cubic time worst case and quadratic time expected
  79. // case. SequenceMatcher is quadratic time for the worst case and has
  80. // expected-case behavior dependent in a complicated way on how many
  81. // elements the sequences have in common; best case time is linear.
  82. type SequenceMatcher struct {
  83. a []string
  84. b []string
  85. b2j map[string][]int
  86. IsJunk func(string) bool
  87. autoJunk bool
  88. bJunk map[string]struct{}
  89. matchingBlocks []Match
  90. fullBCount map[string]int
  91. bPopular map[string]struct{}
  92. opCodes []OpCode
  93. }
  94. func NewMatcher(a, b []string) *SequenceMatcher {
  95. m := SequenceMatcher{autoJunk: true}
  96. m.SetSeqs(a, b)
  97. return &m
  98. }
  99. func NewMatcherWithJunk(a, b []string, autoJunk bool,
  100. isJunk func(string) bool,
  101. ) *SequenceMatcher {
  102. m := SequenceMatcher{IsJunk: isJunk, autoJunk: autoJunk}
  103. m.SetSeqs(a, b)
  104. return &m
  105. }
  106. // Set two sequences to be compared.
  107. func (m *SequenceMatcher) SetSeqs(a, b []string) {
  108. m.SetSeq1(a)
  109. m.SetSeq2(b)
  110. }
  111. // Set the first sequence to be compared. The second sequence to be compared is
  112. // not changed.
  113. //
  114. // SequenceMatcher computes and caches detailed information about the second
  115. // sequence, so if you want to compare one sequence S against many sequences,
  116. // use .SetSeq2(s) once and call .SetSeq1(x) repeatedly for each of the other
  117. // sequences.
  118. //
  119. // See also SetSeqs() and SetSeq2().
  120. func (m *SequenceMatcher) SetSeq1(a []string) {
  121. if &a == &m.a {
  122. return
  123. }
  124. m.a = a
  125. m.matchingBlocks = nil
  126. m.opCodes = nil
  127. }
  128. // Set the second sequence to be compared. The first sequence to be compared is
  129. // not changed.
  130. func (m *SequenceMatcher) SetSeq2(b []string) {
  131. if &b == &m.b {
  132. return
  133. }
  134. m.b = b
  135. m.matchingBlocks = nil
  136. m.opCodes = nil
  137. m.fullBCount = nil
  138. m.chainB()
  139. }
  140. func (m *SequenceMatcher) chainB() {
  141. // Populate line -> index mapping
  142. b2j := map[string][]int{}
  143. for i, s := range m.b {
  144. indices := b2j[s]
  145. indices = append(indices, i)
  146. b2j[s] = indices
  147. }
  148. // Purge junk elements
  149. m.bJunk = map[string]struct{}{}
  150. if m.IsJunk != nil {
  151. junk := m.bJunk
  152. for s := range b2j {
  153. if m.IsJunk(s) {
  154. junk[s] = struct{}{}
  155. }
  156. }
  157. for s := range junk {
  158. delete(b2j, s)
  159. }
  160. }
  161. // Purge remaining popular elements
  162. popular := map[string]struct{}{}
  163. n := len(m.b)
  164. if m.autoJunk && n >= 200 {
  165. ntest := n/100 + 1
  166. for s, indices := range b2j {
  167. if len(indices) > ntest {
  168. popular[s] = struct{}{}
  169. }
  170. }
  171. for s := range popular {
  172. delete(b2j, s)
  173. }
  174. }
  175. m.bPopular = popular
  176. m.b2j = b2j
  177. }
  178. func (m *SequenceMatcher) isBJunk(s string) bool {
  179. _, ok := m.bJunk[s]
  180. return ok
  181. }
  182. // Find longest matching block in a[alo:ahi] and b[blo:bhi].
  183. //
  184. // If IsJunk is not defined:
  185. //
  186. // Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
  187. // alo <= i <= i+k <= ahi
  188. // blo <= j <= j+k <= bhi
  189. // and for all (i',j',k') meeting those conditions,
  190. // k >= k'
  191. // i <= i'
  192. // and if i == i', j <= j'
  193. //
  194. // In other words, of all maximal matching blocks, return one that
  195. // starts earliest in a, and of all those maximal matching blocks that
  196. // start earliest in a, return the one that starts earliest in b.
  197. //
  198. // If IsJunk is defined, first the longest matching block is
  199. // determined as above, but with the additional restriction that no
  200. // junk element appears in the block. Then that block is extended as
  201. // far as possible by matching (only) junk elements on both sides. So
  202. // the resulting block never matches on junk except as identical junk
  203. // happens to be adjacent to an "interesting" match.
  204. //
  205. // If no blocks match, return (alo, blo, 0).
  206. func (m *SequenceMatcher) findLongestMatch(alo, ahi, blo, bhi int) Match {
  207. // CAUTION: stripping common prefix or suffix would be incorrect.
  208. // E.g.,
  209. // ab
  210. // acab
  211. // Longest matching block is "ab", but if common prefix is
  212. // stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
  213. // strip, so ends up claiming that ab is changed to acab by
  214. // inserting "ca" in the middle. That's minimal but unintuitive:
  215. // "it's obvious" that someone inserted "ac" at the front.
  216. // Windiff ends up at the same place as diff, but by pairing up
  217. // the unique 'b's and then matching the first two 'a's.
  218. besti, bestj, bestsize := alo, blo, 0
  219. // find longest junk-free match
  220. // during an iteration of the loop, j2len[j] = length of longest
  221. // junk-free match ending with a[i-1] and b[j]
  222. j2len := map[int]int{}
  223. for i := alo; i != ahi; i++ {
  224. // look at all instances of a[i] in b; note that because
  225. // b2j has no junk keys, the loop is skipped if a[i] is junk
  226. newj2len := map[int]int{}
  227. for _, j := range m.b2j[m.a[i]] {
  228. // a[i] matches b[j]
  229. if j < blo {
  230. continue
  231. }
  232. if j >= bhi {
  233. break
  234. }
  235. k := j2len[j-1] + 1
  236. newj2len[j] = k
  237. if k > bestsize {
  238. besti, bestj, bestsize = i-k+1, j-k+1, k
  239. }
  240. }
  241. j2len = newj2len
  242. }
  243. // Extend the best by non-junk elements on each end. In particular,
  244. // "popular" non-junk elements aren't in b2j, which greatly speeds
  245. // the inner loop above, but also means "the best" match so far
  246. // doesn't contain any junk *or* popular non-junk elements.
  247. for besti > alo && bestj > blo && !m.isBJunk(m.b[bestj-1]) &&
  248. m.a[besti-1] == m.b[bestj-1] {
  249. besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
  250. }
  251. for besti+bestsize < ahi && bestj+bestsize < bhi &&
  252. !m.isBJunk(m.b[bestj+bestsize]) &&
  253. m.a[besti+bestsize] == m.b[bestj+bestsize] {
  254. bestsize++
  255. }
  256. // Now that we have a wholly interesting match (albeit possibly
  257. // empty!), we may as well suck up the matching junk on each
  258. // side of it too. Can't think of a good reason not to, and it
  259. // saves post-processing the (possibly considerable) expense of
  260. // figuring out what to do with it. In the case of an empty
  261. // interesting match, this is clearly the right thing to do,
  262. // because no other kind of match is possible in the regions.
  263. for besti > alo && bestj > blo && m.isBJunk(m.b[bestj-1]) &&
  264. m.a[besti-1] == m.b[bestj-1] {
  265. besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
  266. }
  267. for besti+bestsize < ahi && bestj+bestsize < bhi &&
  268. m.isBJunk(m.b[bestj+bestsize]) &&
  269. m.a[besti+bestsize] == m.b[bestj+bestsize] {
  270. bestsize++
  271. }
  272. return Match{A: besti, B: bestj, Size: bestsize}
  273. }
  274. // Return list of triples describing matching subsequences.
  275. //
  276. // Each triple is of the form (i, j, n), and means that
  277. // a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
  278. // i and in j. It's also guaranteed that if (i, j, n) and (i', j', n') are
  279. // adjacent triples in the list, and the second is not the last triple in the
  280. // list, then i+n != i' or j+n != j'. IOW, adjacent triples never describe
  281. // adjacent equal blocks.
  282. //
  283. // The last triple is a dummy, (len(a), len(b), 0), and is the only
  284. // triple with n==0.
  285. func (m *SequenceMatcher) GetMatchingBlocks() []Match {
  286. if m.matchingBlocks != nil {
  287. return m.matchingBlocks
  288. }
  289. var matchBlocks func(alo, ahi, blo, bhi int, matched []Match) []Match
  290. matchBlocks = func(alo, ahi, blo, bhi int, matched []Match) []Match {
  291. match := m.findLongestMatch(alo, ahi, blo, bhi)
  292. i, j, k := match.A, match.B, match.Size
  293. if match.Size > 0 {
  294. if alo < i && blo < j {
  295. matched = matchBlocks(alo, i, blo, j, matched)
  296. }
  297. matched = append(matched, match)
  298. if i+k < ahi && j+k < bhi {
  299. matched = matchBlocks(i+k, ahi, j+k, bhi, matched)
  300. }
  301. }
  302. return matched
  303. }
  304. matched := matchBlocks(0, len(m.a), 0, len(m.b), nil)
  305. // It's possible that we have adjacent equal blocks in the
  306. // matching_blocks list now.
  307. nonAdjacent := []Match{}
  308. i1, j1, k1 := 0, 0, 0
  309. for _, b := range matched {
  310. // Is this block adjacent to i1, j1, k1?
  311. i2, j2, k2 := b.A, b.B, b.Size
  312. if i1+k1 == i2 && j1+k1 == j2 {
  313. // Yes, so collapse them -- this just increases the length of
  314. // the first block by the length of the second, and the first
  315. // block so lengthened remains the block to compare against.
  316. k1 += k2
  317. } else {
  318. // Not adjacent. Remember the first block (k1==0 means it's
  319. // the dummy we started with), and make the second block the
  320. // new block to compare against.
  321. if k1 > 0 {
  322. nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
  323. }
  324. i1, j1, k1 = i2, j2, k2
  325. }
  326. }
  327. if k1 > 0 {
  328. nonAdjacent = append(nonAdjacent, Match{i1, j1, k1})
  329. }
  330. nonAdjacent = append(nonAdjacent, Match{len(m.a), len(m.b), 0})
  331. m.matchingBlocks = nonAdjacent
  332. return m.matchingBlocks
  333. }
  334. // Return list of 5-tuples describing how to turn a into b.
  335. //
  336. // Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
  337. // has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
  338. // tuple preceding it, and likewise for j1 == the previous j2.
  339. //
  340. // The tags are characters, with these meanings:
  341. //
  342. // 'r' (replace): a[i1:i2] should be replaced by b[j1:j2]
  343. //
  344. // 'd' (delete): a[i1:i2] should be deleted, j1==j2 in this case.
  345. //
  346. // 'i' (insert): b[j1:j2] should be inserted at a[i1:i1], i1==i2 in this case.
  347. //
  348. // 'e' (equal): a[i1:i2] == b[j1:j2]
  349. func (m *SequenceMatcher) GetOpCodes() []OpCode {
  350. if m.opCodes != nil {
  351. return m.opCodes
  352. }
  353. i, j := 0, 0
  354. matching := m.GetMatchingBlocks()
  355. opCodes := make([]OpCode, 0, len(matching))
  356. for _, m := range matching {
  357. // invariant: we've pumped out correct diffs to change
  358. // a[:i] into b[:j], and the next matching block is
  359. // a[ai:ai+size] == b[bj:bj+size]. So we need to pump
  360. // out a diff to change a[i:ai] into b[j:bj], pump out
  361. // the matching block, and move (i,j) beyond the match
  362. ai, bj, size := m.A, m.B, m.Size
  363. tag := byte(0)
  364. if i < ai && j < bj {
  365. tag = 'r'
  366. } else if i < ai {
  367. tag = 'd'
  368. } else if j < bj {
  369. tag = 'i'
  370. }
  371. if tag > 0 {
  372. opCodes = append(opCodes, OpCode{tag, i, ai, j, bj})
  373. }
  374. i, j = ai+size, bj+size
  375. // the list of matching blocks is terminated by a
  376. // sentinel with size 0
  377. if size > 0 {
  378. opCodes = append(opCodes, OpCode{'e', ai, i, bj, j})
  379. }
  380. }
  381. m.opCodes = opCodes
  382. return m.opCodes
  383. }
  384. // Isolate change clusters by eliminating ranges with no changes.
  385. //
  386. // Return a generator of groups with up to n lines of context.
  387. // Each group is in the same format as returned by GetOpCodes().
  388. func (m *SequenceMatcher) GetGroupedOpCodes(n int) [][]OpCode {
  389. if n < 0 {
  390. n = 3
  391. }
  392. codes := m.GetOpCodes()
  393. if len(codes) == 0 {
  394. codes = []OpCode{{'e', 0, 1, 0, 1}}
  395. }
  396. // Fixup leading and trailing groups if they show no changes.
  397. if codes[0].Tag == 'e' {
  398. c := codes[0]
  399. i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
  400. codes[0] = OpCode{c.Tag, max(i1, i2-n), i2, max(j1, j2-n), j2}
  401. }
  402. if codes[len(codes)-1].Tag == 'e' {
  403. c := codes[len(codes)-1]
  404. i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
  405. codes[len(codes)-1] = OpCode{c.Tag, i1, min(i2, i1+n), j1, min(j2, j1+n)}
  406. }
  407. nn := n + n
  408. groups := [][]OpCode{}
  409. group := []OpCode{}
  410. for _, c := range codes {
  411. i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
  412. // End the current group and start a new one whenever
  413. // there is a large range with no changes.
  414. if c.Tag == 'e' && i2-i1 > nn {
  415. group = append(group, OpCode{
  416. c.Tag, i1, min(i2, i1+n),
  417. j1, min(j2, j1+n),
  418. })
  419. groups = append(groups, group)
  420. group = []OpCode{}
  421. i1, j1 = max(i1, i2-n), max(j1, j2-n)
  422. }
  423. group = append(group, OpCode{c.Tag, i1, i2, j1, j2})
  424. }
  425. if len(group) > 0 && !(len(group) == 1 && group[0].Tag == 'e') {
  426. groups = append(groups, group)
  427. }
  428. return groups
  429. }
  430. // Return a measure of the sequences' similarity (float in [0,1]).
  431. //
  432. // Where T is the total number of elements in both sequences, and
  433. // M is the number of matches, this is 2.0*M / T.
  434. // Note that this is 1 if the sequences are identical, and 0 if
  435. // they have nothing in common.
  436. //
  437. // .Ratio() is expensive to compute if you haven't already computed
  438. // .GetMatchingBlocks() or .GetOpCodes(), in which case you may
  439. // want to try .QuickRatio() or .RealQuickRation() first to get an
  440. // upper bound.
  441. func (m *SequenceMatcher) Ratio() float64 {
  442. matches := 0
  443. for _, m := range m.GetMatchingBlocks() {
  444. matches += m.Size
  445. }
  446. return calculateRatio(matches, len(m.a)+len(m.b))
  447. }
  448. // Return an upper bound on ratio() relatively quickly.
  449. //
  450. // This isn't defined beyond that it is an upper bound on .Ratio(), and
  451. // is faster to compute.
  452. func (m *SequenceMatcher) QuickRatio() float64 {
  453. // viewing a and b as multisets, set matches to the cardinality
  454. // of their intersection; this counts the number of matches
  455. // without regard to order, so is clearly an upper bound
  456. if m.fullBCount == nil {
  457. m.fullBCount = map[string]int{}
  458. for _, s := range m.b {
  459. m.fullBCount[s]++
  460. }
  461. }
  462. // avail[x] is the number of times x appears in 'b' less the
  463. // number of times we've seen it in 'a' so far ... kinda
  464. avail := map[string]int{}
  465. matches := 0
  466. for _, s := range m.a {
  467. n, ok := avail[s]
  468. if !ok {
  469. n = m.fullBCount[s]
  470. }
  471. avail[s] = n - 1
  472. if n > 0 {
  473. matches++
  474. }
  475. }
  476. return calculateRatio(matches, len(m.a)+len(m.b))
  477. }
  478. // Return an upper bound on ratio() very quickly.
  479. //
  480. // This isn't defined beyond that it is an upper bound on .Ratio(), and
  481. // is faster to compute than either .Ratio() or .QuickRatio().
  482. func (m *SequenceMatcher) RealQuickRatio() float64 {
  483. la, lb := len(m.a), len(m.b)
  484. return calculateRatio(min(la, lb), la+lb)
  485. }
  486. // Convert range to the "ed" format
  487. func formatRangeUnified(start, stop int) string {
  488. // Per the diff spec at http://www.unix.org/single_unix_specification/
  489. beginning := start + 1 // lines start numbering with one
  490. length := stop - start
  491. if length == 1 {
  492. return fmt.Sprintf("%d", beginning)
  493. }
  494. if length == 0 {
  495. beginning-- // empty ranges begin at line just before the range
  496. }
  497. return fmt.Sprintf("%d,%d", beginning, length)
  498. }
  499. // Unified diff parameters
  500. type UnifiedDiff struct {
  501. A []string // First sequence lines
  502. FromFile string // First file name
  503. FromDate string // First file time
  504. B []string // Second sequence lines
  505. ToFile string // Second file name
  506. ToDate string // Second file time
  507. Eol string // Headers end of line, defaults to LF
  508. Context int // Number of context lines
  509. }
  510. // Compare two sequences of lines; generate the delta as a unified diff.
  511. //
  512. // Unified diffs are a compact way of showing line changes and a few
  513. // lines of context. The number of context lines is set by 'n' which
  514. // defaults to three.
  515. //
  516. // By default, the diff control lines (those with ---, +++, or @@) are
  517. // created with a trailing newline. This is helpful so that inputs
  518. // created from file.readlines() result in diffs that are suitable for
  519. // file.writelines() since both the inputs and outputs have trailing
  520. // newlines.
  521. //
  522. // For inputs that do not have trailing newlines, set the lineterm
  523. // argument to "" so that the output will be uniformly newline free.
  524. //
  525. // The unidiff format normally has a header for filenames and modification
  526. // times. Any or all of these may be specified using strings for
  527. // 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
  528. // The modification times are normally expressed in the ISO 8601 format.
  529. func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error {
  530. buf := bufio.NewWriter(writer)
  531. defer buf.Flush()
  532. wf := func(format string, args ...interface{}) error {
  533. _, err := buf.WriteString(fmt.Sprintf(format, args...))
  534. return err
  535. }
  536. ws := func(s string) error {
  537. _, err := buf.WriteString(s)
  538. return err
  539. }
  540. if len(diff.Eol) == 0 {
  541. diff.Eol = "\n"
  542. }
  543. started := false
  544. m := NewMatcher(diff.A, diff.B)
  545. for _, g := range m.GetGroupedOpCodes(diff.Context) {
  546. if !started {
  547. started = true
  548. fromDate := ""
  549. if len(diff.FromDate) > 0 {
  550. fromDate = "\t" + diff.FromDate
  551. }
  552. toDate := ""
  553. if len(diff.ToDate) > 0 {
  554. toDate = "\t" + diff.ToDate
  555. }
  556. if diff.FromFile != "" || diff.ToFile != "" {
  557. err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol)
  558. if err != nil {
  559. return err
  560. }
  561. err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol)
  562. if err != nil {
  563. return err
  564. }
  565. }
  566. }
  567. first, last := g[0], g[len(g)-1]
  568. range1 := formatRangeUnified(first.I1, last.I2)
  569. range2 := formatRangeUnified(first.J1, last.J2)
  570. if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil {
  571. return err
  572. }
  573. for _, c := range g {
  574. i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
  575. if c.Tag == 'e' {
  576. for _, line := range diff.A[i1:i2] {
  577. if err := ws(" " + line); err != nil {
  578. return err
  579. }
  580. }
  581. continue
  582. }
  583. if c.Tag == 'r' || c.Tag == 'd' {
  584. for _, line := range diff.A[i1:i2] {
  585. if err := ws("-" + line); err != nil {
  586. return err
  587. }
  588. }
  589. }
  590. if c.Tag == 'r' || c.Tag == 'i' {
  591. for _, line := range diff.B[j1:j2] {
  592. if err := ws("+" + line); err != nil {
  593. return err
  594. }
  595. }
  596. }
  597. }
  598. }
  599. return nil
  600. }
  601. // Like WriteUnifiedDiff but returns the diff a string.
  602. func GetUnifiedDiffString(diff UnifiedDiff) (string, error) {
  603. w := &bytes.Buffer{}
  604. err := WriteUnifiedDiff(w, diff)
  605. return w.String(), err
  606. }
  607. // Split a string on "\n" while preserving them. The output can be used
  608. // as input for UnifiedDiff and ContextDiff structures.
  609. func SplitLines(s string) []string {
  610. lines := strings.SplitAfter(s, "\n")
  611. lines[len(lines)-1] += "\n"
  612. return lines
  613. }