From 57d50b3810fdd51818b5ab819682f69b07e57ea0 Mon Sep 17 00:00:00 2001 From: Steven Hartland Date: Fri, 25 Nov 2022 11:27:43 +0000 Subject: [PATCH] fix(oapi-codegen): package name detection Re-add package name detection which was removed removed in the configuration rework. This also improves it by using go list to detect current package names. --- cmd/oapi-codegen/oapi-codegen.go | 42 ++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/cmd/oapi-codegen/oapi-codegen.go b/cmd/oapi-codegen/oapi-codegen.go index 957b90fef6..aa33a76ea7 100644 --- a/cmd/oapi-codegen/oapi-codegen.go +++ b/cmd/oapi-codegen/oapi-codegen.go @@ -17,7 +17,9 @@ import ( "flag" "fmt" "os" + "os/exec" "path" + "path/filepath" "runtime/debug" "strings" @@ -238,6 +240,10 @@ func main() { // fields. opts.Configuration = opts.UpdateDefaults() + if err := detectPackageName(&opts); err != nil { + errExit("%s\n", err) + } + // Now, ensure that the config options are valid. if err := opts.Validate(); err != nil { errExit("configuration error: %v\n", err) @@ -309,6 +315,42 @@ func loadTemplateOverrides(templatesDir string) (map[string]string, error) { return templates, nil } +// detectPackageName detects and sets PackageName if not already set. +func detectPackageName(cfg *configuration) error { + if cfg.PackageName != "" { + return nil + } + + if cfg.OutputFile != "" { + // Determine from the package name of the output file. + dir := filepath.Dir(cfg.PackageName) + cmd := exec.Command("go", "list", "-f", "{{.Name}}", dir) + out, err := cmd.CombinedOutput() + if err != nil { + outStr := string(out) + switch { + case strings.Contains(outStr, "expected 'package', found 'EOF'"): + // Redirecting the output to current directory which hasn't + // written anything yet, ignore. + case strings.HasPrefix(outStr, "no Go files in"): + // No go files yet, ignore. + default: + // Unexpected failure report. + return fmt.Errorf("detect package name for %q output: %q: %w", dir, string(out), err) + } + } else { + cfg.PackageName = string(out) + return nil + } + } + + // Fallback to determining from the spec file name. + parts := strings.Split(filepath.Base(flag.Arg(0)), ".") + cfg.PackageName = codegen.LowercaseFirstCharacter(codegen.ToCamelCase(parts[0])) + + return nil +} + // updateConfigFromFlags updates a loaded configuration from flags. Flags // override anything in the file. We generate errors for command line options // associated with the old style configuration