Documentation
¶
Overview ¶
Package xdiff implements Git's line-oriented diff and three-way merge algorithms in pure Go.
Inputs are arbitrary bytes. A record ends at '\n' or at the end of the input. The final newline is significant unless a whitespace option ignores it. Diff results use zero-based line offsets and retain references to the inputs. Callers must not change the inputs while they use a result.
Options are read-only. Independent calls are safe for concurrent use. Cancellation returns the context error, not a partial result.
The implementation derives from Git's xdiff. See LICENSE and NOTICE.
Index ¶
- func WriteUnified(ctx context.Context, w io.Writer, result *Result, options *EmitOptions) error
- type Algorithm
- type Change
- type Chunk
- type ConflictStyle
- type EmitCallbacks
- type EmitOptions
- type Hunk
- type Line
- type MergeFavor
- type MergeLevel
- type MergeOptions
- type MergeResult
- type Operation
- type Options
- type Result
- func (r *Result) Changes() []Change
- func (r *Result) Chunks() []Chunk
- func (r *Result) Emit(ctx context.Context, options *EmitOptions, callbacks *EmitCallbacks) error
- func (r *Result) HunkRanges(ctx context.Context, options *EmitOptions) ([]Change, error)
- func (r *Result) Hunks(ctx context.Context, options *EmitOptions) ([]Hunk, error)
- type Whitespace
Examples ¶
- Diff
- Diff (Anchors)
- Diff (Histogram)
- Diff (Minimal)
- Diff (OutputFilters)
- Diff (Patience)
- Diff (Whitespace)
- Merge
- Merge (CrlfMarkers)
- Merge (Favors)
- Merge (Levels)
- Merge (Styles)
- Result.Chunks
- Result.Emit
- Result.Emit (Colors)
- Result.Emit (CustomHeader)
- Result.Emit (NoHeader)
- Result.Emit (Ranges)
- Result.Emit (Stop)
- Result.HunkRanges
- Result.HunkRanges (Filters)
- Result.Hunks
- Result.Hunks (FindFunction)
- WriteUnified
- WriteUnified (FunctionContext)
- WriteUnified (FunctionNames)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func WriteUnified ¶
WriteUnified writes unified hunks without file headers through result.Emit. It returns writer errors and reports incomplete writes as io.ErrShortWrite.
Example ¶
result, err := Diff(context.Background(), []byte("one\nold\n"), []byte("one\nnew\n"), nil)
if err != nil {
panic(err)
}
var output bytes.Buffer
if err := WriteUnified(context.Background(), &output, result, &EmitOptions{Context: 1}); err != nil {
panic(err)
}
fmt.Print(output.String())
Output: @@ -1,2 +1,2 @@ one -old +new
Example (FunctionContext) ¶
result, err := Diff(context.Background(), []byte("@name\n old\n}\n"), []byte("@name\n new\n}\n"), nil)
if err != nil {
panic(err)
}
emit := EmitOptions{FunctionContext: true, NoHunkHeader: true,
FindFunc: func(line []byte) (string, bool) {
return strings.TrimSpace(string(line)), len(line) > 0 && line[0] == '@'
}}
var output bytes.Buffer
if err := WriteUnified(context.Background(), &output, result, &emit); err != nil {
panic(err)
}
fmt.Print(output.String())
Output: @name - old + new }
Example (FunctionNames) ¶
result, err := Diff(context.Background(), []byte("function\n old\n}\n"), []byte("function\n new\n}\n"), nil)
if err != nil {
panic(err)
}
var output bytes.Buffer
if err := WriteUnified(context.Background(), &output, result, &EmitOptions{FunctionNames: true}); err != nil {
panic(err)
}
fmt.Print(output.String())
Output: @@ -2 +2 @@ function - old + new
Types ¶
type Change ¶
Change describes a replacement. Offsets are zero-based line indexes. A zero count represents an insertion or deletion at the specified offset.
type Chunk ¶
Chunk contains input slices for one operation. Equal chunks retain both inputs because whitespace rules can match lines with different bytes. Delete chunks have no New bytes. Insert chunks have no Old bytes.
type ConflictStyle ¶
type ConflictStyle uint8
ConflictStyle selects the conflict marker format.
const ( ConflictMerge ConflictStyle = iota ConflictDiff3 ConflictZDiff3 )
type EmitCallbacks ¶
type EmitCallbacks struct {
// HunkFunc selects range-only output for Emit.
// Ranges exclude outer context but include unchanged gaps within a group.
// EmitOptions.Context and InterHunkContext control grouping.
// Emit skips function options and text callbacks in this mode.
// An error stops emission.
HunkFunc func(Change) error
// HunkHeaderFunc replaces the standard hunk header.
// When nil, LineFunc receives the formatted header as one part.
// EmitOptions.NoHunkHeader suppresses both header paths.
HunkHeaderFunc func(Hunk) error
// LineFunc receives a record's prefix, original content, and optional
// missing-newline notice as separate parts. It also receives default headers.
// Emit requires LineFunc unless HunkFunc is set.
// The parts and their bytes are borrowed:
// do not modify them or retain them after the callback returns.
LineFunc func(parts ...[]byte) error
}
EmitCallbacks receives unified output without file headers or grouped ranges. Callbacks return an error to stop emission.
type EmitOptions ¶
type EmitOptions struct {
Context, InterHunkContext int
NoHunkHeader bool
FunctionNames bool
FunctionContext bool
// FindFunc identifies a function header and its display name.
// A nil callback uses xdiff's default ASCII header detection.
FindFunc func(line []byte) (name string, ok bool)
}
EmitOptions controls hunk construction and formatting. Zero values request no context.
type MergeFavor ¶
type MergeFavor uint8
MergeFavor selects automatic conflict resolution.
const ( FavorConflict MergeFavor = iota FavorOurs FavorTheirs FavorUnion )
type MergeLevel ¶
type MergeLevel uint8
MergeLevel selects conflict refinement. The zero value is MergeMinimal.
const ( MergeMinimal MergeLevel = iota MergeEager MergeZealous MergeZealousAlnum )
type MergeOptions ¶
type MergeOptions struct {
Diff Options
Level MergeLevel
Favor MergeFavor
Style ConflictStyle
MarkerSize int
AncestorLabel, OursLabel, TheirsLabel string
}
MergeOptions controls three-way merge. Nil selects MergeZealous and seven-character markers. A non-nil options value uses Level as written.
type MergeResult ¶
MergeResult contains merged bytes and the number of unresolved conflicts. A conflict is a successful merge computation, not an error.
func Merge ¶
func Merge(ctx context.Context, base, ours, theirs []byte, options *MergeOptions) (*MergeResult, error)
Merge computes a three-way merge without changing its inputs or options. Nil options select MergeZealous and seven-character conflict markers. A conflict is not an error. Content is independent of the input slices. Labels retain embedded newlines; a NUL terminates a label, as in Git.
Example ¶
result, err := Merge(context.Background(), []byte("base\n"),
[]byte("same\nours\nend\n"), []byte("same\ntheirs\nend\n"), nil)
if err != nil {
panic(err)
}
fmt.Print(string(result.Content))
fmt.Println("conflicts:", result.Conflicts)
Output: same <<<<<<< ours ======= theirs >>>>>>> end conflicts: 1
Example (CrlfMarkers) ¶
result, err := Merge(context.Background(), []byte("base\r\n"), []byte("ours"), []byte("theirs"), nil)
if err != nil {
panic(err)
}
fmt.Printf("%q\n", result.Content)
Output: "<<<<<<<\r\nours\r\n=======\r\ntheirs\r\n>>>>>>>\r\n"
Example (Favors) ¶
for _, favor := range []MergeFavor{FavorOurs, FavorTheirs, FavorUnion} {
result, err := Merge(context.Background(), []byte("base"), []byte("ours"), []byte("theirs"),
&MergeOptions{Favor: favor})
if err != nil {
panic(err)
}
fmt.Printf("favor %d: %q, conflicts: %d\n", favor, result.Content, result.Conflicts)
}
Output: favor 1: "ours", conflicts: 0 favor 2: "theirs", conflicts: 0 favor 3: "ours\ntheirs", conflicts: 0
Example (Levels) ¶
for _, level := range []MergeLevel{MergeMinimal, MergeEager, MergeZealous, MergeZealousAlnum} {
result, err := Merge(context.Background(), []byte("base\n"), []byte("same\n"), []byte("same\n"),
&MergeOptions{Level: level})
if err != nil {
panic(err)
}
fmt.Printf("level %d, conflicts: %d\n", level, result.Conflicts)
}
Output: level 0, conflicts: 1 level 1, conflicts: 0 level 2, conflicts: 0 level 3, conflicts: 0
Example (Styles) ¶
for _, style := range []ConflictStyle{ConflictMerge, ConflictDiff3, ConflictZDiff3} {
options := &MergeOptions{Level: MergeZealous, Style: style, MarkerSize: 3,
AncestorLabel: "base", OursLabel: "left", TheirsLabel: "right"}
result, err := Merge(context.Background(), []byte("base\n"),
[]byte("same\nours\nend\n"), []byte("same\ntheirs\nend\n"), options)
if err != nil {
panic(err)
}
fmt.Printf("style %d:\n%s", style, result.Content)
}
Output: style 0: same <<< left ours === theirs >>> right end style 1: <<< left same ours end ||| base base === same theirs end >>> right style 2: same <<< left ours ||| base base === theirs >>> right end
type Options ¶
type Options struct {
Algorithm Algorithm
Minimal bool
IndentHeuristic bool
Whitespace Whitespace
// IgnoreBlankLines suppresses changes that contain only blank lines.
// It affects hunks and output, not the underlying edit script.
IgnoreBlankLines bool
// IgnoreRegex suppresses changes whose lines all match at least one
// expression. Expressions match full records, including final newlines.
// Expressions use Go regexp semantics. Use (?m) for Git-like line anchors.
// CompilePOSIX provides POSIX ERE syntax and newline-aware matching.
// Go matches UTF-8 code points; C matching depends on its locale.
IgnoreRegex []*regexp.Regexp
// Anchors are line prefixes that constrain patience diff.
Anchors []string
}
Options controls diff computation. A nil pointer selects the zero values.
type Result ¶
type Result struct {
// contains filtered or unexported fields
}
Result contains a diff and references to its input bytes. Its methods do not change the result.
func Diff ¶
Diff computes line replacements from old to new. It does not modify inputs or options. Nil options select Myers without the indent heuristic.
Example ¶
result, err := Diff(context.Background(), []byte("one\ntwo\n"), []byte("one\nthree\n"), nil)
if err != nil {
panic(err)
}
for _, change := range result.Changes() {
fmt.Printf("old %d,%d -> new %d,%d\n", change.OldStart, change.OldLines, change.NewStart, change.NewLines)
}
Output: old 1,1 -> new 1,1
Example (Anchors) ¶
opts := Options{Algorithm: Patience, Anchors: []string{"a"}}
result, err := Diff(context.Background(), []byte("a\nb\nc\n"), []byte("c\nb\na\n"), &opts)
if err != nil {
panic(err)
}
fmt.Println(result.Changes())
Output: [{0 0 0 2} {1 2 3 0}]
Example (Histogram) ¶
opts := Options{Algorithm: Histogram}
result, err := Diff(context.Background(), []byte("one\ntwo\n"), []byte("one\nthree\n"), &opts)
if err != nil {
panic(err)
}
fmt.Println(result.Changes())
Output: [{1 1 1 1}]
Example (Minimal) ¶
package main
import (
"context"
"fmt"
"github.com/go-git/go-xdiff"
)
func main() {
result, err := xdiff.Diff(context.Background(), []byte("a\nb\n"), []byte("b\na\n"),
&xdiff.Options{Minimal: true})
if err != nil {
panic(err)
}
deleted, inserted := 0, 0
for _, change := range result.Changes() {
deleted += change.OldLines
inserted += change.NewLines
}
fmt.Println(deleted, "deleted,", inserted, "inserted")
}
Output: 1 deleted, 1 inserted
Example (OutputFilters) ¶
opts := Options{Whitespace: IgnoreAllSpace, IgnoreBlankLines: true,
IgnoreRegex: []*regexp.Regexp{regexp.MustCompile("^timestamp:")}}
result, err := Diff(context.Background(), []byte("value\n\nkeep\ntimestamp: old\n"),
[]byte(" value \nkeep\ntimestamp: new\n"), &opts)
if err != nil {
panic(err)
}
hunks, err := result.Hunks(context.Background(), nil)
if err != nil {
panic(err)
}
fmt.Println("Changes:", len(result.Changes()))
fmt.Println("Hunks:", len(hunks))
Output: Changes: 2 Hunks: 0
Example (Patience) ¶
opts := Options{Algorithm: Patience}
result, err := Diff(context.Background(), []byte("a\nb\nc\n"), []byte("c\nb\na\n"), &opts)
if err != nil {
panic(err)
}
fmt.Println(result.Changes())
Output: [{0 2 0 0} {3 0 1 2}]
Example (Whitespace) ¶
package main
import (
"context"
"fmt"
"github.com/go-git/go-xdiff"
)
func main() {
for _, mode := range []xdiff.Whitespace{
xdiff.IgnoreAllSpace, xdiff.IgnoreSpaceChange, xdiff.IgnoreSpaceAtEOL, xdiff.IgnoreCRAtEOL,
} {
result, err := xdiff.Diff(context.Background(), []byte("line\r\n"), []byte("line\n"),
&xdiff.Options{Whitespace: mode})
if err != nil {
panic(err)
}
fmt.Println(len(result.Changes()))
}
}
Output: 0 0 0 0
func (*Result) Changes ¶
Changes returns an independent copy of the compacted edit script. Output suppression does not remove changes from this script.
func (*Result) Chunks ¶
Chunks returns equal, delete, and insert chunks in source order. Each chunk refers to the original input bytes.
Example ¶
package main
import (
"context"
"fmt"
"github.com/go-git/go-xdiff"
)
func main() {
result, err := xdiff.Diff(context.Background(), []byte("one\ntwo\n"), []byte("one\nthree\n"), nil)
if err != nil {
panic(err)
}
for _, chunk := range result.Chunks() {
// A patch adapter uses destination bytes for unchanged context.
content := chunk.New
if chunk.Operation == xdiff.Delete {
content = chunk.Old
}
fmt.Printf("%d %q\n", chunk.Operation, content)
}
}
Output: 0 "one\n" -1 "two\n" 1 "three\n"
func (*Result) Emit ¶
func (r *Result) Emit(ctx context.Context, options *EmitOptions, callbacks *EmitCallbacks) error
Emit sends unified output without file headers to callbacks. When callbacks.HunkFunc is set, it reports grouped ranges instead. Otherwise, it requires LineFunc even when the result has no changes. It checks cancellation before and after each callback.
Example ¶
package main
import (
"bytes"
"context"
"fmt"
"github.com/go-git/go-xdiff"
)
func main() {
result, err := xdiff.Diff(context.Background(), []byte("old\n"), []byte("new\n"), nil)
if err != nil {
panic(err)
}
var output bytes.Buffer
err = result.Emit(context.Background(), nil, &xdiff.EmitCallbacks{
LineFunc: func(parts ...[]byte) error {
for _, part := range parts {
output.Write(part)
}
return nil
},
})
if err != nil {
panic(err)
}
fmt.Print(output.String())
}
Output: @@ -1 +1 @@ -old +new
Example (Colors) ¶
package main
import (
"bytes"
"context"
"fmt"
"github.com/go-git/go-xdiff"
)
func main() {
result, err := xdiff.Diff(context.Background(), []byte("old\n"), []byte("new\n"), nil)
if err != nil {
panic(err)
}
var output bytes.Buffer
err = result.Emit(context.Background(), nil, &xdiff.EmitCallbacks{
LineFunc: func(parts ...[]byte) error {
color := "\x1b[36m"
switch parts[0][0] {
case '-':
color = "\x1b[31m"
case '+':
color = "\x1b[32m"
}
output.WriteString(color)
for _, part := range parts {
output.Write(part)
}
output.WriteString("\x1b[0m")
return nil
},
})
if err != nil {
panic(err)
}
fmt.Printf("%q\n", output.String())
}
Output: "\x1b[36m@@ -1 +1 @@\n\x1b[0m\x1b[31m-old\n\x1b[0m\x1b[32m+new\n\x1b[0m"
Example (CustomHeader) ¶
package main
import (
"bytes"
"context"
"fmt"
"github.com/go-git/go-xdiff"
)
func main() {
result, err := xdiff.Diff(context.Background(), []byte("old"), []byte("new"), nil)
if err != nil {
panic(err)
}
var output bytes.Buffer
err = result.Emit(context.Background(), nil, &xdiff.EmitCallbacks{
HunkHeaderFunc: func(h xdiff.Hunk) error {
_, err := fmt.Fprintf(&output, "old=%d new=%d\n", h.OldLines, h.NewLines)
return err
},
LineFunc: func(parts ...[]byte) error {
for _, part := range parts {
output.Write(part)
}
return nil
},
})
if err != nil {
panic(err)
}
fmt.Print(output.String())
}
Output: old=1 new=1 -old \ No newline at end of file +new \ No newline at end of file
Example (NoHeader) ¶
package main
import (
"bytes"
"context"
"fmt"
"github.com/go-git/go-xdiff"
)
func main() {
result, err := xdiff.Diff(context.Background(), []byte("old\n"), []byte("new\n"), nil)
if err != nil {
panic(err)
}
var output bytes.Buffer
err = result.Emit(context.Background(), &xdiff.EmitOptions{NoHunkHeader: true}, &xdiff.EmitCallbacks{
LineFunc: func(parts ...[]byte) error {
for _, part := range parts {
output.Write(part)
}
return nil
},
})
if err != nil {
panic(err)
}
fmt.Print(output.String())
}
Output: -old +new
Example (Ranges) ¶
package main
import (
"context"
"fmt"
"github.com/go-git/go-xdiff"
)
func main() {
result, err := xdiff.Diff(context.Background(),
[]byte("head\nold-one\nsame\nold-two\ntail\n"),
[]byte("head\nnew-one\nsame\nnew-two\ntail\n"), nil)
if err != nil {
panic(err)
}
err = result.Emit(context.Background(), &xdiff.EmitOptions{Context: 1}, &xdiff.EmitCallbacks{
HunkFunc: func(change xdiff.Change) error {
_, err := fmt.Printf("old=[%d,%d) new=[%d,%d)\n",
change.OldStart, change.OldStart+change.OldLines,
change.NewStart, change.NewStart+change.NewLines)
return err
},
})
if err != nil {
panic(err)
}
}
Output: old=[1,4) new=[1,4)
Example (Stop) ¶
package main
import (
"context"
"errors"
"fmt"
"github.com/go-git/go-xdiff"
)
func main() {
result, err := xdiff.Diff(context.Background(), []byte("old\nsame\nold\n"), []byte("new\nsame\nnew\n"), nil)
if err != nil {
panic(err)
}
stop := errors.New("stop")
calls := 0
err = result.Emit(context.Background(), nil, &xdiff.EmitCallbacks{
HunkFunc: func(xdiff.Change) error {
calls++
return stop
},
})
fmt.Println("calls:", calls)
fmt.Println("stopped:", errors.Is(err, stop))
}
Output: calls: 1 stopped: true
func (*Result) HunkRanges ¶
HunkRanges returns filtered, grouped changes without outer context. Ranges can include unchanged lines between changes. Only Context and InterHunkContext affect range construction. HunkRanges does not call FindFunc.
Example ¶
package main
import (
"context"
"fmt"
"github.com/go-git/go-xdiff"
)
func main() {
result, err := xdiff.Diff(context.Background(),
[]byte("head\nold-one\nsame\nold-two\ntail\n"),
[]byte("head\nnew-one\nsame\nnew-two\ntail\n"), nil)
if err != nil {
panic(err)
}
ranges, err := result.HunkRanges(context.Background(), &xdiff.EmitOptions{Context: 1})
if err != nil {
panic(err)
}
fmt.Println(ranges)
}
Output: [{1 3 1 3}]
Example (Filters) ¶
package main
import (
"context"
"fmt"
"regexp"
"github.com/go-git/go-xdiff"
)
func main() {
result, err := xdiff.Diff(context.Background(),
[]byte("head\n\nkeep\ntimestamp: old\nsame\nold\n"),
[]byte("head\nkeep\ntimestamp: new\nsame\nnew\n"),
&xdiff.Options{IgnoreBlankLines: true,
IgnoreRegex: []*regexp.Regexp{regexp.MustCompile("^timestamp:")}})
if err != nil {
panic(err)
}
ranges, err := result.HunkRanges(context.Background(), nil)
if err != nil {
panic(err)
}
fmt.Println("raw changes:", len(result.Changes()))
fmt.Println("ranges:", ranges)
}
Output: raw changes: 3 ranges: [{5 1 4 1}]
func (*Result) Hunks ¶
Hunks returns unified hunks whose line contents refer to the original inputs. NoHunkHeader affects Emit and WriteUnified only.
Example ¶
result, err := Diff(context.Background(), []byte("a\nb\nc\nd\ne\n"), []byte("A\nb\nc\nd\nE\n"), nil)
if err != nil {
panic(err)
}
hunks, err := result.Hunks(context.Background(), &EmitOptions{Context: 1, InterHunkContext: 1})
if err != nil {
panic(err)
}
for _, hunk := range hunks {
fmt.Println(hunk.Change)
}
Output: {0 5 0 5}
Example (FindFunction) ¶
result, err := Diff(context.Background(), []byte("@name\n old\n}\n"), []byte("@name\n new\n}\n"), nil)
if err != nil {
panic(err)
}
hunks, err := result.Hunks(context.Background(), &EmitOptions{
FunctionNames: true,
FindFunc: func(line []byte) (string, bool) {
return "custom name", bytes.HasPrefix(line, []byte("@"))
},
})
if err != nil {
panic(err)
}
fmt.Println(hunks[0].Function)
Output: custom name
type Whitespace ¶
type Whitespace uint8
Whitespace selects line comparison rules. The zero value compares all bytes. If several flags are set, the first applicable rule in this list takes precedence: IgnoreAllSpace, IgnoreSpaceChange, IgnoreSpaceAtEOL, IgnoreCRAtEOL.
const ( IgnoreAllSpace Whitespace = 1 << iota IgnoreSpaceChange IgnoreSpaceAtEOL IgnoreCRAtEOL )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
algorithms
command
|
|
|
diff
command
|
|
|
merge
command
|
|
|
internal
|
|
|
testref
Package testref runs the pinned C xdiff implementation for explicit test use.
|
Package testref runs the pinned C xdiff implementation for explicit test use. |