clipperhouse / typewriter

The package underlying gen: type-driven code generation for Go
http://clipperhouse.github.io/gen/typewriters/#
Other
52 stars 20 forks source link

Support non-struct types, custom tags, custom writers #13

Open bradrydzewski opened 9 years ago

bradrydzewski commented 9 years ago

@clipperhouse thanks for referring me to this project on twitter. I've been looking through the code and this looks like a great drop-in replacement for some of the parser and generator code I've hand written for my sqlgen tool. I will happily integrate.

I realize this package targets Anything “of T”, however, I think it could serve as a powerful base for any code generator of any type with some minor enhancements. I've detailed some ideas below.

1. Remove type restrictions (ie not just struct) allowing the typewriter to decide which types it would like to process. For example, the ability to annotate a function so that I can auto-generate my routing code:

// +gen route="GET /foo/{bar}"
func HandleFoo(w http.ResponseWriter, r *http.Request) {
    // serve
}

2. Custom tag parsing would also be helpful. I would love to see this behave a bit more similar to Go tags, where there is no restriction on what format is used inside the tag. Take the above example where I'd like to declare routing information inside the tag. Or the below example, more directly related to the sql generation tool I wrote, where people are requesting the ability to specify struct-level attributes such as the table name:

// +gen sql="table_name: foo_tbl"
type Foo struct {

}

3. provide more control over writing files (ie supply my own writer, combine files). If we re-visit the http routing example, I could see annotating multiple handler functions across multiple files, but wanting to generate a single routes.go file.

I'm willing to implement any of the proposed features, if you think they make sense. We can also break this into multiple issues, for tracking purposes, if you prefer.

clipperhouse commented 9 years ago

Quick thoughts:

1) That’s interesting. gen supports marking up any type declaration (doesn’t care if it’s a struct), but one could argue for marking up funcs. It’s not a type, but if it’s useful…

2) I could simply expose a .Raw property or similar, with the original text so one can do their own parsing.

3) Worth considering, allowing the injection of one’s own writer. You can write your own files now of course (typewriters are just code), but having some support within typewriter’s conventions would be nice.