Browse Source

codecgen: add support for go1.11 modules (#266)

Without this change, when using the new module support in go 1.11, codecgen would not be able to determine the proper package path and fail.

Since the golang.org/x/tools/go/packages does not yet support previous go versions, use a build tag to revert to the previous mechanism on older go versions.
Vincent Vanackere 7 years ago
parent
commit
ed9a3b5f07

+ 2 - 3
codec/codecgen/gen.go

@@ -11,7 +11,6 @@ import (
 	"flag"
 	"fmt"
 	"go/ast"
-	"go/build"
 	"go/parser"
 	"go/token"
 	"math/rand"
@@ -127,7 +126,7 @@ func Generate(outfile, buildTag, codecPkgPath string,
 	if err != nil {
 		return
 	}
-	pkg, err := build.Default.ImportDir(absdir, build.AllowBinary)
+	importPath, err := pkgPath(absdir)
 	if err != nil {
 		return
 	}
@@ -154,7 +153,7 @@ func Generate(outfile, buildTag, codecPkgPath string,
 		StructTags:      st,
 		NoExtensions:    noExtensions,
 	}
-	tv.ImportPath = pkg.ImportPath
+	tv.ImportPath = importPath
 	if tv.ImportPath == tv.CodecImportPath {
 		tv.CodecPkgFiles = true
 		tv.CodecPkgName = "codec"

+ 24 - 0
codec/codecgen/goversion_pkgpath_gte_go111.go

@@ -0,0 +1,24 @@
+// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a MIT license found in the LICENSE file.
+
+// +build go1.11
+
+package main
+
+import (
+	"fmt"
+
+	"golang.org/x/tools/go/packages"
+)
+
+func pkgPath(dir string) (string, error) {
+	pkgs, err := packages.Load(&packages.Config{Dir: dir}, ".")
+	if err != nil {
+		return "", err
+	}
+	if len(pkgs) != 1 {
+		return "", fmt.Errorf("Could not read package (%d package found)", len(pkgs))
+	}
+	pkg := pkgs[0]
+	return pkg.PkgPath, nil
+}

+ 18 - 0
codec/codecgen/goversion_pkgpath_lt_go111.go

@@ -0,0 +1,18 @@
+// Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved.
+// Use of this source code is governed by a MIT license found in the LICENSE file.
+
+// +build !go1.11
+
+package main
+
+import (
+	"go/build"
+)
+
+func pkgPath(dir string) (string, error) {
+	pkg, err := build.Default.ImportDir(dir, build.AllowBinary)
+	if err != nil {
+		return "", err
+	}
+	return pkg.ImportPath, nil
+}