Skip to content

Commit

Permalink
fix: only write to file if content changed, fixes #794 (#797)
Browse files Browse the repository at this point in the history
  • Loading branch information
a-h authored Jun 27, 2024
1 parent 2a7278c commit a0f5da5
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 @@ -26,15 +26,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, args.StdinFilepath))
return format(writeToWriter(stdout), readFromReader(stdin, args.StdinFilepath), 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 @@ -121,7 +122,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 @@ -139,5 +140,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 a0f5da5

Please sign in to comment.