I'm looking to make a tool which generates method stubs from some given input. I've seen the ast
package, but it seems to represent an already parsed AST, which has information about where in the source file everything is. Importantly, you need to provide source information
I'm looking at generating a source file programatically, so I have no idea where in the final file my AST nodes will end up.
I'm wondering:
ast
package, will it pretty-print properly (i.e. ignore the position information)?I realize I could do this all with text generation, but that seems type-unsafe and harder to deal with.
Consider https://github.com/lu4p/astextract which has a nicer AST to work with that can be printed into go code.
I know you've thought about this, but using text/template
and goimports
on the resulting string is actually quite reasonable. It's way easier to write and it translates much better to writing normal go code. As you note, it's not type-safe (which is fine because running goimports
on it later enforces that). The biggest con is actually that it's hard to test (we ended up writing a set of generated tests and manual written tests).
(EDIT: just realized how old of a question this is - going to leave my answer up for others as I'm sure you've found some way to solve this for yourself by now)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With