a-h / templ

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

Organise imports #778

Closed joerdav closed 2 weeks ago

joerdav commented 1 month ago

This PR currently contains the following changes, which we may or may not want, yet to be decided:

Remove default dependency on io, bytes, strings, context from generated templates, so only github.com/a-h/templ is required. If github.com/a-h/templ is imported in a .templ file, don’t write it twice. If github.com/a-h/templ is not imported in a .templ, write it to the generated file (for backwards compatibility), but warn that it is a problem, tell the user they should run templ fmt. Update templ fmt to add github.com/a-h/templ as a dep to any templates that don’t have it. Trick gopls into supporting code actions for our generated files.

a-h commented 3 weeks ago

I've had a crack at a version that uses the Go AST parser to do the replacement and rewrite https://github.com/a-h/imports

WDYT? Anything useful in there?

joerdav commented 3 weeks ago

There is a lot useful in here I think. I see that you call updateImports multiple times, I wondered why you don't run it on the generated go code rather than segments of the template?

From my first read am I right in assuming this wouldn't yet remove unused imports or sort them in the style that gopls does?

Apart from that looks good to me, though I don't think there is anything of use in this PR if we go down this route, so we're better off starting fresh.

a-h commented 3 weeks ago

Yeah, I only thought about doing it on the generated code after I'd written it all. 😂 It would be much simpler, I think.

For removing unused imports and sorting them, it would be possible to do that if the organise imports functionality ran updateImports on the generated file, parsed the results, and moved the entire set of import statements from the generated *_templ.go file to the first Go code node in the *.templ file (or created it, if one doesn't exist, like the example does).

However, doing that would mean that io and bytes etc. would appear in the templ file which would be jarring to users. But... if we took your idea of only referencing a specific templ package (e.g. runtime github.com/a-h/templ/runtime/v2 in the generated code, then you'd only see that one package in the templ file, which I think would be a great design overall.

a-h commented 3 weeks ago

In my defence, it was late. 😁