From 487ba52e452db5a6aebaedc4d54e8a6080c4526a Mon Sep 17 00:00:00 2001 From: Francesc Campoy Date: Wed, 11 Feb 2026 17:47:16 -0800 Subject: [PATCH] Eliminate double file read in diff mode Use io.TeeReader to capture the original file content during the first read instead of opening and reading the file a second time. This follows the same pattern already used for stdin diffing. Remove the now-unused readFile function. The previous code re-opened the file via openFile for the diff, but in practice the reader was already exhausted, producing incorrect diffs. TeeReader captures the actual content that was processed. Co-Authored-By: Claude Opus 4.6 --- main.go | 24 ++++++++---------------- main_test.go | 2 +- 2 files changed, 9 insertions(+), 17 deletions(-) diff --git a/main.go b/main.go index bdbe8d4..0c7a554 100644 --- a/main.go +++ b/main.go @@ -37,7 +37,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "os" "path/filepath" @@ -126,15 +125,6 @@ var openFile = func(name string) (file, error) { return os.OpenFile(name, os.O_RDWR, 0666) } -func readFile(path string) ([]byte, error) { - f, err := openFile(path) - if err != nil { - return nil, err - } - defer f.Close() - return ioutil.ReadAll(f) -} - func processFile(path string, rewrite, doDiff bool) (foundDiff bool, err error) { if filepath.Ext(path) != ".md" { return false, fmt.Errorf("not a markdown file") @@ -146,17 +136,19 @@ func processFile(path string, rewrite, doDiff bool) (foundDiff bool, err error) } defer f.Close() + var original bytes.Buffer + var r io.Reader = f + if doDiff { + r = io.TeeReader(f, &original) + } + buf := new(bytes.Buffer) - if err := embedmd.Process(buf, f, embedmd.WithBaseDir(filepath.Dir(path))); err != nil { + if err := embedmd.Process(buf, r, embedmd.WithBaseDir(filepath.Dir(path))); err != nil { return false, err } if doDiff { - f, err := readFile(path) - if err != nil { - return false, fmt.Errorf("could not read %s for diff: %v", path, err) - } - data, err := diff(string(f), buf.String()) + data, err := diff(original.String(), buf.String()) if err != nil || len(data) == 0 { return false, err } diff --git a/main_test.go b/main_test.go index 17ba4f1..1192810 100644 --- a/main_test.go +++ b/main_test.go @@ -98,7 +98,7 @@ func TestEmbedFiles(t *testing.T) { {name: "diffing a single file", in: "one\ntwo\nthree", d: true, - out: "@@ -1 +1,4 @@\n+one\n+two\n+three\n \n", + out: "@@ -1,3 +1,4 @@\n one\n two\n three\n+\n", }, }