ugit/internal/html/generate.go

97 lines
1.9 KiB
Go
Raw Normal View History

//go:build generate
package main
import (
"bytes"
_ "embed"
"fmt"
"go.jolheiser.com/ugit/internal/html/markup"
"go/format"
"os"
"os/exec"
"github.com/alecthomas/chroma/v2/styles"
)
var (
tailwindCSS = `
@tailwind base;
@tailwind components;
@tailwind utilities;
`
//go:embed generate.css
otherCSS string
)
//go:generate templ generate
//go:generate go run generate.go
func main() {
if err := tailwind(); err != nil {
panic(err)
}
}
// Generate tailwind code from templ templates and combine with other misc CSS
func tailwind() error {
fmt.Println("generating tailwind...")
tmp, err := os.CreateTemp(os.TempDir(), "ugit-tailwind*")
if err != nil {
return err
}
defer os.Remove(tmp.Name())
if _, err := tmp.WriteString(tailwindCSS + otherCSS); err != nil {
return err
}
fmt.Println("generating chroma styles...")
latte := styles.Get("catppuccin-latte")
if err := markup.Formatter.WriteCSS(tmp, latte); err != nil {
return err
}
tmp.WriteString("@media (prefers-color-scheme: dark) {")
mocha := styles.Get("catppuccin-mocha")
if err := markup.Formatter.WriteCSS(tmp, mocha); err != nil {
return err
}
tmp.WriteString("}")
fmt.Println("finished generating chroma styles")
tmp.Close()
styles, err := os.Create("tailwind.go")
if err != nil {
return err
}
defer styles.Close()
var buf bytes.Buffer
cmd := exec.Command("tailwind-ctp", "-i", tmp.Name(), "--minify")
cmd.Stdout = &buf
if err := cmd.Run(); err != nil {
return err
}
code := fmt.Sprintf(`// Code generated by generate.go - DO NOT EDIT.
package html
import "net/http"
func TailwindHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/css")
w.Write([]byte(%q))
}`, buf.String())
formatted, err := format.Source([]byte(code))
if err != nil {
return err
}
styles.Write(formatted)
fmt.Println("finished generating tailwind")
return nil
}