// Command genopenapi writes docs/swagger.json, the OpenAPI 3.1 document of // Überbringer's HTTP API, from the route table in // internal/app/uberbringer/server and the Go types it names: paths from the // routes, schemas by reflecting the request and response types (their json // and jsonschema tags and their doc comments). Nothing in the document is // written by hand, and a golden test fails when the committed file differs // from what this produces. // // go run ./tools/genopenapi (or: go generate ./...) package main import ( "bytes" "errors" "fmt" "os" "path/filepath" ) // swaggerPath is the generated document, relative to the repository root. const swaggerPath = "docs/swagger.json" func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, "genopenapi:", err) os.Exit(1) } } func run() error { cwd, err := os.Getwd() if err != nil { return err } root, err := findRepoRoot(cwd) if err != nil { return err } out, err := Generate(root) if err != nil { return err } path := filepath.Join(root, filepath.FromSlash(swaggerPath)) current, err := os.ReadFile(path) if err != nil && !errors.Is(err, os.ErrNotExist) { return err } if bytes.Equal(current, out) { fmt.Printf("genopenapi: %s is up to date\n", swaggerPath) return nil } if err := os.WriteFile(path, out, 0o644); err != nil { return err } fmt.Printf("genopenapi: wrote %s\n", swaggerPath) return nil } // findRepoRoot walks up from start to the directory holding go.mod. func findRepoRoot(start string) (string, error) { dir := start for { if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { return dir, nil } parent := filepath.Dir(dir) if parent == dir { return "", fmt.Errorf("go.mod not found above %s", start) } dir = parent } }