Skip to content

Commit

Permalink
Skip rewriting output files if unchanged
Browse files Browse the repository at this point in the history
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 golang#604
  • Loading branch information
sodul committed Aug 11, 2022
1 parent 73266f9 commit fdeca2c
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 14 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Expand Up @@ -17,3 +17,6 @@ mockgen/mockgen
# Editors
.vscode
.idea

# vendor directory used for IDEs
/vendor
37 changes: 23 additions & 14 deletions mockgen/mockgen.go
Expand Up @@ -21,6 +21,7 @@ package main
import (
"bytes"
"encoding/json"
"errors"
"flag"
"fmt"
"go/token"
Expand Down Expand Up @@ -107,19 +108,6 @@ func main() {
return
}

dst := os.Stdout
if len(*destination) > 0 {
if err := os.MkdirAll(filepath.Dir(*destination), os.ModePerm); err != nil {
log.Fatalf("Unable to create directory: %v", err)
}
f, err := os.Create(*destination)
if err != nil {
log.Fatalf("Failed opening destination file: %v", err)
}
defer f.Close()
dst = f
}

outputPackageName := *packageOut
if outputPackageName == "" {
// pkg.Name in reflect mode is the base name of the import path,
Expand Down Expand Up @@ -171,7 +159,28 @@ func main() {
if err := g.Generate(pkg, outputPackageName, outputPackagePath); err != nil {
log.Fatalf("Failed generating mock: %v", err)
}
if _, err := dst.Write(g.Output()); err != nil {
output := g.Output()
dst := os.Stdout
if len(*destination) > 0 {
if err := os.MkdirAll(filepath.Dir(*destination), os.ModePerm); err != nil {
log.Fatalf("Unable to create directory: %v", err)
}
existing, err := os.ReadFile(*destination)
if err != nil && !errors.Is(err, os.ErrNotExist) {
log.Fatalf("Failed reading pre-exiting destination file: %v", err)
}
if len(existing) == len(output) && bytes.Compare(existing, output) == 0 {
log.Println("Pre-existing file is already up to date.")
return
}
f, err := os.Create(*destination)
if err != nil {
log.Fatalf("Failed opening destination file: %v", err)
}
defer f.Close()
dst = f
}
if _, err := dst.Write(output); err != nil {
log.Fatalf("Failed writing to destination: %v", err)
}
}
Expand Down

0 comments on commit fdeca2c

Please sign in to comment.