livebud / bud

The Full-Stack Web Framework for Go
MIT License
5.58k stars 179 forks source link

Add support for custom generators #282

Closed matthewmueller closed 2 years ago

matthewmueller commented 2 years ago

This PR adds support for custom generators. Custom generators allow you to define application-specific code generators that hook into the rest of the code generators. There was a first attempt at doing this in https://github.com/livebud/bud/pull/236, but it was subsequently removed in https://github.com/livebud/bud/pull/276 because the implementation had some tradeoffs so I looked for a better solution.

You can add a custom generator to you application by creating packages inside the generator/ directory. For example, you can define the following package in generator/tailwind/tailwind.go

package tailwind

import (
    "github.com/livebud/bud/package/budfs"
)

type Generator struct {
  // Dependencies
}

func (g *Generator) GenerateDir(fsys budfs.FS, dir *budfs.Dir) error {
    dir.GenerateFile("tailwind.css", func(fsys budfs.FS, file *budfs.File) error {
        file.Data = []byte("/** tailwind **/")
        return nil
    })
    dir.GenerateFile("preflight.css", func(fsys budfs.FS, file *budfs.File) error {
        file.Data = []byte("/** preflight **/")
        return nil
    })
    return nil
}

Bud will then be able to find and run the function for preflight.css at bud/internal/generator/tailwind/preflight.css. Custom generators use the same budfs package that core generators like controller and view use.

While this PR introduces the ability to define your own custom generators, they're not exposed anywhere yet. The next step is to update other generators like public and web to look for custom generators and pull them into the build when they're in a certain directory. This will come in a follow-up PR.

Remaining todos for this PR: