Skip to content

Commit

Permalink
mdiff: add a Format method to the Patch type
Browse files Browse the repository at this point in the history
This is just a gloss for creating a temporary Diff to render the patch back
out, but it makes it a little nicer to read.

Update the tests to exercise it too.
  • Loading branch information
creachadair committed Sep 9, 2024
1 parent 1e30e32 commit 944e480
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
12 changes: 9 additions & 3 deletions mdiff/mdiff_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,9 @@ func TestRead(t *testing.T) {

// The output should round-trip
var buf bytes.Buffer
mdiff.Format(&buf, &mdiff.Diff{Chunks: p.Chunks}, nil)
if err := p.Format(&buf, mdiff.Format); err != nil {
t.Errorf("Format: unexpected error: %v", err)
}
if got := buf.String(); got != odiff {
t.Errorf("Read: got:\n%s\nwant:\n%s", got, odiff)
}
Expand All @@ -234,7 +236,9 @@ func TestRead(t *testing.T) {

// The output should round-trip.
var buf bytes.Buffer
mdiff.FormatUnified(&buf, &mdiff.Diff{Chunks: p.Chunks}, p.FileInfo)
if err := p.Format(&buf, mdiff.FormatUnified); err != nil {
t.Errorf("Format: unexpected error: %v", err)
}
if got := buf.String(); got != udiff {
t.Errorf("ReadUnified: got:\n%s\nwant:\n%s", got, udiff)
}
Expand Down Expand Up @@ -270,7 +274,9 @@ func TestRead(t *testing.T) {
// Render the first patch back out, it should look like the unified
// diff it came from (with the header shimmed).
var buf bytes.Buffer
mdiff.FormatUnified(&buf, &mdiff.Diff{Chunks: ps[0].Chunks}, u.FileInfo)
if err := u.Format(&buf, mdiff.FormatUnified); err != nil {
t.Errorf("Format: unexpected error: %v", err)
}
if diff := gocmp.Diff(buf.String(), udiff); diff != "" {
t.Errorf("Git patch output (-got, +want):\n%s", diff)
}
Expand Down
6 changes: 6 additions & 0 deletions mdiff/reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ type Patch struct {
Chunks []*Chunk
}

// Format renders a patch in textual format using the specified format
// function.
func (p *Patch) Format(w io.Writer, f FormatFunc) error {
return f(w, &Diff{Chunks: p.Chunks}, p.FileInfo)
}

// ReadGitPatch reads a sequence of unified diff [patches] in the format
// produced by "git diff -p" with default settings. The commit metadata and
// header lines are ignored.
Expand Down

0 comments on commit 944e480

Please sign in to comment.