Skip to content

streamingfast/diffx

Repository files navigation

diffx

A Go library for rendering unified diffs with ANSI coloring, line collapsing, and inline change highlighting.

Built on top of go-difflib for the diff computation.

Features

  • Simple one-line API for quick diffs
  • JSON-aware diffing with automatic key sorting and normalization
  • Unified diff output with line numbers and gutter
  • ANSI color support with auto-detection (TTY)
  • Collapses long context lines (>120 chars by default) with (+N chars) suffix
  • Highlights character-level differences within changed lines
  • Configurable via functional options

Install

go get github.com/streamingfast/diffx

Quick Start

// One-line string diff (no color)
result := diffx.Diff(before, after)

// Write to stdout (auto-detects TTY for color)
diffx.WriteDiff(os.Stdout, before, after)

// JSON diff — normalizes keys order and formatting
result, err := diffx.JSONDiff(before, after)

// JSON diff to writer
diffx.WriteJSONDiff(os.Stdout, before, after)

Usage

String diff

// Returns a plain-text diff string (no ANSI color by default).
result := diffx.Diff(oldContent, newContent)

// Force color on.
result := diffx.Diff(oldContent, newContent, diffx.WithColor(true))

Writer diff

// Writes diff to w, auto-detects color when w is a TTY.
err := diffx.WriteDiff(os.Stdout, oldContent, newContent)

JSON diff

Both inputs are unmarshaled and re-marshaled with sorted keys and consistent indentation before diffing. This makes the diff stable regardless of original key ordering.

// String version.
result, err := diffx.JSONDiff(beforeJSON, afterJSON)

// Writer version.
err := diffx.WriteJSONDiff(os.Stdout, beforeJSON, afterJSON)

Reporter (full control)

For advanced use, create a UnifiedDiffReporter directly:

reporter := diffx.NewUnifiedDiffReporter(
    diffx.WithColor(true),
    diffx.WithMaxLineLength(80),
    diffx.WithContextLines(5),
)
err := reporter.Report(os.Stdout, "expected.json", "actual.json", before, after)

Options

// Force color on/off (default: auto-detect TTY for writers, off for strings)
diffx.WithColor(true)

// Set max line length before collapsing (default: 120, 0 = disable)
diffx.WithMaxLineLength(80)

// Set number of context lines around each hunk (default: 3)
diffx.WithContextLines(5)

Color Scheme

Element Color
Gutter (no diff) Gray
Gutter (removal) Red
Gutter (addition) Green
Hunk header (@@) Gray
Context text Default
Removed line Red
Added line Green
Inline diff highlight Bold on tinted background (red/green)

Example

go run ./examples/basic

License

Apache 2.0

About

Unified diff library with unified diff prettier for console based rendering

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages