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
54 changes: 38 additions & 16 deletions gen/gen.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"go/types"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
Expand Down Expand Up @@ -62,8 +63,12 @@ func Generate(o Options) ([]File, error) {
cfg := &packages.Config{
Mode: packages.NeedName | packages.NeedTypes | packages.NeedSyntax | packages.NeedModule | packages.NeedFiles,
Dir: o.Dir,
Env: loaderEnv(os.Environ()),
}
goflags, err := goEnv(o.Dir, "GOFLAGS")
if err != nil {
return nil, err
}
cfg.Env = loaderEnv(os.Environ(), goflags)
if len(o.Tags) > 0 {
cfg.BuildFlags = []string{"-tags=" + strings.Join(o.Tags, ",")}
}
Expand Down Expand Up @@ -243,22 +248,39 @@ func isGenerated(p *packages.Package) bool {
return false
}

// loaderEnv is env without -trimpath in GOFLAGS: the generator reads doc comments and enum
// declarations from the files that dependencies' positions name, and a trimmed build names them
// by module path instead of the file on disk.
func loaderEnv(env []string) []string {
out := make([]string, 0, len(env))
// loaderEnv is env with goflags, the effective GOFLAGS, minus -trimpath: the generator reads
// doc comments and enum declarations from the files that dependencies' positions name, and a
// trimmed build names them by module path instead of the file on disk. goflags comes from
// go env, so a -trimpath set with go env -w is dropped too; setting GOFLAGS in the environment
// overrides the go env file, so its other flags are kept by carrying them over, and an empty
// GOFLAGS would read as unset and bring the file back, so -trimpath=false is always written.
func loaderEnv(env []string, goflags string) []string {
out := make([]string, 0, len(env)+1)
for _, kv := range env {
if flags, ok := strings.CutPrefix(kv, "GOFLAGS="); ok {
kept := make([]string, 0, 4)
for _, f := range strings.Fields(flags) {
if f != "-trimpath" && f != "-trimpath=true" {
kept = append(kept, f)
}
}
kv = "GOFLAGS=" + strings.Join(kept, " ")
if !strings.HasPrefix(kv, "GOFLAGS=") {
out = append(out, kv)
}
}
kept := make([]string, 0, 4)
for _, f := range strings.Fields(goflags) {
if f != "-trimpath" && f != "-trimpath=true" && f != "-trimpath=false" {
kept = append(kept, f)
}
out = append(out, kv)
}
return out
kept = append(kept, "-trimpath=false")
return append(out, "GOFLAGS="+strings.Join(kept, " "))
}

// goEnv returns the value go env reports for name in dir, which honors both the environment and
// the go env file.
func goEnv(dir, name string) (string, error) {
cmd := exec.Command("go", "env", name)
cmd.Dir = dir
var stderr bytes.Buffer
cmd.Stderr = &stderr
out, err := cmd.Output()
if err != nil {
return "", fmt.Errorf("go env %s: %w: %s", name, err, strings.TrimSpace(stderr.String()))
}
return strings.TrimSpace(string(out)), nil
}
30 changes: 28 additions & 2 deletions gen/gen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -665,9 +665,35 @@ func TestLookupTag(t *testing.T) {
}

func TestLoaderEnvDropsTrimpath(t *testing.T) {
got := loaderEnv([]string{"HOME=/h", "GOFLAGS=-trimpath -tags=x -p=4", "GOFLAGS=-trimpath=true"})
want := []string{"HOME=/h", "GOFLAGS=-tags=x -p=4", "GOFLAGS="}
got := loaderEnv([]string{"HOME=/h", "GOFLAGS=-trimpath", "PATH=/bin"}, "-trimpath -tags=x -trimpath=true -p=4")
want := []string{"HOME=/h", "PATH=/bin", "GOFLAGS=-tags=x -p=4 -trimpath=false"}
if strings.Join(got, "|") != strings.Join(want, "|") {
t.Fatalf("loaderEnv = %q, want %q", got, want)
}
}

func TestGenerateReadsDependenciesWhenTheGoConfigTrimsPaths(t *testing.T) {
dir := moduleFiles(t, "", map[string]string{
"kinds/kinds.go": "package kinds\n\ntype Status string\n\nconst (\n" +
"\t// Open is waiting for work.\n\tOpen Status = \"Open\"\n\tClosed Status = \"Closed\"\n)\n",
"models/order.go": "package models\n\nimport (\n\t\"github.com/emoss08/keel\"\n" +
"\t\"example.com/app/kinds\"\n)\n\ntype Order struct {\n\tkeel.Table ~keel:\"orders\"~\n" +
"\tID string ~keel:\"id,pk\"~\n\tStatus kinds.Status ~keel:\"status\"~\n}\n",
})
goenv := filepath.Join(t.TempDir(), "env")
if err := os.WriteFile(goenv, []byte("GOFLAGS=-trimpath\n"), 0o644); err != nil {
t.Fatal(err)
}
t.Setenv("GOENV", goenv)
t.Setenv("GOFLAGS", "")

if _, err := Generate(Options{Dir: dir, Patterns: []string{"./models"}}); err != nil {
t.Fatal(err)
}
}

func TestGoEnvReportsItsFailure(t *testing.T) {
if _, err := goEnv(filepath.Join(t.TempDir(), "missing"), "GOFLAGS"); err == nil {
t.Fatal("go env ran in a directory that does not exist")
}
}
7 changes: 6 additions & 1 deletion gen/methods_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,13 @@ import (
func keelTypes(t *testing.T) *types.Package {
t.Helper()
_, file, _, _ := runtime.Caller(0)
dir := filepath.Dir(filepath.Dir(file))
goflags, err := goEnv(dir, "GOFLAGS")
if err != nil {
t.Fatal(err)
}
pkgs, err := packages.Load(&packages.Config{Mode: packages.NeedName | packages.NeedTypes,
Dir: filepath.Dir(filepath.Dir(file)), Env: loaderEnv(os.Environ())}, keelPath)
Dir: dir, Env: loaderEnv(os.Environ(), goflags)}, keelPath)
if err != nil {
t.Fatal(err)
}
Expand Down
Loading