Fix pkger generating the wrong package name for pkger.go

The issue is that, if pkger.go is created (empty) before the `go list
-json` call it will fail and give the generic directory name instead of the
actual package name under the directory. This is fine in most cases,
except when the package name differs from the directory name - which is
allowed. Then pkger.go will conflict and fail to compile with the rest
of *.go under the same directory.

To fix, we simply obtain the real package name before creating the dummy
pkger.go file and then pass the name into the file.
This commit is contained in:
Eric Chen 2020-03-11 03:31:03 -07:00
parent 5b8abbabca
commit 9552dcf46d
1 changed files with 6 additions and 11 deletions

View File

@ -124,6 +124,11 @@ func (e *packCmd) Flags() *flag.FlagSet {
}
func Package(info here.Info, out string, decls parser.Decls) error {
c, err := here.Dir(filepath.Dir(out))
if err != nil {
return err
}
os.RemoveAll(out)
defer func() {
if err := recover(); err != nil {
@ -137,18 +142,8 @@ func Package(info here.Info, out string, decls parser.Decls) error {
}
defer f.Close()
c, err := here.Dir(filepath.Dir(out))
if err != nil {
return err
}
name := c.Name
if info.Module.Main {
name = "main"
}
fmt.Fprintf(f, "// Code generated by pkger; DO NOT EDIT.\n\n")
fmt.Fprintf(f, "package %s\n\n", name)
fmt.Fprintf(f, "package %s\n\n", c.Name)
fmt.Fprintf(f, "import (\n\t\"github.com/markbates/pkger\"\n\t")
fmt.Fprintf(f, "\"github.com/markbates/pkger/pkging/mem\"\n)\n\n")
fmt.Fprintf(f, "var _ = pkger.Apply(mem.UnmarshalEmbed([]byte(`")