@@ -17,7 +17,9 @@ import (
1717 "flag"
1818 "fmt"
1919 "os"
20+ "os/exec"
2021 "path"
22+ "path/filepath"
2123 "runtime/debug"
2224 "strings"
2325
@@ -238,6 +240,10 @@ func main() {
238240 // fields.
239241 opts .Configuration = opts .UpdateDefaults ()
240242
243+ if err := detectPackageName (& opts ); err != nil {
244+ errExit ("%s\n " , err )
245+ }
246+
241247 // Now, ensure that the config options are valid.
242248 if err := opts .Validate (); err != nil {
243249 errExit ("configuration error: %v\n " , err )
@@ -309,6 +315,42 @@ func loadTemplateOverrides(templatesDir string) (map[string]string, error) {
309315 return templates , nil
310316}
311317
318+ // detectPackageName detects and sets PackageName if not already set.
319+ func detectPackageName (cfg * configuration ) error {
320+ if cfg .PackageName != "" {
321+ return nil
322+ }
323+
324+ if cfg .OutputFile != "" {
325+ // Determine from the package name of the output file.
326+ dir := filepath .Dir (cfg .PackageName )
327+ cmd := exec .Command ("go" , "list" , "-f" , "{{.Name}}" , dir )
328+ out , err := cmd .CombinedOutput ()
329+ if err != nil {
330+ outStr := string (out )
331+ switch {
332+ case strings .Contains (outStr , "expected 'package', found 'EOF'" ):
333+ // Redirecting the output to current directory which hasn't
334+ // written anything yet, ignore.
335+ case strings .HasPrefix (outStr , "no Go files in" ):
336+ // No go files yet, ignore.
337+ default :
338+ // Unexpected failure report.
339+ return fmt .Errorf ("detect package name for %q output: %q: %w" , dir , string (out ), err )
340+ }
341+ } else {
342+ cfg .PackageName = string (out )
343+ return nil
344+ }
345+ }
346+
347+ // Fallback to determining from the spec file name.
348+ parts := strings .Split (filepath .Base (flag .Arg (0 )), "." )
349+ cfg .PackageName = codegen .LowercaseFirstCharacter (codegen .ToCamelCase (parts [0 ]))
350+
351+ return nil
352+ }
353+
312354// updateConfigFromFlags updates a loaded configuration from flags. Flags
313355// override anything in the file. We generate errors for command line options
314356// associated with the old style configuration
0 commit comments