xdiff

package module
v0.0.0-...-cc0cca4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 11, 2026 License: LGPL-2.1, LGPL-2.1-or-later Imports: 13 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-xdiff

A pure-Go port of Git's xdiff for line diffs and three-way merges. It supports Myers, minimal, patience, anchored, and histogram diffs. It requires Go 1.26 or later, with no external dependencies, CGO, or Git executable.

Install

go get github.com/go-git/go-xdiff

Diff

package main

import (
	"context"
	"log"
	"os"

	"github.com/go-git/go-xdiff"
)

func main() {
	ctx := context.Background()
	result, err := xdiff.Diff(ctx, []byte("one\ntwo\n"), []byte("one\nthree\n"), nil)
	if err != nil {
		log.Fatal(err)
	}
	if err := xdiff.WriteUnified(ctx, os.Stdout, result, &xdiff.EmitOptions{Context: 3}); err != nil {
		log.Fatal(err)
	}
}

Use Options to select an algorithm, ignore whitespace, or enable the indent heuristic. Nil options select Myers without the indent heuristic.

The result provides:

  • Changes() for replacements with zero-based line offsets.
  • Chunks() for equal, delete, and insert byte ranges.
  • Hunks() for structured unified hunks.
  • Emit() for callback-based unified output without file headers.

Use the package-level WriteUnified() helper for output to an io.Writer. For custom output, pass EmitCallbacks to Emit(). EmitOptions controls grouping and formatting. EmitCallbacks controls the output destination. LineFunc receives separate prefix, content, and optional missing-newline notice parts. It receives each standard hunk header as one part. The parts and their bytes are borrowed. Do not modify or retain them.

An optional HunkHeaderFunc replaces the standard header and receives a Hunk with zero-based ranges. NoHunkHeader suppresses both header paths. LineFunc is required, even when there are no changes, unless EmitCallbacks.HunkFunc is set. Callbacks return errors to stop emission. Emit() checks cancellation before and after each callback. The caller controls colors and terminal detection.

Set EmitCallbacks.HunkFunc for range-only output without header or line callbacks. Context settings control grouping, but returned ranges exclude outer context and function expansion. Hunks() returns complete hunks without output callbacks.

Use HunkRanges() to collect the same ranges into a slice. It reuses EmitOptions but does not call FindFunc.

ranges, err := result.HunkRanges(ctx, &xdiff.EmitOptions{Context: 3})
if err != nil {
	return err
}

Merge

result, err := xdiff.Merge(ctx, base, ours, theirs, nil)
if err != nil {
	return err
}
// result.Content contains the merged bytes, including any conflict markers.
// result.Conflicts counts unresolved conflicts.

Conflicts are results, not errors. Nil options select zealous refinement. An explicit zero-valued MergeOptions selects minimal refinement. Use options to select diff3 or zdiff3 markers, labels, or automatic conflict resolution.

Examples

Run these examples from the repository root:

go run ./examples/diff       # Unified diff output.
go run ./examples/algorithms # Algorithm selection and zero-based line ranges.
go run ./examples/merge      # Clean merges and diff3 conflict markers.

Behavior

Inputs are []byte. Lines end at LF bytes. The library preserves CRLF, arbitrary bytes, and missing final newlines. It does not detect binary files.

Diff results reference the inputs. Do not modify input bytes while using a result. Options remain unchanged. Calls support context cancellation. Equal chunks retain both inputs when whitespace rules match different bytes. Blank-line and regex filters affect hunks and output, not changes or chunks. Ignore expressions use Go's regexp rules; use (?m) for line anchors. Use regexp.CompilePOSIX for POSIX ERE syntax and newline-aware matching. Exact C regex compatibility is not guaranteed: Go matches UTF-8 code points, while C character interpretation and classes depend on the locale.

See the API documentation, API examples, and benchmarks.

Development

make validate test
make reference # Requires a C compiler.

The C reference supplies comparison tests. A scheduled workflow proposes upstream updates through pull requests.

License

LGPL-2.1-or-later, with the histogram algorithm's EDL-1.0 notice. See NOTICE and the source headers. Distributors must comply with the applicable LGPL source, notice, and relinking requirements.

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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func WriteUnified

func WriteUnified(ctx context.Context, w io.Writer, result *Result, options *EmitOptions) error

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 Algorithm

type Algorithm uint8

Algorithm selects a line correspondence algorithm.

const (
	Myers Algorithm = iota
	Patience
	Histogram
)

type Change

type Change struct {
	OldStart, OldLines int
	NewStart, NewLines int
}

Change describes a replacement. Offsets are zero-based line indexes. A zero count represents an insertion or deletion at the specified offset.

type Chunk

type Chunk struct {
	Operation Operation
	Old, New  []byte
}

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 Hunk

type Hunk struct {
	Change
	Function string
	Lines    []Line
}

Hunk contains zero-based line ranges and the corresponding output lines.

type Line

type Line struct {
	Operation Operation
	Content   []byte
}

Line is an output line, including its original newline if present.

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

type MergeResult struct {
	Content   []byte
	Conflicts int
}

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 Operation

type Operation int8

Operation identifies a chunk's role.

const (
	Delete Operation = -1
	Equal  Operation = 0
	Insert Operation = 1
)

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

func Diff(ctx context.Context, old, new []byte, options *Options) (*Result, error)

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

func (r *Result) Changes() []Change

Changes returns an independent copy of the compacted edit script. Output suppression does not remove changes from this script.

func (*Result) Chunks

func (r *Result) Chunks() []Chunk

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

func (r *Result) HunkRanges(ctx context.Context, options *EmitOptions) ([]Change, error)

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

func (r *Result) Hunks(ctx context.Context, options *EmitOptions) ([]Hunk, error)

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
)

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL