Skip to content

Commit 7874bd9

Browse files
committed
Avoid updating target file mtime in 'generate'
If the target file exists on disk already, compare its contents to the generated source in memory: only update the target file on disk if the contents differ or if the target file is missing. This should allow build tools downstream of sqlc to make conditional decisions based on whether the generated code files have been updated (e.g. mockgen).
1 parent a60f370 commit 7874bd9

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

internal/cmd/cmd.go

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,10 +205,28 @@ var genCmd = &cobra.Command{
205205
defer trace.StartRegion(cmd.Context(), "writefiles").End()
206206
for filename, source := range output {
207207
os.MkdirAll(filepath.Dir(filename), 0755)
208-
if err := os.WriteFile(filename, []byte(source), 0644); err != nil {
208+
// if the target file does not exist, we can just write to it
209+
if _, err := os.Stat(filename); os.IsNotExist(err) {
210+
if err := os.WriteFile(filename, []byte(source), 0644); err != nil {
211+
fmt.Fprintf(stderr, "%s: %s\n", filename, err)
212+
return err
213+
}
214+
return nil
215+
}
216+
// otherwise, if the target file exists, read its contents and compare it to the source
217+
targetFile, err := os.ReadFile(filename)
218+
if err != nil {
209219
fmt.Fprintf(stderr, "%s: %s\n", filename, err)
210220
return err
211221
}
222+
// if the target file is the same as the source, we can just remove the temp file
223+
if bytes.Equal(targetFile, []byte(source)) {
224+
if err := os.WriteFile(filename, []byte(source), 0644); err != nil {
225+
fmt.Fprintf(stderr, "%s: %s\n", filename, err)
226+
return err
227+
}
228+
continue
229+
}
212230
}
213231
return nil
214232
},

0 commit comments

Comments
 (0)