MCPcopy Create free account
hub / github.com/pmezard/go-difflib / WriteUnifiedDiff

Function WriteUnifiedDiff

difflib/difflib.go:559–632  ·  view source on GitHub ↗

Compare two sequences of lines; generate the delta as a unified diff. Unified diffs are a compact way of showing line changes and a few lines of context. The number of context lines is set by 'n' which defaults to three. By default, the diff control lines (those with ---, +++, or @@) are created

(writer io.Writer, diff UnifiedDiff)

Source from the content-addressed store, hash-verified

557// 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
558// The modification times are normally expressed in the ISO 8601 format.
559func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error {
560 buf := bufio.NewWriter(writer)
561 defer buf.Flush()
562 wf := func(format string, args ...interface{}) error {
563 _, err := buf.WriteString(fmt.Sprintf(format, args...))
564 return err
565 }
566 ws := func(s string) error {
567 _, err := buf.WriteString(s)
568 return err
569 }
570
571 if len(diff.Eol) == 0 {
572 diff.Eol = "\n"
573 }
574
575 started := false
576 m := NewMatcher(diff.A, diff.B)
577 for _, g := range m.GetGroupedOpCodes(diff.Context) {
578 if !started {
579 started = true
580 fromDate := ""
581 if len(diff.FromDate) > 0 {
582 fromDate = "\t" + diff.FromDate
583 }
584 toDate := ""
585 if len(diff.ToDate) > 0 {
586 toDate = "\t" + diff.ToDate
587 }
588 if diff.FromFile != "" || diff.ToFile != "" {
589 err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol)
590 if err != nil {
591 return err
592 }
593 err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol)
594 if err != nil {
595 return err
596 }
597 }
598 }
599 first, last := g[0], g[len(g)-1]
600 range1 := formatRangeUnified(first.I1, last.I2)
601 range2 := formatRangeUnified(first.J1, last.J2)
602 if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil {
603 return err
604 }
605 for _, c := range g {
606 i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
607 if c.Tag == 'e' {
608 for _, line := range diff.A[i1:i2] {
609 if err := ws(" " + line); err != nil {
610 return err
611 }
612 }
613 continue
614 }
615 if c.Tag == 'r' || c.Tag == 'd' {
616 for _, line := range diff.A[i1:i2] {

Callers 1

GetUnifiedDiffStringFunction · 0.85

Calls 3

NewMatcherFunction · 0.85
formatRangeUnifiedFunction · 0.85
GetGroupedOpCodesMethod · 0.80

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…