Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,10 @@ server scaffold, and tests.
## Introduction

Generated code has a reputation for being obviously generated. This module tries
hard not to earn it: output is run through `goimports` and `gofumpt`, names are
converted to Go conventions rather than transliterated, and the emitted types are
the ones you would have declared by hand.
hard not to earn it: each file imports exactly the packages it uses, sorted,
and is formatted with `gofumpt`, names are converted to Go conventions rather
than transliterated, and the emitted types are the ones you would have declared
by hand.

Getting there depends on the specification being in good shape first, which is why
this module doesn't work from the raw document. It normalizes the spec through the
Expand Down
7 changes: 4 additions & 3 deletions README/intro.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
Generated code has a reputation for being obviously generated. This module tries
hard not to earn it: output is run through `goimports` and `gofumpt`, names are
converted to Go conventions rather than transliterated, and the emitted types are
the ones you would have declared by hand.
hard not to earn it: each file imports exactly the packages it uses, sorted,
and is formatted with `gofumpt`, names are converted to Go conventions rather
than transliterated, and the emitted types are the ones you would have declared
by hand.

Getting there depends on the specification being in good shape first, which is why
this module doesn't work from the raw document. It normalizes the spec through the
Expand Down
4 changes: 1 addition & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ require (
github.com/ettle/strcase v0.2.0
github.com/go-api-libs/api v0.0.0-20261111173335-ea65a0d2e99a
github.com/spf13/afero v1.15.0
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a
mvdan.cc/gofumpt v0.12.0
)

Expand All @@ -26,8 +25,7 @@ require (
github.com/MarkRosemaker/yaml2json v0.0.0-20261109120453-1b901dbf7e8f // indirect
github.com/go-api-libs/types v0.0.0-20261109120451-6cd1daca4971 // indirect
golang.org/x/exp v0.0.0-20261112173441-d10d3b464990 // indirect
golang.org/x/mod v0.43.0 // indirect
golang.org/x/sync v0.25.0 // indirect
golang.org/x/text v0.44.0 // indirect
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
4 changes: 0 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,6 @@ github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
golang.org/x/exp v0.0.0-20261112173441-d10d3b464990 h1:Ki27Rkann+mW+hv34e1eegTr8npmBX7sTq/1TV1eW8Y=
golang.org/x/exp v0.0.0-20261112173441-d10d3b464990/go.mod h1:J3U+E8RzytcGvwz+uJuAP4zULJ2TkAQBnmPZMexpdXs=
golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY=
golang.org/x/sync v0.25.0 h1:dJnifr0nMV8/SBnBvdo4eSGGnrc3O4FFx6IqvtLcmRs=
golang.org/x/sync v0.25.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo=
golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY=
golang.org/x/tools v0.52.1-0.20261106145633-d407941a339a h1:Yqozs0FNPRoPGS4hNGlrNwRENWr5H5nVG9sN/f+5640=
Expand Down
130 changes: 130 additions & 0 deletions render/imports.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
package render

import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/token"
"slices"
"strings"
)

// importPaths is every package generated code uses, by the name it is used by. The import section of a generated file
// is written from it (see [writeImports]), not from the template, so a package added to a template must be added here.
var importPaths = map[string]string{
"base64": "encoding/base64",
"bytes": "bytes",
"cmp": "cmp",
"context": "context",
"errors": "errors",
"filepath": "path/filepath",
"fmt": "fmt",
"fs": "io/fs",
"http": "net/http",
"httptest": "net/http/httptest",
"io": "io",
"json": "encoding/json/v2",
"jsontext": "encoding/json/jsontext",
"maps": "maps",
"net": "net",
"os": "os",
"slices": "slices",
"slog": "log/slog",
"strconv": "strconv",
"strings": "strings",
"testing": "testing",
"time": "time",
"url": "net/url",
"uuid": "uuid",

"api": "github.com/go-api-libs/api",
"cassette": "github.com/MarkRosemaker/cassette",
"civil": "cloud.google.com/go/civil",
"jsonutil": "github.com/MarkRosemaker/jsonutil",
"server": "github.com/go-api-libs/api/server",
"types": "github.com/go-api-libs/types",
}

// writeImports gives the Go source src the import section it needs: each package of [importPaths] it uses, and no
// other, the standard library's first, then the rest, each group sorted by path. Whatever imports src has are
// replaced: what a file uses is read off its code, so a template needs no import section of its own.
//
// A package is used where its name is the left side of a selector, such as http in http.StatusOK, and the name is
// declared nowhere in the file, so that a variable of the same name does not count.
func writeImports(name string, src []byte) ([]byte, error) {
fset := token.NewFileSet()

f, err := parser.ParseFile(fset, name, src, parser.ParseComments)
if err != nil {
return nil, err
}

used := map[string]bool{}

ast.Inspect(f, func(n ast.Node) bool {
if sel, ok := n.(*ast.SelectorExpr); ok {
// an identifier the parser could not resolve in the file: a package, or something of the universe scope
if id, ok := sel.X.(*ast.Ident); ok && id.Obj == nil && importPaths[id.Name] != "" {
used[id.Name] = true
}
}

return true
})

var std, other []string

for name := range used {
path := importPaths[name]
if first, _, _ := strings.Cut(path, "/"); strings.Contains(first, ".") {
other = append(other, path)
} else {
std = append(std, path)
}
}

slices.Sort(std)
slices.Sort(other)

var block bytes.Buffer
if len(std)+len(other) > 0 {
block.WriteString("\n\nimport (\n")

for _, path := range std {
fmt.Fprintf(&block, "\t%q\n", path)
}

if len(std) > 0 && len(other) > 0 {
block.WriteString("\n")
}

for _, path := range other {
fmt.Fprintf(&block, "\t%q\n", path)
}

block.WriteString(")")
}

// the source without its imports, and the new ones right after the package clause
out := slices.Clone(src[:fset.Position(f.Name.End()).Offset])
out = append(out, block.Bytes()...)
at := fset.Position(f.Name.End()).Offset

for _, decl := range f.Decls {
gen, ok := decl.(*ast.GenDecl)
if !ok || gen.Tok != token.IMPORT {
continue
}

out = append(out, src[at:fset.Position(gen.Pos()).Offset]...)

// and the blank lines after it, which the space before the next declaration already holds
at = fset.Position(gen.End()).Offset
for at < len(src) && (src[at] == '\n' || src[at] == ' ' || src[at] == '\t') {
at++
}
}

return append(out, src[at:]...), nil
}
122 changes: 122 additions & 0 deletions render/imports_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package render

import "testing"

func TestWriteImports(t *testing.T) {
for _, tc := range []struct {
name, src, want string
}{
{
name: "adds what is used, the standard library first, each group sorted",
src: `package p

func f() (*url.URL, error) {
_ = api.NewErrCustom
_ = civil.Date{}
return nil, errors.New(strconv.Itoa(http.StatusOK))
}
`,
want: `package p

import (
"errors"
"net/http"
"net/url"
"strconv"

"cloud.google.com/go/civil"
"github.com/go-api-libs/api"
)

func f() (*url.URL, error) {
_ = api.NewErrCustom
_ = civil.Date{}
return nil, errors.New(strconv.Itoa(http.StatusOK))
}
`,
},
{
name: "drops what is not used, and replaces imports that guessed wrong",
src: `package p

import (
"encoding/json"
"fmt"
"strings"
)

import "os"

func f(b []byte, v any) error { return json.Unmarshal(b, v) }
`,
want: `package p

import (
"encoding/json/v2"
)

func f(b []byte, v any) error { return json.Unmarshal(b, v) }
`,
},
{
name: "a variable of a package's name is no use of it",
src: `package p

func f(url struct{ Host string }) string { return url.Host }
`,
want: `package p

func f(url struct{ Host string }) string { return url.Host }
`,
},
{
name: "a name it does not know is left to the compiler",
src: `package p

func f() { other.Do() }
`,
want: `package p

func f() { other.Do() }
`,
},
{
name: "keeps the comments around",
src: `// Code generated. DO NOT EDIT.

// Package p is p.
package p

// f is f.
func f() string { return fmt.Sprint(1) }
`,
want: `// Code generated. DO NOT EDIT.

// Package p is p.
package p

import (
"fmt"
)

// f is f.
func f() string { return fmt.Sprint(1) }
`,
},
} {
t.Run(tc.name, func(t *testing.T) {
got, err := writeImports("p.go", []byte(tc.src))
if err != nil {
t.Fatal(err)
}

if string(got) != tc.want {
t.Errorf("got:\n%s\nwant:\n%s", got, tc.want)
}
})
}

if _, err := writeImports("p.go", []byte("package p\n\nfunc {")); err == nil {
t.Error("source that does not parse: got no error")
}
}
13 changes: 6 additions & 7 deletions render/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (

"github.com/MarkRosemaker/openapi-codegen/config"
"github.com/MarkRosemaker/openapi-codegen/ir"
"golang.org/x/tools/imports"
gofumpt "mvdan.cc/gofumpt/format"
)

Expand Down Expand Up @@ -85,8 +84,8 @@ func FilesFromFS(fsys fs.FS, doc *ir.Document, g config.Generate) ([]File, error
return files, nil
}

// RenderTemplate executes a template string against the IR document and
// post-processes the result with goimports and gofumpt.
// RenderTemplate executes a template string against the IR document, writes the imports the result uses (see
// [writeImports]), and formats it with gofumpt.
func RenderTemplate(tmplName, tmplContent string, doc *ir.Document) ([]byte, error) {
tmpl, err := template.New(tmplName).Funcs(templateFuncs()).Parse(tmplContent)
if err != nil {
Expand All @@ -102,13 +101,13 @@ func RenderTemplate(tmplName, tmplContent string, doc *ir.Document) ([]byte, err
return nil, nil
}

// goimports: remove unused imports, add missing ones.
processed, err := imports.Process(tmplName, buf.Bytes(), nil)
// the imports the code uses, from a fixed table, rather than goimports' guesses from what it finds installed
processed, err := writeImports(tmplName, buf.Bytes())
if err != nil {
return buf.Bytes(), fmt.Errorf("goimports: %w\n---\n%s", err, buf.String())
return buf.Bytes(), fmt.Errorf("imports: %w\n---\n%s", err, buf.String())
}

// gofumpt: stricter formatting on top of goimports output.
// gofumpt: stricter formatting on top.
return gofumpt.Source(processed, gofumpt.Options{
LangVersion: "go1.25",
ModulePath: "github.com/MarkRosemaker/openapi-codegen",
Expand Down
6 changes: 3 additions & 3 deletions render/render_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,8 +294,8 @@ func TestRenderTemplate_ParseError(t *testing.T) {
}
}

func TestRenderTemplate_GoimportsError(t *testing.T) {
// Template that produces invalid Go (not parseable by goimports).
func TestRenderTemplate_InvalidGo(t *testing.T) {
// Template that produces invalid Go, which has no imports to read off.
_, err := render.RenderTemplate("bad.go.tmpl", "not valid go at all @@@@", nil)
if err == nil {
t.Fatal("expected error for non-Go template output")
Expand Down Expand Up @@ -638,7 +638,7 @@ func containsStr(s, sub string) bool {
return false
}

// A template with nothing to write is no file, rather than an empty one goimports refuses: the types' tests where no
// A template with nothing to write is no file, rather than an empty one that does not parse: the types' tests where no
// enum is declared.
func TestFilesFromFS_NothingToWrite(t *testing.T) {
t.Parallel()
Expand Down
19 changes: 0 additions & 19 deletions render/templates/client.gen.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,6 @@

package {{.PackageName}}

import (
"bytes"
"cmp"
"context"
"encoding/json/v2"
"fmt"
"maps"
"net"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"time"

"cloud.google.com/go/civil"
"github.com/go-api-libs/api"
"github.com/go-api-libs/types"
)

const defaultUserAgent = "{{.UserAgent}}"

Expand Down
Loading
Loading