MCPcopy Create free account
hub / github.com/cogentcore/core / WriteUnifiedDiff

Function WriteUnifiedDiff

texteditor/difflib/bytes/bytes.go:896–983  ·  view source on GitHub ↗

WriteUnifiedDiff compares two sequences of lines and generates 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 ---, ++

(writer io.Writer, diff UnifiedDiff)

Source from the content-addressed store, hash-verified

894// 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
895// The modification times are normally expressed in the ISO 8601 format.
896func WriteUnifiedDiff(writer io.Writer, diff UnifiedDiff) error {
897 //buf := bufio.NewWriter(writer)
898 //defer buf.Flush()
899 var bld strings.Builder
900 bld.Reset()
901 wf := func(format string, args ...interface{}) error {
902 _, err := fmt.Fprintf(&bld, format, args...)
903 return err
904 }
905 ws := func(s []byte) error {
906 _, err := bld.Write(s)
907 return err
908 }
909
910 if len(diff.Eol) == 0 {
911 diff.Eol = []byte("\n")
912 }
913
914 started := false
915 m := NewMatcher(diff.A, diff.B)
916 for _, g := range m.GetGroupedOpCodes(diff.Context) {
917 if !started {
918 started = true
919 fromDate := ""
920 if len(diff.FromDate) > 0 {
921 fromDate = "\t" + diff.FromDate
922 }
923 toDate := ""
924 if len(diff.ToDate) > 0 {
925 toDate = "\t" + diff.ToDate
926 }
927 if diff.FromFile != "" || diff.ToFile != "" {
928 err := wf("--- %s%s%s", diff.FromFile, fromDate, diff.Eol)
929 if err != nil {
930 return err
931 }
932 err = wf("+++ %s%s%s", diff.ToFile, toDate, diff.Eol)
933 if err != nil {
934 return err
935 }
936 }
937 }
938 first, last := g[0], g[len(g)-1]
939 range1 := formatRangeUnified(first.I1, last.I2)
940 range2 := formatRangeUnified(first.J1, last.J2)
941 if err := wf("@@ -%s +%s @@%s", range1, range2, diff.Eol); err != nil {
942 return err
943 }
944 for _, c := range g {
945 i1, i2, j1, j2 := c.I1, c.I2, c.J1, c.J2
946 if c.Tag == 'e' {
947 for _, line := range diff.A[i1:i2] {
948 if err := ws(SPACE); err != nil {
949 return err
950 }
951 if err := ws(line); err != nil {
952 return err
953 }

Callers 1

GetUnifiedDiffStringFunction · 0.70

Calls 8

WriteStringMethod · 0.80
NewMatcherFunction · 0.70
formatRangeUnifiedFunction · 0.70
WriteMethod · 0.65
StringMethod · 0.65
ResetMethod · 0.45
GetGroupedOpCodesMethod · 0.45
FlushMethod · 0.45

Tested by

no test coverage detected