"os"
"os/exec"
"path/filepath"
+ "runtime"
"strings"
"testing"
)
t.Fatalf("%s: %v\n%s", strings.Join(cmd.Args, " "), err, cmd.Stderr)
}
- if err := os.WriteFile(filepath.Join(dir, fp+"_defs.go"), out, 0644); err != nil {
+ fn := fp + "_defs.go"
+ if err := os.WriteFile(filepath.Join(dir, fn), out, 0644); err != nil {
t.Fatal(err)
}
+
+ // Verify that command line arguments are not rewritten in the generated comment,
+ // see go.dev/issue/52063
+ hasGeneratedByComment := false
+ for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
+ cgoExe := "cgo"
+ if runtime.GOOS == "windows" {
+ cgoExe = "cgo.exe"
+ }
+ if !strings.HasPrefix(line, "// "+cgoExe+" -godefs") {
+ continue
+ }
+ if want := "// " + cgoExe + " " + strings.Join(cmd.Args[3:], " "); line != want {
+ t.Errorf("%s: got generated comment %q, want %q", fn, line, want)
+ }
+ hasGeneratedByComment = true
+ break
+ }
+
+ if !hasGeneratedByComment {
+ t.Errorf("%s: comment with generating cgo -godefs command not found", fn)
+ }
}
main, err := os.ReadFile(filepath.Join("testdata", "main.go"))
)
// godefs returns the output for -godefs mode.
-func (p *Package) godefs(f *File) string {
+func (p *Package) godefs(f *File, args []string) string {
var buf bytes.Buffer
fmt.Fprintf(&buf, "// Code generated by cmd/cgo -godefs; DO NOT EDIT.\n")
- fmt.Fprintf(&buf, "// %s %s\n", filepath.Base(os.Args[0]), strings.Join(os.Args[1:], " "))
+ fmt.Fprintf(&buf, "// %s %s\n", filepath.Base(args[0]), strings.Join(args[1:], " "))
fmt.Fprintf(&buf, "\n")
override := make(map[string]string)
usage()
}
+ // Save original command line arguments for the godefs generated comment. Relative file
+ // paths in os.Args will be rewritten to absolute file paths in the loop below.
+ osArgs := make([]string, len(os.Args))
+ copy(osArgs, os.Args[:])
goFiles := args[i:]
for _, arg := range args[:i] {
p.PackagePath = f.Package
p.Record(f)
if *godefs {
- os.Stdout.WriteString(p.godefs(f))
+ os.Stdout.WriteString(p.godefs(f, osArgs))
} else {
p.writeOutput(f, input)
}