diff --git a/main.go b/main.go index 37c779b..a2c0ea0 100644 --- a/main.go +++ b/main.go @@ -59,6 +59,24 @@ func main() { exechelper.WithEnvirons(os.Environ()...), exechelper.WithStderr(os.Stderr), } + + // Extract the GOOS + goos, ok := os.LookupEnv("GOOS") + if !ok { + cmdStr := "go env GOOS" + goosBytes, GoosErr := exechelper.Output(cmdStr, options...) + if GoosErr != nil { + log.Fatalf("error extracting GOOS: %+v", GoosErr) + } + goos = strings.TrimSpace(string(goosBytes)) + } + + // Compute the filename, and remove any old one *before* we build up the list of packages we need + filename := fmt.Sprintf("imports_%s.go", goos) + if err := os.Remove(filename); err != nil && !os.IsNotExist(err) { + log.Fatalf("unable to remove %s because %+v", filename, err) + } + // Get the module Path and Dir (example: Path: github.com/foo/bar Dir: /home/bob/git/bar) modBytes, err := exechelper.Output(`go list -m -f '{{printf "%s %s" .Path .Dir}}'`, options...) if err != nil { @@ -91,29 +109,13 @@ func main() { } sort.Strings(input.Packages) - // Extract the GOOS - goos, ok := os.LookupEnv("GOOS") - if !ok { - cmdStr := "go env GOOS" - options := []*exechelper.Option{ - exechelper.WithStderr(os.Stderr), - exechelper.WithStdout(os.Stdout), - exechelper.WithEnvirons(os.Environ()...), - } - goosBytes, GoosErr := exechelper.Output(cmdStr, options...) - if GoosErr != nil { - log.Fatalf("error extracting GOOS: %+v", GoosErr) - } - goos = strings.TrimSpace(string(goosBytes)) - } - // Create the template tmpl := template.Must(template.New(fmt.Sprintf("imports_%s.go", goos)).Parse(importsGoTmpl)) // Create the imports.go file - f, err := os.Create(fmt.Sprintf("imports_%s.go", goos)) + f, err := os.Create(filename) if err != nil { - log.Fatalf("error creating file: %q: %+v", fmt.Sprintf("imports_%s.go", goos), err) + log.Fatalf("error creating file: %q: %+v", filename, err) } defer func() { _ = f.Close() }() if err := tmpl.Execute(f, input); err != nil {