diff --git a/go.mod b/go.mod index 94e90be..b20615a 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( github.com/spf13/cobra v1.1.3 github.com/spf13/pflag v1.0.5 github.com/stretchr/testify v1.7.0 + golang.org/x/mod v0.4.2 k8s.io/api v0.21.2 k8s.io/apimachinery v0.21.2 k8s.io/apiserver v0.21.2 diff --git a/pkg/builder/doc.go b/pkg/builder/doc.go index 37711b0..392d9f7 100644 --- a/pkg/builder/doc.go +++ b/pkg/builder/doc.go @@ -43,7 +43,7 @@ limitations under the License. // Install the code generators (from your module): // // $ go get sigs.k8s.io/apiserver-runtime/tools/apiserver-runtime-gen -// $ apiserver-runtime-gen --install +// $ apiserver-runtime-gen --install-generators // // Add the code generation tag to you main package: // diff --git a/tools/apiserver-runtime-gen/main.go b/tools/apiserver-runtime-gen/main.go index 464cdaf..3f714d6 100644 --- a/tools/apiserver-runtime-gen/main.go +++ b/tools/apiserver-runtime-gen/main.go @@ -12,6 +12,7 @@ import ( "strings" "github.com/spf13/cobra" + "golang.org/x/mod/modfile" ) var bin, output string @@ -166,15 +167,11 @@ func main() { cmd.Flags().BoolVar(&install, "install-generators", true, "Go get the generators") var defaultModule string - why := exec.Command("go", "mod", "why") - why.Stderr = os.Stderr - if m, err := why.Output(); err == nil { - parts := strings.Split(string(m), "\n") - if len(parts) > 1 { - defaultModule = parts[1] + cwd, _ := os.Getwd() + if modRoot := findModuleRoot(cwd); modRoot != "" { + if b, err := ioutil.ReadFile(path.Join(modRoot, "go.mod")); err == nil { + defaultModule = modfile.ModulePath(b) } - } else { - fmt.Fprintf(os.Stderr, "cannot parse go module: %v\n", err) } cmd.Flags().StringVar(&module, "module", defaultModule, "Go module of the apiserver.") @@ -226,3 +223,18 @@ func getCmd(cmd string, args ...string) *exec.Cmd { e.Args = append(e.Args, args...) return e } + +func findModuleRoot(dir string) string { + for { + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { + return dir + } + + parentDIR := path.Dir(dir) + if parentDIR == dir { + break + } + dir = parentDIR + } + return "" +}