livebud / bud

The Full-Stack Web Framework for Go
MIT License
5.57k stars 180 forks source link

framework/generator: updated the custom generator api #359

Closed matthewmueller closed 1 year ago

matthewmueller commented 1 year ago

Hidden in the v0.2.6 release is custom generator support. I didn't mention it because the API wasn't stable. In this PR, I take another pass over the custom generator API. I'm feeling pretty good about it now.

The important thing to note is that the custom code generators that you'd write for your application are equally as powerful as the code generators that Bud ships with. The benefit of writing custom generators within the framework is that you get caching, depending on other generators and hot reload for free.

For example, if you add the following code in the $APP/generator/graphql package:

package graphql

import "github.com/livebud/bud/package/genfs"

type Generator struct {
  // Add dependencies here to load them in via dependency injection
}

func (g *Generator) Generate(fsys genfs.FS, dir *genfs.Dir) error {
  dir.GenerateFile("graphql.go", func(fsys genfs.FS, file *genfs.File) error {
    // Do something custom
    file.Data = []byte(`...`)
    return nil
  })
  return nil
})

Then when Bud's generators run, it'll run this custom logic and you'll end up with a bud/internal/graphql/graphql.go file.

Remaining Todos: