Skip to content

Commit

Permalink
Merge pull request #112061 from JoelSpeed/proto-gopath
Browse files Browse the repository at this point in the history
Ensure go-to-protobuf gen can run when not in GOPATH

Kubernetes-commit: fdada9242fdaf446320843cbc24eb006e122cb89
  • Loading branch information
k8s-publishing-bot committed Mar 10, 2023
2 parents 4400d5f + 6173bf7 commit dde8213
Showing 1 changed file with 19 additions and 0 deletions.
19 changes: 19 additions & 0 deletions cmd/go-to-protobuf/protobuf/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ type Generator struct {
KeepGogoproto bool
SkipGeneratedRewrite bool
DropEmbeddedFields string
TrimPathPrefix string
}

func New() *Generator {
Expand Down Expand Up @@ -95,6 +96,7 @@ func (g *Generator) BindFlags(flag *flag.FlagSet) {
flag.BoolVar(&g.KeepGogoproto, "keep-gogoproto", g.KeepGogoproto, "If true, the generated IDL will contain gogoprotobuf extensions which are normally removed")
flag.BoolVar(&g.SkipGeneratedRewrite, "skip-generated-rewrite", g.SkipGeneratedRewrite, "If true, skip fixing up the generated.pb.go file (debugging only).")
flag.StringVar(&g.DropEmbeddedFields, "drop-embedded-fields", g.DropEmbeddedFields, "Comma-delimited list of embedded Go types to omit from generated protobufs")
flag.StringVar(&g.TrimPathPrefix, "trim-path-prefix", g.TrimPathPrefix, "If set, trim the specified prefix from --output-package when generating files.")
}

func Run(g *Generator) {
Expand Down Expand Up @@ -200,6 +202,7 @@ func Run(g *Generator) {

c.Verify = g.Common.VerifyOnly
c.FileTypes["protoidl"] = NewProtoFile()
c.TrimPathPrefix = g.TrimPathPrefix

// order package by imports, importees first
deps := deps(c, protobufNames.packages)
Expand Down Expand Up @@ -270,6 +273,22 @@ func Run(g *Generator) {
outputPath = filepath.Join(g.VendorOutputBase, p.OutputPath())
}

// When working outside of GOPATH, we typically won't want to generate the
// full path for a package. For example, if our current project's root/base
// package is github.com/foo/bar, outDir=., p.Path()=github.com/foo/bar/generated,
// then we really want to be writing files to ./generated, not ./github.com/foo/bar/generated.
// The following will trim a path prefix (github.com/foo/bar) from p.Path() to arrive at
// a relative path that works with projects not in GOPATH.
if g.TrimPathPrefix != "" {
separator := string(filepath.Separator)
if !strings.HasSuffix(g.TrimPathPrefix, separator) {
g.TrimPathPrefix += separator
}

path = strings.TrimPrefix(path, g.TrimPathPrefix)
outputPath = strings.TrimPrefix(outputPath, g.TrimPathPrefix)
}

// generate the gogoprotobuf protoc
cmd := exec.Command("protoc", append(args, path)...)
out, err := cmd.CombinedOutput()
Expand Down

0 comments on commit dde8213

Please sign in to comment.