diff --git a/cmd/templ/fmtcmd/main.go b/cmd/templ/fmtcmd/main.go index c6ae7406c..6e0584365 100644 --- a/cmd/templ/fmtcmd/main.go +++ b/cmd/templ/fmtcmd/main.go @@ -26,7 +26,7 @@ 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) @@ -34,7 +34,8 @@ func Run(log *slog.Logger, stdin io.Reader, stdout io.Writer, args Arguments) (e 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() @@ -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 @@ -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()) }