a-h / templ

A language for writing HTML user interfaces in Go.
https://templ.guide/
MIT License
8.26k stars 272 forks source link

Request: templ fmt should not write the file unless there are changes #128

Closed jonerer closed 1 year ago

jonerer commented 1 year ago

Thanks for this awesome project -- it feels like a perfect fit for htmx+alpine etc. Love the type safety.

I would like to be able to run templ fmt automatically on changes. But right now running templ fmt will trigger a restart of air since it rewrites files even though fmt doesn't create any changes. It would be awesome if templ fmt doesn't write the file when there's no changes.

I believe a change somewhere around here: err = atomic.WriteFile(fileName, w) could fix it.

Ideally I'd like to put something like cmd = "templ fmt . && templ generate && go build -o ./tmp/main ." my .air.toml. But right now that causes an infinite loop.

Thanks!

joerdav commented 1 year ago

This could potentially leverage the outcome of #123 if the hash option is developed. To avoid having to reload the file to do a diff check before writing the file.

Although, we do already load the whole file into memory anyway: https://github.com/a-h/templ/blob/fc8328a0fd7aa8930882885a4398c6367ec56d38/parser/v2/templatefile.go#L14

a-h commented 1 year ago

Thanks for the report @jonerer!

You're right @joerdav - the fmt command is already holding the file in RAM so it's not much work to do an additional check, and in a lot of cases, it will skip a filesystem write, which should result in a net save of performance overall.

I've made a quick tweak to that section of code.