Generate the OpenAPI document from a route table
Security / Vulnerability check (push) Successful in 38s
Test / Lint and test (push) Successful in 1m53s

The server registers its routes from one table in server/routes.go, and
tools/genopenapi (run by go generate) writes docs/swagger.json, an
OpenAPI 3.1 document, from the same table and the Go types it names.
Schemas are reflected with invopop/jsonschema: descriptions from the
first paragraph of the doc comments, enums and limits from jsonschema
tags. Request schemas are strict, as the decoder is; response schemas
allow fields added later. The daemon serves the embedded document at
GET /openapi.json without a token, internal/app passes it to the server
in its config, and release archives and the Docker build include it.

Tests keep it honest: a golden test and a CI step fail when the
document is stale, every registered route must be in the table, and the
tags are held to validation, to the Go constants and to the values the
handlers send. receipt.Element and printqueue.Status gain field doc
comments for the descriptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 09:30:42 -06:00
1 parent 9f7c5db923
commit bdd337e2dc
31 files changed
+3153 -128

No files matched your search

+120
View File
@@ -0,0 +1,120 @@
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"reflect"
"strings"
)
// modulePath is the module's import path, which every package path starts
// with.
const modulePath = "uberbringer"
// comments maps "pkgpath.Type" and "pkgpath.Type.Field" to the first
// paragraph of their doc comments, for the packages whose types the document
// describes. Later paragraphs are for Go readers only.
// jsonschema's own extractor builds its keys from file paths, which come out
// with backslashes on Windows, so the generator reads the comments itself to
// give the same document on every platform.
type comments map[string]string
// extractComments reads the doc comments of every type in the packages of
// the given values.
func extractComments(root string, of ...any) (comments, error) {
out := make(comments)
for _, v := range of {
pkg := reflect.TypeOf(v).PkgPath()
rel, ok := strings.CutPrefix(pkg, modulePath+"/")
if !ok {
return nil, fmt.Errorf("package %s is outside the module", pkg)
}
dir := filepath.Join(root, filepath.FromSlash(rel))
entries, err := os.ReadDir(dir)
if err != nil {
return nil, fmt.Errorf("reading %s: %w", rel, err)
}
fset := token.NewFileSet()
for _, e := range entries {
name := e.Name()
if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
continue
}
f, err := parser.ParseFile(fset, filepath.Join(dir, name), nil, parser.ParseComments)
if err != nil {
return nil, err
}
out.collect(pkg, f)
}
}
return out, nil
}
func (c comments) collect(pkg string, f *ast.File) {
for _, decl := range f.Decls {
gen, ok := decl.(*ast.GenDecl)
if !ok || gen.Tok != token.TYPE {
continue
}
for _, spec := range gen.Specs {
ts := spec.(*ast.TypeSpec)
doc := ts.Doc
if doc == nil && len(gen.Specs) == 1 {
doc = gen.Doc
}
key := pkg + "." + ts.Name.Name
if text := firstParagraph(doc.Text()); text != "" {
c[key] = text
}
st, ok := ts.Type.(*ast.StructType)
if !ok {
continue
}
for _, field := range st.Fields.List {
text := field.Doc.Text()
if text == "" {
text = field.Comment.Text()
}
for _, n := range field.Names {
if text != "" {
c[key+"."+n.Name] = firstParagraph(text)
}
}
}
}
}
}
// lookup is the jsonschema LookupComment hook: field is the Go field name,
// or empty for the type itself. A comment starts, as Go doc comments do,
// with the Go name; the document shows the schema's or the property's name
// there instead.
func (c comments) lookup(t reflect.Type, field string) string {
key := t.PkgPath() + "." + t.Name()
if field == "" {
text := c[key]
if rest, ok := strings.CutPrefix(text, t.Name()+" "); ok {
text = schemaName(t) + " " + rest
}
return text
}
text := c[key+"."+field]
if f, ok := t.FieldByName(field); ok {
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
if rest, ok := strings.CutPrefix(text, field+" "); ok && name != "" {
text = name + " " + rest
}
}
return text
}
// firstParagraph returns a doc comment's text up to its first blank line, on
// one line.
func firstParagraph(text string) string {
para, _, _ := strings.Cut(strings.TrimSpace(text), "\n\n")
return strings.Join(strings.Fields(para), " ")
}
+7
View File
@@ -0,0 +1,7 @@
package main
// `go generate ./...` regenerates docs/swagger.json. go generate runs each
// directive in its own package's directory, so the directive builds this
// package as ".".
//
//go:generate go run .
+355
View File
@@ -0,0 +1,355 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"reflect"
"sort"
"strconv"
"strings"
"unicode"
"unicode/utf8"
"github.com/invopop/jsonschema"
"uberbringer/internal/app/uberbringer/server"
"uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt"
)
const (
componentsPrefix = "#/components/schemas/"
defsPrefix = "#/$defs/"
securityScheme = "bearerAuth"
mediaJSON = "application/json"
// codesExtension lists the error codes a status stands for.
codesExtension = "x-uberbringer-codes"
)
// jobIDPattern matches a job_ TypeID: a UUIDv7 in Crockford base32 after the
// prefix.
const jobIDPattern = "^job_[0-7][0-9a-hjkmnp-tv-z]{25}$"
// Generate returns docs/swagger.json for the route table. root is the
// repository root, whose sources hold the doc comments.
func Generate(root string) ([]byte, error) {
c, err := extractComments(root, server.Route{}, receipt.Job{}, printqueue.Status{})
if err != nil {
return nil, err
}
g := &generator{
requests: newSchemaReflector(c, true),
responses: newSchemaReflector(c, false),
schemas: make(map[string]any),
}
if _, err := g.schemaRef(g.responses, server.ErrorBody()); err != nil {
return nil, err
}
paths := make(map[string]any)
tags := make(map[string]bool)
for _, r := range server.Routes() {
op, err := g.operation(r)
if err != nil {
return nil, fmt.Errorf("%s %s: %w", r.Method, r.Path, err)
}
item, _ := paths[r.Path].(map[string]any)
if item == nil {
item = make(map[string]any)
paths[r.Path] = item
}
item[strings.ToLower(r.Method)] = op
tags[r.Tag] = true
}
var serverErrors []string
for _, e := range server.ServerErrors() {
serverErrors = append(serverErrors, strconv.Itoa(e.Status)+" "+e.Code)
}
doc := map[string]any{
"openapi": "3.1.0",
"info": map[string]any{
"title": "Überbringer HTTP API",
"version": "v1",
"description": "Takes print jobs as JSON and prints them on an Epson ESC/POS receipt printer. " +
"Every error is JSON with a stable code. Each operation lists the codes it and its " +
"middleware answer with; the HTTP server itself can also refuse any request with " +
strings.Join(serverErrors, ", ") + ". Responses from /healthz and every /api/v1 route " +
"carry Cache-Control: no-store. Generated from the route table; do not edit.",
"license": map[string]any{"name": "EUPL-1.2", "identifier": "EUPL-1.2"},
},
"tags": sortedTags(tags),
"paths": paths,
"components": map[string]any{
"schemas": g.schemas,
"securitySchemes": map[string]any{
securityScheme: map[string]any{
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT",
"description": "An HS256 token signed with api.secret, as `uberbringer token` issues them.",
},
},
},
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(doc); err != nil {
return nil, fmt.Errorf("encoding the document: %w", err)
}
return buf.Bytes(), nil
}
// newSchemaReflector reflects types into JSON Schema 2020-12, the dialect of
// OpenAPI 3.1. A request schema is strict, as the server decodes requests:
// an unknown field is an error, and a field is required only when its
// jsonschema tag says so. A response schema allows additional properties,
// so a field added later does not break a client validating against an
// older document, and requires the fields that are always sent.
func newSchemaReflector(c comments, request bool) *jsonschema.Reflector {
return &jsonschema.Reflector{
Anonymous: true,
AllowAdditionalProperties: !request,
RequiredFromJSONSchemaTags: request,
Namer: schemaName,
Mapper: mapType(c),
LookupComment: c.lookup,
}
}
type generator struct {
requests, responses *jsonschema.Reflector
schemas map[string]any
}
func (g *generator) operation(r server.Route) (map[string]any, error) {
op := map[string]any{
"operationId": r.OperationID,
"summary": r.Summary,
"tags": []string{r.Tag},
}
if r.Description != "" {
op["description"] = r.Description
}
if r.Auth {
op["security"] = []any{map[string]any{securityScheme: []string{}}}
} else {
op["security"] = []any{}
}
if len(r.Params) > 0 {
params := make([]any, len(r.Params))
for i, p := range r.Params {
params[i] = map[string]any{
"name": p.Name,
"in": p.In,
"required": p.Required || p.In == "path",
"description": p.Description,
"schema": map[string]any{"type": "string"},
}
}
op["parameters"] = params
}
if r.Request != nil {
ref, err := g.schemaRef(g.requests, r.Request)
if err != nil {
return nil, err
}
op["requestBody"] = map[string]any{
"required": true,
"content": map[string]any{mediaJSON: map[string]any{"schema": ref}},
}
}
responses, err := g.routeResponses(r)
if err != nil {
return nil, err
}
op["responses"] = responses
return op, nil
}
func (g *generator) routeResponses(r server.Route) (map[string]any, error) {
responses := make(map[string]any)
for _, resp := range r.Responses {
doc := map[string]any{"description": resp.Description}
if len(resp.Content) > 0 {
content := make(map[string]any, len(resp.Content))
for _, c := range resp.Content {
schema, err := g.bodySchema(c.Body)
if err != nil {
return nil, err
}
content[c.MediaType] = map[string]any{"schema": schema}
}
doc["content"] = content
}
if len(resp.Headers) > 0 {
headers := make(map[string]any, len(resp.Headers))
for _, h := range resp.Headers {
schema := map[string]any{"type": "string"}
if h.Integer {
schema = map[string]any{"type": "integer", "minimum": 1}
}
headers[h.Name] = map[string]any{"description": h.Description, "schema": schema}
}
doc["headers"] = headers
}
responses[strconv.Itoa(resp.Status)] = doc
}
byStatus := make(map[int][]server.ErrorDoc)
for _, e := range r.DocumentedErrors() {
byStatus[e.Status] = append(byStatus[e.Status], e)
}
for status, codes := range byStatus {
key := strconv.Itoa(status)
if _, taken := responses[key]; taken {
return nil, fmt.Errorf("status %d is both a response and an error", status)
}
names := make([]string, len(codes))
titles := make([]string, len(codes))
for i, c := range codes {
names[i] = c.Code
titles[i] = c.Code + ": " + c.Message
}
resp := map[string]any{
"description": http.StatusText(status) + ". " + strings.Join(titles, "; ") + ".",
codesExtension: names,
"content": map[string]any{mediaJSON: map[string]any{
"schema": map[string]any{"$ref": componentsPrefix + "ErrorResponse"},
}},
}
if headers := errorHeaders(status); headers != nil {
resp["headers"] = headers
}
responses[key] = resp
}
return responses, nil
}
// bodySchema is the schema of a response body: a string for a text body,
// otherwise a reference to the reflected type.
func (g *generator) bodySchema(body any) (map[string]any, error) {
if _, ok := body.(string); ok {
return map[string]any{"type": "string"}, nil
}
return g.schemaRef(g.responses, body)
}
// errorHeaders documents the headers an error status carries besides its
// body, or nil for none.
func errorHeaders(status int) map[string]any {
switch status {
case http.StatusUnauthorized:
return map[string]any{"WWW-Authenticate": map[string]any{
"description": `The challenge: Bearer realm="uberbringer", with error="invalid_token" when a ` +
"token was sent but is not valid.",
"schema": map[string]any{"type": "string"},
}}
case http.StatusTooManyRequests:
return map[string]any{"Retry-After": map[string]any{
"description": "How many seconds to wait before the client's next request is let through.",
"schema": map[string]any{"type": "integer", "minimum": 1},
}}
case http.StatusServiceUnavailable:
return map[string]any{"Retry-After": map[string]any{
"description": "Sent with queue_full: how many seconds to wait before trying again.",
"schema": map[string]any{"type": "integer", "minimum": 1},
}}
}
return nil
}
// schemaRef reflects v's type into the components and returns a reference
// to it.
func (g *generator) schemaRef(r *jsonschema.Reflector, v any) (map[string]any, error) {
s := r.Reflect(v)
raw, err := json.Marshal(s)
if err != nil {
return nil, fmt.Errorf("reflecting %T: %w", v, err)
}
var root map[string]any
if err := json.Unmarshal(raw, &root); err != nil {
return nil, fmt.Errorf("reflecting %T: %w", v, err)
}
defs, _ := root["$defs"].(map[string]any)
for name, def := range defs {
def = rewriteRefs(def)
if existing, ok := g.schemas[name]; ok && !reflect.DeepEqual(existing, def) {
return nil, fmt.Errorf("two different schemas are both named %q", name)
}
g.schemas[name] = def
}
ref, ok := root["$ref"].(string)
if !ok {
return nil, fmt.Errorf("%T did not reflect to a named schema", v)
}
return map[string]any{"$ref": strings.Replace(ref, defsPrefix, componentsPrefix, 1)}, nil
}
// rewriteRefs points every $ref at the components instead of $defs.
func rewriteRefs(node any) any {
switch n := node.(type) {
case map[string]any:
for k, v := range n {
if s, ok := v.(string); ok && k == "$ref" {
n[k] = strings.Replace(s, defsPrefix, componentsPrefix, 1)
continue
}
n[k] = rewriteRefs(v)
}
case []any:
for i, v := range n {
n[i] = rewriteRefs(v)
}
}
return node
}
// schemaName names a component after its Go type, with a capital letter
// since several of the server's types are unexported. A job's status is
// JobStatus, as Status alone says too little.
func schemaName(t reflect.Type) string {
if t == reflect.TypeFor[printqueue.Status]() {
return "JobStatus"
}
name := t.Name()
if name == "" {
return ""
}
r, size := utf8.DecodeRuneInString(name)
return string(unicode.ToUpper(r)) + name[size:]
}
// mapType gives a job ID its JSON form, a string, in place of the Go struct
// behind it.
func mapType(c comments) func(reflect.Type) *jsonschema.Schema {
return func(t reflect.Type) *jsonschema.Schema {
if t != reflect.TypeFor[printqueue.JobID]() {
return nil
}
return &jsonschema.Schema{
Type: "string",
Pattern: jobIDPattern,
Description: c.lookup(t, ""),
Examples: []any{"job_01kbx4n6m3ex8tq0wq3r5vrzq1"},
}
}
}
func sortedTags(tags map[string]bool) []any {
names := make([]string, 0, len(tags))
for name := range tags {
names = append(names, name)
}
sort.Strings(names)
out := make([]any, len(names))
for i, name := range names {
out[i] = map[string]any{"name": name}
}
return out
}
+260
View File
@@ -0,0 +1,260 @@
package main
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"uberbringer/internal/app/uberbringer/server"
)
// repoRoot finds the repository root above the package directory, which go
// test runs in.
func repoRoot(t *testing.T) string {
t.Helper()
cwd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
root, err := findRepoRoot(cwd)
if err != nil {
t.Fatal(err)
}
return root
}
func generated(t *testing.T) map[string]any {
t.Helper()
out, err := Generate(repoRoot(t))
if err != nil {
t.Fatalf("Generate: %v", err)
}
var doc map[string]any
if err := json.Unmarshal(out, &doc); err != nil {
t.Fatalf("generated document is not JSON: %v", err)
}
return doc
}
func schema(t *testing.T, doc map[string]any, name string) map[string]any {
t.Helper()
s, ok := doc["components"].(map[string]any)["schemas"].(map[string]any)[name].(map[string]any)
if !ok {
t.Fatalf("no schema %s", name)
}
return s
}
func property(t *testing.T, doc map[string]any, schemaName, prop string) map[string]any {
t.Helper()
p, ok := schema(t, doc, schemaName)["properties"].(map[string]any)[prop].(map[string]any)
if !ok {
t.Fatalf("%s has no property %s", schemaName, prop)
}
return p
}
// TestSwaggerJSONUpToDate fails when docs/swagger.json differs from what the
// route table and its types produce: regenerate with `go generate ./...`.
func TestSwaggerJSONUpToDate(t *testing.T) {
root := repoRoot(t)
committed, err := os.ReadFile(filepath.Join(root, filepath.FromSlash(swaggerPath)))
if err != nil {
t.Fatal(err)
}
out, err := Generate(root)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(committed, out) {
t.Fatal("docs/swagger.json is out of date; run: go generate ./...")
}
}
func TestGenerateIsStable(t *testing.T) {
a, err := Generate(repoRoot(t))
if err != nil {
t.Fatal(err)
}
b, err := Generate(repoRoot(t))
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(a, b) {
t.Fatal("two runs produced different documents")
}
}
func TestEveryRouteIsDocumented(t *testing.T) {
doc := generated(t)
if doc["openapi"] != "3.1.0" {
t.Fatalf("openapi = %v", doc["openapi"])
}
paths := doc["paths"].(map[string]any)
for _, r := range server.Routes() {
op, ok := paths[r.Path].(map[string]any)[strings.ToLower(r.Method)].(map[string]any)
if !ok {
t.Errorf("%s %s is not documented", r.Method, r.Path)
continue
}
if op["operationId"] != r.OperationID {
t.Errorf("%s %s: operationId %v", r.Method, r.Path, op["operationId"])
}
responses := op["responses"].(map[string]any)
if _, ok := responses["500"]; !ok {
t.Errorf("%s %s: no 500 response", r.Method, r.Path)
}
security, _ := op["security"].([]any)
if r.Auth != (len(security) == 1) {
t.Errorf("%s %s: Auth %v, security %v", r.Method, r.Path, r.Auth, op["security"])
}
if !r.Auth {
continue
}
for status, header := range map[string]string{"401": "WWW-Authenticate", "429": "Retry-After"} {
resp, ok := responses[status].(map[string]any)
if !ok {
t.Errorf("%s %s: no %s response", r.Method, r.Path, status)
continue
}
if headers, _ := resp["headers"].(map[string]any); headers[header] == nil {
t.Errorf("%s %s: %s without %s", r.Method, r.Path, status, header)
}
}
}
}
// Every {name} in a path has its path parameter.
func TestPathParametersDocumented(t *testing.T) {
doc := generated(t)
paths := doc["paths"].(map[string]any)
for _, r := range server.Routes() {
op := paths[r.Path].(map[string]any)[strings.ToLower(r.Method)].(map[string]any)
params, _ := op["parameters"].([]any)
for _, name := range pathParams(r.Path) {
found := slices.ContainsFunc(params, func(p any) bool {
m := p.(map[string]any)
return m["name"] == name && m["in"] == "path" && m["required"] == true
})
if !found {
t.Errorf("%s %s: path parameter %s is not documented", r.Method, r.Path, name)
}
}
}
}
func pathParams(path string) []string {
var names []string
for part := range strings.SplitSeq(path, "/") {
if name, ok := strings.CutPrefix(part, "{"); ok {
names = append(names, strings.TrimSuffix(name, "}"))
}
}
return names
}
func TestReferencesResolve(t *testing.T) {
doc := generated(t)
schemas := doc["components"].(map[string]any)["schemas"].(map[string]any)
var walk func(node any)
walk = func(node any) {
switch n := node.(type) {
case map[string]any:
for k, v := range n {
if s, ok := v.(string); ok && k == "$ref" {
name, found := strings.CutPrefix(s, componentsPrefix)
if !found {
t.Errorf("$ref %q does not point at the components", s)
} else if _, ok := schemas[name]; !ok {
t.Errorf("$ref %q names no schema", s)
}
continue
}
walk(v)
}
case []any:
for _, v := range n {
walk(v)
}
}
}
walk(doc)
}
// A request schema refuses unknown fields and requires only what its
// jsonschema tags mark, as the server's strict decoder does. A response
// schema allows fields a later version adds.
func TestRequestSchemasAreStrict(t *testing.T) {
doc := generated(t)
for name, required := range map[string][]any{"Job": {"elements"}, "Element": {"type"}, "Pair": {"key"}} {
s := schema(t, doc, name)
if s["additionalProperties"] != false {
t.Errorf("%s allows additional properties", name)
}
if got, _ := s["required"].([]any); !slices.Equal(got, required) {
t.Errorf("%s requires %v, want %v", name, got, required)
}
}
for _, name := range []string{"JobStatus", "HealthResponse", "PreviewResponse", "ErrorResponse"} {
if _, ok := schema(t, doc, name)["additionalProperties"]; ok {
t.Errorf("%s restricts additional properties", name)
}
}
}
// Descriptions come from the doc comments, with the JSON name in place of
// the Go name; enums and the job ID's pattern from the tags and the mapper.
func TestSchemasCarryComments(t *testing.T) {
doc := generated(t)
if d, _ := schema(t, doc, "Element")["description"].(string); !strings.HasPrefix(d, "Element is one item on a receipt") {
t.Errorf("Element description = %q", d)
}
// A type's description starts with the schema's name and stops at the
// first blank line of its doc comment.
if d, _ := schema(t, doc, "ErrorResponse")["description"].(string); !strings.HasPrefix(d, "ErrorResponse is ") {
t.Errorf("ErrorResponse description = %q", d)
}
if d, _ := schema(t, doc, "Job")["description"].(string); d != "Job is a receipt to print." {
t.Errorf("Job description = %q", d)
}
status := property(t, doc, "JobStatus", "status")
if d, _ := status["description"].(string); !strings.HasPrefix(d, "status is ") {
t.Errorf("JobStatus.status description = %q", d)
}
if enum, _ := status["enum"].([]any); len(enum) != 4 {
t.Errorf("JobStatus.status enum = %v", status["enum"])
}
id := property(t, doc, "JobStatus", "id")
if id["type"] != "string" || id["pattern"] != jobIDPattern {
t.Errorf("JobStatus.id = %v", id)
}
for _, prop := range []string{"text", "size", "pairs", "leader"} {
if d, _ := property(t, doc, "Element", prop)["description"].(string); d == "" {
t.Errorf("Element.%s has no description", prop)
}
}
}
// Preview answers plain text or JSON, and the print route's 202 carries
// the job's URL.
func TestResponseContent(t *testing.T) {
doc := generated(t)
paths := doc["paths"].(map[string]any)
preview := paths["/api/v1/preview"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)["200"].(map[string]any)
content := preview["content"].(map[string]any)
if len(content) != 2 || content["application/json"] == nil {
t.Errorf("preview 200 content = %v", content)
}
accepted := paths["/api/v1/print"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)["202"].(map[string]any)
if headers, _ := accepted["headers"].(map[string]any); headers["Location"] == nil {
t.Errorf("print 202 headers = %v", accepted["headers"])
}
queueFull := paths["/api/v1/print"].(map[string]any)["post"].(map[string]any)["responses"].(map[string]any)["503"].(map[string]any)
if codes, _ := queueFull[codesExtension].([]any); !slices.Contains(codes, any("queue_full")) {
t.Errorf("print 503 codes = %v", queueFull[codesExtension])
}
}
+72
View File
@@ -0,0 +1,72 @@
// 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
}
}