Skip to content

Commit

Permalink
fix: only write to file if content changed, fixes #794
Browse files Browse the repository at this point in the history
  • Loading branch information
a-h committed Jun 16, 2024
1 parent 8d27ad1 commit 3837c64
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions cmd/templ/fmtcmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,16 @@ type Arguments struct {
func Run(log *slog.Logger, stdin io.Reader, stdout io.Writer, args Arguments) (err error) {
// If no files are provided, read from stdin and write to stdout.
if len(args.Files) == 0 {
return format(writeToWriter(stdout), readFromReader(stdin))
return format(writeToWriter(stdout), readFromReader(stdin), true)
}
process := func(fileName string) error {
read := readFromFile(fileName)
write := writeToFile
if args.ToStdout {
write = writeToWriter(stdout)
}
return format(write, read)
writeIfUnchanged := args.ToStdout
return format(write, read, writeIfUnchanged)
}
dir := args.Files[0]
return NewFormatter(log, dir, process, args.WorkerCount).Run()
Expand Down Expand Up @@ -119,7 +120,7 @@ func writeToFile(fileName, tgt string) error {
return atomic.WriteFile(fileName, bytes.NewBufferString(tgt))
}

func format(write writer, read reader) (err error) {
func format(write writer, read reader, writeIfUnchanged bool) (err error) {
fileName, src, err := read()
if err != nil {
return err
Expand All @@ -132,5 +133,8 @@ func format(write writer, read reader) (err error) {
if err = t.Write(w); err != nil {
return fmt.Errorf("formatting error: %w", err)
}
if !writeIfUnchanged && src == w.String() {
return nil
}
return write(fileName, w.String())
}

0 comments on commit 3837c64

Please sign in to comment.