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

Commit 5b45562

Browse files
authored
skip rewriting output files if unchanged (#626)
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 73266f9 commit 5b45562

File tree

3 files changed

+29
-18
lines changed

3 files changed

+29
-18
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/internal/tests/mock_in_test_package/mock_test.go

+4-4
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

mockgen/mockgen.go

+22-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,27 @@ 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 := ioutil.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+
return
174+
}
175+
f, err := os.Create(*destination)
176+
if err != nil {
177+
log.Fatalf("Failed opening destination file: %v", err)
178+
}
179+
defer f.Close()
180+
dst = f
181+
}
182+
if _, err := dst.Write(output); err != nil {
175183
log.Fatalf("Failed writing to destination: %v", err)
176184
}
177185
}

0 commit comments

Comments
 (0)