Skip to content
This repository was archived by the owner on Jun 27, 2023. It is now read-only.

Commit 6711b2a

Browse files
committed
Skip rewriting output files if unchanged
When running mockgen with the output option this checks if the existing file content already exists and skips writing if there is nothing to change. This will help reduce i/o when changing lots of files, but also reduce the re-indexing triggering in IDEs. Solves #604
1 parent 32e424a commit 6711b2a

File tree

2 files changed

+26
-14
lines changed

2 files changed

+26
-14
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,6 @@ mockgen/mockgen
1717
# Editors
1818
.vscode
1919
.idea
20+
21+
# vendor directory used for IDEs
22+
/vendor

mockgen/mockgen.go

+23-14
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ package main
2121
import (
2222
"bytes"
2323
"encoding/json"
24+
"errors"
2425
"flag"
2526
"fmt"
2627
"go/token"
@@ -107,19 +108,6 @@ func main() {
107108
return
108109
}
109110

110-
dst := os.Stdout
111-
if len(*destination) > 0 {
112-
if err := os.MkdirAll(filepath.Dir(*destination), os.ModePerm); err != nil {
113-
log.Fatalf("Unable to create directory: %v", err)
114-
}
115-
f, err := os.Create(*destination)
116-
if err != nil {
117-
log.Fatalf("Failed opening destination file: %v", err)
118-
}
119-
defer f.Close()
120-
dst = f
121-
}
122-
123111
outputPackageName := *packageOut
124112
if outputPackageName == "" {
125113
// pkg.Name in reflect mode is the base name of the import path,
@@ -171,7 +159,28 @@ func main() {
171159
if err := g.Generate(pkg, outputPackageName, outputPackagePath); err != nil {
172160
log.Fatalf("Failed generating mock: %v", err)
173161
}
174-
if _, err := dst.Write(g.Output()); err != nil {
162+
output := g.Output()
163+
dst := os.Stdout
164+
if len(*destination) > 0 {
165+
if err := os.MkdirAll(filepath.Dir(*destination), os.ModePerm); err != nil {
166+
log.Fatalf("Unable to create directory: %v", err)
167+
}
168+
existing, err := os.ReadFile(*destination)
169+
if err != nil && !errors.Is(err, os.ErrNotExist) {
170+
log.Fatalf("Failed reading pre-exiting destination file: %v", err)
171+
}
172+
if len(existing) == len(output) && bytes.Compare(existing, output) == 0 {
173+
log.Println("Pre-existing file is already up to date.")
174+
return
175+
}
176+
f, err := os.Create(*destination)
177+
if err != nil {
178+
log.Fatalf("Failed opening destination file: %v", err)
179+
}
180+
defer f.Close()
181+
dst = f
182+
}
183+
if _, err := dst.Write(output); err != nil {
175184
log.Fatalf("Failed writing to destination: %v", err)
176185
}
177186
}

0 commit comments

Comments
 (0)