pax_global_header00006660000000000000000000000064143322562530014517gustar00rootroot0000000000000052 comment=168a8eac459f4c240ad54e1147f916056efd4c46 protobuild-0.3.0/000077500000000000000000000000001433225625300137025ustar00rootroot00000000000000protobuild-0.3.0/.github/000077500000000000000000000000001433225625300152425ustar00rootroot00000000000000protobuild-0.3.0/.github/workflows/000077500000000000000000000000001433225625300172775ustar00rootroot00000000000000protobuild-0.3.0/.github/workflows/ci.yml000066400000000000000000000105311433225625300204150ustar00rootroot00000000000000name: CI on: push: branches: [ main ] pull_request: branches: [ main ] jobs: check: name: Project checks runs-on: ubuntu-20.04 timeout-minutes: 5 steps: - name: Check out code uses: actions/checkout@v2 with: path: src/github.com/containerd/protobuild fetch-depth: 25 - name: Project checks uses: containerd/project-checks@v1 with: working-directory: src/github.com/containerd/protobuild test: name: Test strategy: matrix: os: [ ubuntu-20.04, windows-2022 ] fail-fast: false runs-on: ${{ matrix.os }} timeout-minutes: 5 steps: - name: Check out code uses: actions/checkout@v2 with: path: src/github.com/containerd/protobuild fetch-depth: 25 - name: Setup environment shell: bash run: | echo "GOPATH=${{ github.workspace }}" >> $GITHUB_ENV echo "${{ github.workspace }}/bin" >> $GITHUB_PATH - name: Check out code uses: actions/checkout@v2 with: path: src/github.com/containerd/protobuild - name: Test working-directory: src/github.com/containerd/protobuild run: | go test v1: name: Run with protoc-gen-go v1.3.5 runs-on: ubuntu-20.04 timeout-minutes: 5 steps: - name: Set up Go uses: actions/setup-go@v2 with: go-version: 1.16.x id: go - name: Setup environment shell: bash run: | echo "GOPATH=${{ github.workspace }}" >> $GITHUB_ENV echo "${{ github.workspace }}/bin" >> $GITHUB_PATH - name: Check out code uses: actions/checkout@v2 with: path: src/github.com/containerd/protobuild - name: Build working-directory: src/github.com/containerd/protobuild run: | go build . - name: Install protoc run: | curl -LO https://github.com/protocolbuffers/protobuf/releases/download/v3.5.0/protoc-3.5.0-linux-x86_64.zip sudo unzip -x protoc-3.5.0-linux-x86_64.zip -d /usr/local sudo chmod -R go+rX /usr/local/include sudo chmod go+x /usr/local/bin/protoc # Both google.golang.org/protobuf/cmd/protoc-gen-go and github.com/golang/protobuf/protoc-gen-go > 1.4.0 don't # support import_path. So this step has to use 1.3.x here. - name: Install protoc-gen-go run: | go install github.com/golang/protobuf/protoc-gen-go@v1.3.5 - name: Run protobuild to see all committed auto-generated files can be generated as is working-directory: src/github.com/containerd/protobuild run: | rm examples/foo/*.pb.* examples/bar/*.pb.* examples/nogrpc/*.pb.* export PATH=$(go env GOBIN):$PATH ./protobuild github.com/containerd/protobuild/examples/bar github.com/containerd/protobuild/examples/foo github.com/containerd/protobuild/examples/nogrpc git diff --exit-code v2: name: Run with protoc-gen-go v1.26 runs-on: ubuntu-20.04 timeout-minutes: 5 steps: - name: Set up Go uses: actions/setup-go@v2 with: go-version: 1.16.x id: go - name: Setup environment shell: bash run: | echo "GOPATH=${{ github.workspace }}" >> $GITHUB_ENV echo "${{ github.workspace }}/bin" >> $GITHUB_PATH - name: Check out code uses: actions/checkout@v2 with: path: src/github.com/containerd/protobuild - name: Build working-directory: src/github.com/containerd/protobuild run: | go build . - name: Install protoc run: | curl -LO https://github.com/protocolbuffers/protobuf/releases/download/v3.18.1/protoc-3.18.1-linux-x86_64.zip sudo unzip -x protoc-3.18.1-linux-x86_64.zip -d /usr/local sudo chmod -R go+rX /usr/local/include sudo chmod go+x /usr/local/bin/protoc - name: Install protoc-gen-go and protoc-gen-go-grpc run: | go install google.golang.org/protobuf/cmd/protoc-gen-go@v1.26 go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.1 - name: Run protobuild to see all committed auto-generated files can be generated as is working-directory: src/github.com/containerd/protobuild run: | rm examples/v2/*.pb.* export PATH=$(go env GOBIN):$PATH ./protobuild -f v2.toml github.com/containerd/protobuild/examples/v2 git diff --exit-code protobuild-0.3.0/.gitignore000066400000000000000000000004711433225625300156740ustar00rootroot00000000000000# Binaries for programs and plugins *.exe *.dll *.so *.dylib # Test binary, build with `go test -c` *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 .glide/ test.sh test.bat protobuild vendor/ protobuild-0.3.0/LICENSE000066400000000000000000000261351433225625300147160ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. protobuild-0.3.0/Protobuild.toml000066400000000000000000000133561433225625300167320ustar00rootroot00000000000000version = "unstable" # Generator defines which generator to go. The default is "go". This will be # formatted into the --xxx_out flag provided to protoc. Below, we have an # example that selects the ctrd vanity binary. # generator = "go" # Plugins allows one to specify one or more plugins for use in generation. # # The common example grpc is provided below. plugins = ["grpc"] # Control protoc include paths. Below are usually some good defaults, but feel # free to try it without them if it works for your project. [includes] # Include paths that will be added before all others. Typically, you want to # treat the root of the project as an include, but this may not be necessary. # # "." is included by default # before = ["."] # Paths that should be treated as include roots in relation to the vendor # directory. These will be calculated with the vendor directory nearest the # target package. # # This should be used only in cases where imports must be resolved from the # vendor package and not a GOPATH package. Most users should employ the # `packages` configuration and let protobuild resolve the existing package. # # With the example below, we import github.com/golang/protobuf from the vendor # directory. # # This is empty by default. # vendored = ["github.com/golang/protobuf"] # Packages will add imports that are relative to the vendor path or GOPATH. # # If in doubt, use this over `vendored` configuration for your project. # # This is empty by default. # packages = ["github.com/golang/protobuf"] # Paths that will be added untouched to the end of the includes. We use # a few paths to pickup the common install locations for protobuf. # This is the default. # after = ["usr/local/include", "/usr/include"] # This section let's us map protobuf imports to Go packages. These will become # `-M` directives in the call to the go protobuf generator. # # We have a few examples to map packages from the examples. [packages] "google/protobuf/empty.proto" = "github.com/containerd/protobuild/internal" # Overrides allows one to specify configuration overrides for specific # packages. Currently, only overriding the generator and plugin set are # supported. # # This can be used to use a different plugin set for a given package. [[overrides]] # Prefix specifies the protobuf import path to which the configuration # overrides apply. # # This works the same as the descriptors selection prefix except that each path # that is overridden must be specified, rather than applying to the whole tree. # # For this example, if there were a package that needed this overrides applied, # you would need to specify that explicitly in the prefixes list. This allows # one to granularly select which packages have the overrides. prefixes = ["github.com/containerd/protobuild/examples/nogrpc"] # Generator allows one to override the generator for the given prefix. # generator = "" # Plugins will override the entire plugin set for the specified prefix. plugins = [] # Descriptors allows you to aggregate generated protobuf descriptors under a # particular Go import path into a single, de-duplicated file. The result of # configuring this option for one or more paths will be a text format protobuf # dump of all the descriptors in the API. # # While this is useful for other applications that require access to # descriptors, the goal of this features is to provide visibility into changes # that may affect API stability. Each service, message and field will be # included in the file, along with dependencies. If a change occurs that # impacts API stability, it will be obvious in a diff with a file from the # previous version. # # Save these descriptors in your repository. When the next round of protobuf # changes are built and merged, additions and incompatible changes can be # detected by diffing these files. When you release, move this file to the # release version to keep track of the exports over time from various releases. # # This takes inspiration from Go's API checker in # https://github.com/golang/go/tree/master/api, but does so for protobufs. # Stablize packages and collections of packages of generated protobufs. [[descriptors]] # Prefix specifies the protobuf import prefix relative to items that you want # to stabilize. # # For example, if the files are imported as # github.com/containerd/protobuild/examples/foo/foo.proto, and you want to # stabilize everything in package "foo", it should be # "github.com/containerd/protobuild/example/foo". # # The example below stablizes the protobufs under the examples directory. The # generated descriptor file will include both the "foo" and "bar" subpackages. prefix = "github.com/containerd/protobuild/examples" # Target defines the output location of the merged descriptor file. target = "examples/next.pb.txt" # Ignore files by their protobuf import path. # # This operates directly on the FileDescriptorProto.Name field, so it will # filter out imported protobufs. This allows one to remove descriptors from the # result that don't impact API stability, such as generation extension # directives. # # The example below will exclude empty.proto. Experiment with this feature by # uncommenting the line below and notice that the description of that file will # be removed. # ignore_files = ["google/protobuf/empty.proto"] # TODO(stevvooe): Possibly automate build rejection under certain classes of # changes. Left alone now until we get a solid idea about the noise present in # this process. # # Remember that you can have multiple aggregation points for descriptors. Here, # we aggregate the descriptors for examples/foo, in addition to the above. # Uncomment these lines to try it out! # [[descriptors]] # target = "examples/foo/descriptors.pb.txt" # prefix = "github.com/containerd/protobuild/examples/foo" protobuild-0.3.0/README.md000066400000000000000000000055331433225625300151670ustar00rootroot00000000000000# protobuild [![Build Status](https://github.com/containerd/protobuild/workflows/CI/badge.svg)](https://github.com/containerd/protobuild/actions?query=workflow%3ACI) [![Go Report Card](https://goreportcard.com/badge/github.com/containerd/protobuild)](https://goreportcard.com/report/github.com/containerd/protobuild) Build protobufs in Go, easily. `protobuild` works by scanning the go package in a project and emitting correct `protoc` commands, configured with the plugins, packages and details of your choice. The main benefit is that it makes it much easier to consume external types from vendored projects. By integrating the protoc include paths with Go's vendoring and GOPATH, builds are much easier to keep consistent across a project. This comes from experience with generating protobufs with `go generate` in swarmkit and the tool used with containerd. It should replace both. ## Status Very early stages. ## Installation To ensure easy use with builds, we'll try to support `go get`. Install with the following command: ``` go get -u github.com/containerd/protobuild ``` ## Usage Protobuild works by providing a list of Go packages in which to build the protobufs. To get started with a project, you must do the following: 1. Create a `Protobuild.toml` file in the root of your Go project. Use the [example](Protobuild.toml) as a starting point. 2. Make sure that the packages where you want your protobuf files have a Go file in place. Usually, adding a `doc.go` file is sufficient. A package for protobuf should look like this: ``` foo.proto doc.go ``` Where the contents of `doc.go` will have a package declaration in it. See the [example](examples/foo/doc.go) for details. Make sure the package name corresponds to what is in the `go_package` option. 3. Run the `protobuild` command: ``` go list ./... | grep -v vendor | xargs protobuild ``` ## Version Compatibility Originally protoc-gen-go was supporting gRPC through its plugins mechanism. [However gRPC support is later extracted as protoc-gen-go-gprc binary](https://github.com/protocolbuffers/protobuf-go/releases/tag/v1.20.0#user-content-v1.20-grpc-support). To use protoc-gen-go and protoc-gen-go-grpc. Please specify `version = "2"` and both code generators instead of `plugins` like below. ``` version = "2" generators = ["go", "go-grpc"] ``` ## Project details protobuild is a containerd sub-project, licensed under the [Apache 2.0 license](./LICENSE). As a containerd sub-project, you will find the: * [Project governance](https://github.com/containerd/project/blob/master/GOVERNANCE.md), * [Maintainers](https://github.com/containerd/project/blob/master/MAINTAINERS), * and [Contributing guidelines](https://github.com/containerd/project/blob/master/CONTRIBUTING.md) information in our [`containerd/project`](https://github.com/containerd/project) repository. protobuild-0.3.0/cmd/000077500000000000000000000000001433225625300144455ustar00rootroot00000000000000protobuild-0.3.0/cmd/go-fix-acronym/000077500000000000000000000000001433225625300173045ustar00rootroot00000000000000protobuild-0.3.0/cmd/go-fix-acronym/main.go000066400000000000000000000040341433225625300205600ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "flag" "fmt" "go/format" "go/parser" "go/token" "io" "io/ioutil" "os" "regexp" "strings" ) const name = "go-fix-acronym" type stringArray []string func (w *stringArray) String() string { return strings.Join(*w, ",") } func (w *stringArray) Set(value string) error { *w = append(*w, value) return nil } type config struct { overwrite bool acronyms stringArray } func rewriteFile(c config, pattern *regexp.Regexp, path string) error { content, err := ioutil.ReadFile(path) if err != nil { return err } fset := token.NewFileSet() tree, err := parser.ParseFile(fset, path, content, parser.ParseComments) if err != nil { return err } rewriteNode(pattern, tree) var out io.Writer if c.overwrite { f, err := os.OpenFile(path, os.O_WRONLY, 0) if err != nil { return err } out = f defer f.Close() } else { out = os.Stdout } format.Node(out, fset, tree) return nil } func realMain(c config, args []string) error { pattern, err := compilePattern(c) if err != nil { return err } for _, path := range args { err := rewriteFile(c, pattern, path) if err != nil { return err } } return nil } func main() { var c config flag.BoolVar(&c.overwrite, "w", false, "write result to (source) file instead of stdout") flag.Var(&c.acronyms, "a", "acronym to capitalize") flag.Parse() err := realMain(c, flag.Args()) if err != nil { fmt.Fprintf(os.Stderr, "%s: %s\n", name, err) os.Exit(1) } } protobuild-0.3.0/cmd/go-fix-acronym/rewrite.go000066400000000000000000000032431433225625300213160ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "go/ast" "regexp" "strings" "golang.org/x/tools/go/ast/astutil" ) func compilePattern(c config) (*regexp.Regexp, error) { return regexp.Compile(strings.Join(c.acronyms, "|")) } func rewriteNode(pattern *regexp.Regexp, node ast.Node) { astutil.Apply( node, func(c *astutil.Cursor) bool { node := c.Node() ident, ok := node.(*ast.Ident) if !ok { return true } matches := pattern.FindAllStringSubmatchIndex(ident.Name, -1) if matches == nil { return true } var ( result string copied int ) for _, match := range matches { // If there are submatches, ignore the first element and only process the submatches. if len(match) > 2 { match = match[2:] } for i := 0; i < len(match); i += 2 { if match[i] == -1 { continue } result += ident.Name[copied:match[i]] result += strings.ToUpper(ident.Name[match[i]:match[i+1]]) copied = match[i+1] } } // Copy the rest. result += ident.Name[copied:len(ident.Name)] ident.Name = result return false }, nil, ) } protobuild-0.3.0/cmd/go-fix-acronym/rewrite_test.go000066400000000000000000000046501433225625300223600ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "bytes" "go/format" "go/parser" "go/token" "strings" "testing" ) func testRewrite(t *testing.T, input, expected string, c config) { fset := token.NewFileSet() n, err := parser.ParseFile(fset, "", input, parser.ParseComments) if err != nil { t.Fatalf("failed to parse: %s", err) } p, err := compilePattern(c) if err != nil { t.Fatalf("failed to compile: %s", err) } rewriteNode(p, n) out := &bytes.Buffer{} format.Node(out, fset, n) if out.String() != expected { t.Fatalf("expected %q, but got %q", expected, out) } } func TestRewrite(t *testing.T) { testcases := []struct { name string input string expected string c config }{ { name: "Simple", c: config{acronyms: []string{"Cpu"}}, input: "//hello\npackage main\nfunc GetCpu(){}", expected: "//hello\npackage main\n\nfunc GetCPU() {}", }, { name: "Multiple matches", c: config{acronyms: []string{"Cpu"}}, input: `package main func GetCpuFromCpuList() {}`, expected: `package main func GetCPUFromCPUList() {}`, }, { name: "Submatches", c: config{acronyms: []string{"Runtime(Ns)"}}, input: `package main func KernelTime_100Ns() {} func RuntimeNsAndNsAndSomeSuffix() {}`, expected: `package main func KernelTime_100Ns() {} func RuntimeNSAndNsAndSomeSuffix() {}`, }, { name: "Multiple submatches", c: config{acronyms: []string{"(Id|Vm)$", "[a-z](Ns)$"}}, input: `package main func Vm() {} func Time_100Ns() {} func RuntimeNs() {} `, expected: `package main func VM() {} func Time_100Ns() {} func RuntimeNS() {}`, }, } for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { testRewrite(t, tc.input, strings.ReplaceAll(tc.expected, "\t", "")+"\n", tc.c) }) } } protobuild-0.3.0/config.go000066400000000000000000000063371433225625300155070ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "fmt" "io/ioutil" "log" "github.com/pelletier/go-toml" ) type config struct { Version string Generators []string // Generator is a code generator which is used from protoc. // Deprecated: Use Generators instead. Generator string // Parameters are custom parameters to be passed to the generators. // The parameter key must be the generator name with a table value // of keys and string values to be passed. // Example: // [parameters.go-ttrpc] // customkey = "somevalue" Parameters map[string]map[string]string // Plugins will be deprecated. It has to be per-Generator setting, // but neither protoc-gen-go nor protoc-gen-go-grpc support plugins. // So the refactoring is not worth to do. Plugins []string Includes struct { Before []string Vendored []string Packages []string After []string } Packages map[string]string Overrides []struct { Prefixes []string // Generator is a code generator which is used from protoc. // Deprecated: Use Generators instead. Generator string Generators []string Parameters map[string]map[string]string Plugins *[]string // TODO(stevvooe): We could probably support overriding of includes and // package maps, but they don't seem to be as useful. Likely, // overriding the package map is more useful but includes happen // project-wide. } Descriptors []struct { Prefix string Target string IgnoreFiles []string `toml:"ignore_files"` } } func newDefaultConfig() config { return config{ Includes: struct { Before []string Vendored []string Packages []string After []string }{ Before: []string{"."}, After: []string{"/usr/local/include", "/usr/include"}, }, } } func readConfig(path string) (config, error) { p, err := ioutil.ReadFile(path) if err != nil { log.Fatalln(err) } return readConfigFrom(p) } func readConfigFrom(p []byte) (config, error) { c := newDefaultConfig() if err := toml.Unmarshal(p, &c); err != nil { log.Fatalln(err) } if c.Generator != "" { if len(c.Generators) > 0 { return config{}, fmt.Errorf( `specify either "generators = %v" or "generator = %v", not both`, c.Generators, c.Generator, ) } c.Generators = []string{c.Generator} c.Generator = "" } for i, o := range c.Overrides { if o.Generator != "" { if len(o.Generators) > 0 { return config{}, fmt.Errorf( `specify either "overrides[%d].generators" or "overrides[%d].generator", not both`, i, i, ) } c.Overrides[i].Generators = []string{o.Generator} c.Overrides[i].Generator = "" } } if len(c.Generators) == 0 { c.Generators = []string{"go"} } return c, nil } protobuild-0.3.0/config_test.go000066400000000000000000000025401433225625300165360ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import "testing" func TestReadConfigFrom(t *testing.T) { testcases := []struct { name string toml string }{ { name: "empty", toml: `version="unstable"`, }, { name: "generator", toml: ` version="unstable" generator="go" `, }, { name: "generators", toml: ` version="unstable" generators=["go"] `, }, } for _, tc := range testcases { t.Run(tc.name, func(t *testing.T) { c, err := readConfigFrom([]byte(tc.toml)) if err != nil { t.Fatalf("err must be nil, but got %v", err) } if c.Generator == "go" { t.Fatalf("Generator must be cleared, but got %v", c.Generator) } if len(c.Generators) != 1 || c.Generators[0] != "go" { t.Fatalf("Generators must be [go], but got %v", c.Generators) } }) } } protobuild-0.3.0/descriptors.go000066400000000000000000000053171433225625300166000ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "bytes" "fmt" "io" "io/ioutil" "log" "os" "os/exec" "strings" "github.com/golang/protobuf/proto" "github.com/golang/protobuf/protoc-gen-go/descriptor" ) type descriptorSet struct { merged descriptor.FileDescriptorSet seen map[string]struct{} ignoreFiles map[string]struct{} descProto string includeDir string } func newDescriptorSet(ignoreFiles []string, d string, i string) *descriptorSet { ifm := make(map[string]struct{}, len(ignoreFiles)) for _, ignore := range ignoreFiles { ifm[ignore] = struct{}{} } return &descriptorSet{ seen: make(map[string]struct{}), ignoreFiles: ifm, descProto: d, includeDir: i, } } func (d *descriptorSet) add(descs ...*descriptor.FileDescriptorProto) { for _, file := range descs { name := file.GetName() if _, ok := d.seen[name]; ok { continue } if _, ok := d.ignoreFiles[name]; ok { continue } // TODO(stevvooe): If we want to filter certain fields in the descriptor, // this is the place to do it. May be necessary if certain fields are // noisy, such as option fields. d.merged.File = append(d.merged.File, file) d.seen[name] = struct{}{} } } // stabilize outputs the merged protobuf descriptor set into the provided writer. // // This is equivalent to the following command: // // cat merged.pb | protoc -I /path/to --decode google.protobuf.FileDescriptorSet /path/to/google/protobuf/descriptor.proto func (d *descriptorSet) marshalTo(w io.Writer) error { p, err := proto.Marshal(&d.merged) if err != nil { return err } args := []string{ "protoc", "-I", d.includeDir, "--decode", "google.protobuf.FileDescriptorSet", d.descProto, } cmd := exec.Command(args[0], args[1:]...) cmd.Stdin = bytes.NewReader(p) cmd.Stdout = w cmd.Stderr = os.Stderr if !quiet { fmt.Println(strings.Join(args, " ")) } return cmd.Run() } func readDesc(path string) (*descriptor.FileDescriptorSet, error) { var desc descriptor.FileDescriptorSet p, err := ioutil.ReadFile(path) if err != nil { return nil, err } if err := proto.Unmarshal(p, &desc); err != nil { log.Fatalln(err) } return &desc, nil } protobuild-0.3.0/examples/000077500000000000000000000000001433225625300155205ustar00rootroot00000000000000protobuild-0.3.0/examples/bar/000077500000000000000000000000001433225625300162645ustar00rootroot00000000000000protobuild-0.3.0/examples/bar/bar.pb.go000066400000000000000000000140611433225625300177610ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: github.com/containerd/protobuild/examples/bar/bar.proto package bar import ( context "context" fmt "fmt" internal "github.com/containerd/protobuild/internal" proto "github.com/golang/protobuf/proto" timestamp "github.com/golang/protobuf/ptypes/timestamp" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type DoRequest struct { Timestamp *timestamp.Timestamp `protobuf:"bytes,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *DoRequest) Reset() { *m = DoRequest{} } func (m *DoRequest) String() string { return proto.CompactTextString(m) } func (*DoRequest) ProtoMessage() {} func (*DoRequest) Descriptor() ([]byte, []int) { return fileDescriptor_bdef534bf6116654, []int{0} } func (m *DoRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_DoRequest.Unmarshal(m, b) } func (m *DoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_DoRequest.Marshal(b, m, deterministic) } func (m *DoRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_DoRequest.Merge(m, src) } func (m *DoRequest) XXX_Size() int { return xxx_messageInfo_DoRequest.Size(m) } func (m *DoRequest) XXX_DiscardUnknown() { xxx_messageInfo_DoRequest.DiscardUnknown(m) } var xxx_messageInfo_DoRequest proto.InternalMessageInfo func (m *DoRequest) GetTimestamp() *timestamp.Timestamp { if m != nil { return m.Timestamp } return nil } func init() { proto.RegisterType((*DoRequest)(nil), "protobuild.example.bar.DoRequest") } func init() { proto.RegisterFile("github.com/containerd/protobuild/examples/bar/bar.proto", fileDescriptor_bdef534bf6116654) } var fileDescriptor_bdef534bf6116654 = []byte{ // 205 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x4f, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xce, 0xcf, 0x2b, 0x49, 0xcc, 0xcc, 0x4b, 0x2d, 0x4a, 0xd1, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0xcd, 0xcc, 0x49, 0xd1, 0x4f, 0xad, 0x48, 0xcc, 0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0x4f, 0x4a, 0x2c, 0x02, 0x61, 0x3d, 0xb0, 0x9c, 0x90, 0x18, 0x42, 0x89, 0x1e, 0x54, 0x89, 0x5e, 0x52, 0x62, 0x91, 0x94, 0x74, 0x7a, 0x7e, 0x7e, 0x7a, 0x4e, 0x2a, 0xcc, 0x84, 0x34, 0xfd, 0xd4, 0xdc, 0x82, 0x92, 0x4a, 0x88, 0x26, 0x29, 0x79, 0x74, 0xc9, 0x92, 0xcc, 0xdc, 0xd4, 0xe2, 0x92, 0xc4, 0xdc, 0x02, 0x88, 0x02, 0x25, 0x57, 0x2e, 0x4e, 0x97, 0xfc, 0xa0, 0xd4, 0xc2, 0xd2, 0xd4, 0xe2, 0x12, 0x21, 0x0b, 0x2e, 0x4e, 0xb8, 0xbc, 0x04, 0xb3, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0x94, 0x1e, 0xc4, 0x04, 0x3d, 0x98, 0x09, 0x7a, 0x21, 0x30, 0x15, 0x41, 0x08, 0xc5, 0x46, 0x6e, 0x5c, 0xcc, 0x4e, 0x89, 0x45, 0x42, 0xf6, 0x5c, 0x4c, 0x2e, 0xf9, 0x42, 0x8a, 0x7a, 0xd8, 0x9d, 0xaa, 0x07, 0xb7, 0x49, 0x4a, 0x0c, 0xc3, 0x58, 0x57, 0x90, 0xab, 0x9d, 0x4c, 0xa2, 0x8c, 0x48, 0x0b, 0x1f, 0xeb, 0xa4, 0xc4, 0xa2, 0x24, 0x36, 0xb0, 0xac, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x2a, 0xa0, 0x00, 0x73, 0x5c, 0x01, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // BarClient is the client API for Bar service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type BarClient interface { Do(ctx context.Context, in *DoRequest, opts ...grpc.CallOption) (*internal.Empty, error) } type barClient struct { cc grpc.ClientConnInterface } func NewBarClient(cc grpc.ClientConnInterface) BarClient { return &barClient{cc} } func (c *barClient) Do(ctx context.Context, in *DoRequest, opts ...grpc.CallOption) (*internal.Empty, error) { out := new(internal.Empty) err := c.cc.Invoke(ctx, "/protobuild.example.bar.Bar/Do", in, out, opts...) if err != nil { return nil, err } return out, nil } // BarServer is the server API for Bar service. type BarServer interface { Do(context.Context, *DoRequest) (*internal.Empty, error) } // UnimplementedBarServer can be embedded to have forward compatible implementations. type UnimplementedBarServer struct { } func (*UnimplementedBarServer) Do(ctx context.Context, req *DoRequest) (*internal.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method Do not implemented") } func RegisterBarServer(s *grpc.Server, srv BarServer) { s.RegisterService(&_Bar_serviceDesc, srv) } func _Bar_Do_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DoRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(BarServer).Do(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/protobuild.example.bar.Bar/Do", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(BarServer).Do(ctx, req.(*DoRequest)) } return interceptor(ctx, in, info, handler) } var _Bar_serviceDesc = grpc.ServiceDesc{ ServiceName: "protobuild.example.bar.Bar", HandlerType: (*BarServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Do", Handler: _Bar_Do_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "github.com/containerd/protobuild/examples/bar/bar.proto", } protobuild-0.3.0/examples/bar/bar.proto000066400000000000000000000005261433225625300201200ustar00rootroot00000000000000syntax = "proto3"; package protobuild.example.bar; import "google/protobuf/empty.proto"; import "google/protobuf/timestamp.proto"; option go_package = "github.com/containerd/protobuild/examples/bar/;bar"; service Bar { rpc Do(DoRequest) returns (google.protobuf.Empty); } message DoRequest { google.protobuf.Timestamp timestamp = 3; } protobuild-0.3.0/examples/bar/doc.go000066400000000000000000000013611433225625300173610ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package bar demonstrates a protobuf package. // // We include a doc.go file in here to let protobuild know to place a // Go/Protobuf package. package bar protobuild-0.3.0/examples/foo/000077500000000000000000000000001433225625300163035ustar00rootroot00000000000000protobuild-0.3.0/examples/foo/doc.go000066400000000000000000000013611433225625300174000ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package foo demonstrates a protobuf package. // // We include a doc.go file in here to let protobuild know to place a // Go/Protobuf package. package foo protobuild-0.3.0/examples/foo/foo.pb.go000066400000000000000000000140611433225625300200170ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: github.com/containerd/protobuild/examples/foo/foo.proto package foo import ( context "context" fmt "fmt" internal "github.com/containerd/protobuild/internal" proto "github.com/golang/protobuf/proto" timestamp "github.com/golang/protobuf/ptypes/timestamp" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type DoRequest struct { Timestamp *timestamp.Timestamp `protobuf:"bytes,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *DoRequest) Reset() { *m = DoRequest{} } func (m *DoRequest) String() string { return proto.CompactTextString(m) } func (*DoRequest) ProtoMessage() {} func (*DoRequest) Descriptor() ([]byte, []int) { return fileDescriptor_db2b55b4267b3d4c, []int{0} } func (m *DoRequest) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_DoRequest.Unmarshal(m, b) } func (m *DoRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_DoRequest.Marshal(b, m, deterministic) } func (m *DoRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_DoRequest.Merge(m, src) } func (m *DoRequest) XXX_Size() int { return xxx_messageInfo_DoRequest.Size(m) } func (m *DoRequest) XXX_DiscardUnknown() { xxx_messageInfo_DoRequest.DiscardUnknown(m) } var xxx_messageInfo_DoRequest proto.InternalMessageInfo func (m *DoRequest) GetTimestamp() *timestamp.Timestamp { if m != nil { return m.Timestamp } return nil } func init() { proto.RegisterType((*DoRequest)(nil), "protobuild.example.foo.DoRequest") } func init() { proto.RegisterFile("github.com/containerd/protobuild/examples/foo/foo.proto", fileDescriptor_db2b55b4267b3d4c) } var fileDescriptor_db2b55b4267b3d4c = []byte{ // 205 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x32, 0x4f, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xce, 0xcf, 0x2b, 0x49, 0xcc, 0xcc, 0x4b, 0x2d, 0x4a, 0xd1, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0xcd, 0xcc, 0x49, 0xd1, 0x4f, 0xad, 0x48, 0xcc, 0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0x4f, 0xcb, 0xcf, 0x07, 0x61, 0x3d, 0xb0, 0x9c, 0x90, 0x18, 0x42, 0x89, 0x1e, 0x54, 0x89, 0x5e, 0x5a, 0x7e, 0xbe, 0x94, 0x74, 0x7a, 0x7e, 0x7e, 0x7a, 0x4e, 0x2a, 0xcc, 0x84, 0x34, 0xfd, 0xd4, 0xdc, 0x82, 0x92, 0x4a, 0x88, 0x26, 0x29, 0x79, 0x74, 0xc9, 0x92, 0xcc, 0xdc, 0xd4, 0xe2, 0x92, 0xc4, 0xdc, 0x02, 0x88, 0x02, 0x25, 0x57, 0x2e, 0x4e, 0x97, 0xfc, 0xa0, 0xd4, 0xc2, 0xd2, 0xd4, 0xe2, 0x12, 0x21, 0x0b, 0x2e, 0x4e, 0xb8, 0xbc, 0x04, 0xb3, 0x02, 0xa3, 0x06, 0xb7, 0x91, 0x94, 0x1e, 0xc4, 0x04, 0x3d, 0x98, 0x09, 0x7a, 0x21, 0x30, 0x15, 0x41, 0x08, 0xc5, 0x46, 0x6e, 0x5c, 0xcc, 0x6e, 0xf9, 0xf9, 0x42, 0xf6, 0x5c, 0x4c, 0x2e, 0xf9, 0x42, 0x8a, 0x7a, 0xd8, 0x9d, 0xaa, 0x07, 0xb7, 0x49, 0x4a, 0x0c, 0xc3, 0x58, 0x57, 0x90, 0xab, 0x9d, 0x4c, 0xa2, 0x8c, 0x48, 0x0b, 0x1f, 0xeb, 0xb4, 0xfc, 0xfc, 0x24, 0x36, 0xb0, 0xac, 0x31, 0x20, 0x00, 0x00, 0xff, 0xff, 0x79, 0xd3, 0x0b, 0x91, 0x5c, 0x01, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. var _ context.Context var _ grpc.ClientConnInterface // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. const _ = grpc.SupportPackageIsVersion6 // FooClient is the client API for Foo service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. type FooClient interface { Do(ctx context.Context, in *DoRequest, opts ...grpc.CallOption) (*internal.Empty, error) } type fooClient struct { cc grpc.ClientConnInterface } func NewFooClient(cc grpc.ClientConnInterface) FooClient { return &fooClient{cc} } func (c *fooClient) Do(ctx context.Context, in *DoRequest, opts ...grpc.CallOption) (*internal.Empty, error) { out := new(internal.Empty) err := c.cc.Invoke(ctx, "/protobuild.example.foo.Foo/Do", in, out, opts...) if err != nil { return nil, err } return out, nil } // FooServer is the server API for Foo service. type FooServer interface { Do(context.Context, *DoRequest) (*internal.Empty, error) } // UnimplementedFooServer can be embedded to have forward compatible implementations. type UnimplementedFooServer struct { } func (*UnimplementedFooServer) Do(ctx context.Context, req *DoRequest) (*internal.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method Do not implemented") } func RegisterFooServer(s *grpc.Server, srv FooServer) { s.RegisterService(&_Foo_serviceDesc, srv) } func _Foo_Do_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DoRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(FooServer).Do(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/protobuild.example.foo.Foo/Do", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(FooServer).Do(ctx, req.(*DoRequest)) } return interceptor(ctx, in, info, handler) } var _Foo_serviceDesc = grpc.ServiceDesc{ ServiceName: "protobuild.example.foo.Foo", HandlerType: (*FooServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Do", Handler: _Foo_Do_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "github.com/containerd/protobuild/examples/foo/foo.proto", } protobuild-0.3.0/examples/foo/foo.proto000066400000000000000000000005261433225625300201560ustar00rootroot00000000000000syntax = "proto3"; package protobuild.example.foo; import "google/protobuf/empty.proto"; import "google/protobuf/timestamp.proto"; option go_package = "github.com/containerd/protobuild/examples/foo/;foo"; service Foo { rpc Do(DoRequest) returns (google.protobuf.Empty); } message DoRequest { google.protobuf.Timestamp timestamp = 3; } protobuild-0.3.0/examples/next.pb.txt000077500000000000000000000057431433225625300176530ustar00rootroot00000000000000file { name: "google/protobuf/empty.proto" package: "google.protobuf" message_type { name: "Empty" } options { java_package: "com.google.protobuf" java_outer_classname: "EmptyProto" java_multiple_files: true go_package: "github.com/golang/protobuf/ptypes/empty" cc_enable_arenas: true objc_class_prefix: "GPB" csharp_namespace: "Google.Protobuf.WellKnownTypes" } syntax: "proto3" } file { name: "google/protobuf/timestamp.proto" package: "google.protobuf" message_type { name: "Timestamp" field { name: "seconds" number: 1 label: LABEL_OPTIONAL type: TYPE_INT64 json_name: "seconds" } field { name: "nanos" number: 2 label: LABEL_OPTIONAL type: TYPE_INT32 json_name: "nanos" } } options { java_package: "com.google.protobuf" java_outer_classname: "TimestampProto" java_multiple_files: true go_package: "github.com/golang/protobuf/ptypes/timestamp" cc_enable_arenas: true objc_class_prefix: "GPB" csharp_namespace: "Google.Protobuf.WellKnownTypes" } syntax: "proto3" } file { name: "github.com/containerd/protobuild/examples/bar/bar.proto" package: "protobuild.example.bar" dependency: "google/protobuf/empty.proto" dependency: "google/protobuf/timestamp.proto" message_type { name: "DoRequest" field { name: "timestamp" number: 3 label: LABEL_OPTIONAL type: TYPE_MESSAGE type_name: ".google.protobuf.Timestamp" json_name: "timestamp" } } service { name: "Bar" method { name: "Do" input_type: ".protobuild.example.bar.DoRequest" output_type: ".google.protobuf.Empty" } } options { go_package: "github.com/containerd/protobuild/examples/bar/;bar" } syntax: "proto3" } file { name: "github.com/containerd/protobuild/examples/foo/foo.proto" package: "protobuild.example.foo" dependency: "google/protobuf/empty.proto" dependency: "google/protobuf/timestamp.proto" message_type { name: "DoRequest" field { name: "timestamp" number: 3 label: LABEL_OPTIONAL type: TYPE_MESSAGE type_name: ".google.protobuf.Timestamp" json_name: "timestamp" } } service { name: "Foo" method { name: "Do" input_type: ".protobuild.example.foo.DoRequest" output_type: ".google.protobuf.Empty" } } options { go_package: "github.com/containerd/protobuild/examples/foo/;foo" } syntax: "proto3" } file { name: "github.com/containerd/protobuild/examples/nogrpc/nogrpc.proto" package: "protobuild.example.nogrpc" dependency: "google/protobuf/timestamp.proto" message_type { name: "Thing" field { name: "timestamp" number: 3 label: LABEL_OPTIONAL type: TYPE_MESSAGE type_name: ".google.protobuf.Timestamp" json_name: "timestamp" } } options { go_package: "github.com/containerd/protobuild/examples/nogrpc/;nogrpc" } syntax: "proto3" } protobuild-0.3.0/examples/nogrpc/000077500000000000000000000000001433225625300170105ustar00rootroot00000000000000protobuild-0.3.0/examples/nogrpc/doc.go000066400000000000000000000012741433225625300201100ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package nogrpc will be generated without grpc, demonstrating the override // feature. package nogrpc protobuild-0.3.0/examples/nogrpc/nogrpc.pb.go000066400000000000000000000062201433225625300212270ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // source: github.com/containerd/protobuild/examples/nogrpc/nogrpc.proto package nogrpc import ( fmt "fmt" proto "github.com/golang/protobuf/proto" timestamp "github.com/golang/protobuf/ptypes/timestamp" math "math" ) // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package type Thing struct { Timestamp *timestamp.Timestamp `protobuf:"bytes,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Thing) Reset() { *m = Thing{} } func (m *Thing) String() string { return proto.CompactTextString(m) } func (*Thing) ProtoMessage() {} func (*Thing) Descriptor() ([]byte, []int) { return fileDescriptor_cb990b4b37c93d36, []int{0} } func (m *Thing) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Thing.Unmarshal(m, b) } func (m *Thing) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Thing.Marshal(b, m, deterministic) } func (m *Thing) XXX_Merge(src proto.Message) { xxx_messageInfo_Thing.Merge(m, src) } func (m *Thing) XXX_Size() int { return xxx_messageInfo_Thing.Size(m) } func (m *Thing) XXX_DiscardUnknown() { xxx_messageInfo_Thing.DiscardUnknown(m) } var xxx_messageInfo_Thing proto.InternalMessageInfo func (m *Thing) GetTimestamp() *timestamp.Timestamp { if m != nil { return m.Timestamp } return nil } func init() { proto.RegisterType((*Thing)(nil), "protobuild.example.nogrpc.Thing") } func init() { proto.RegisterFile("github.com/containerd/protobuild/examples/nogrpc/nogrpc.proto", fileDescriptor_cb990b4b37c93d36) } var fileDescriptor_cb990b4b37c93d36 = []byte{ // 162 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xb2, 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xce, 0xcf, 0x2b, 0x49, 0xcc, 0xcc, 0x4b, 0x2d, 0x4a, 0xd1, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0xcd, 0xcc, 0x49, 0xd1, 0x4f, 0xad, 0x48, 0xcc, 0x2d, 0xc8, 0x49, 0x2d, 0xd6, 0xcf, 0xcb, 0x4f, 0x2f, 0x2a, 0x48, 0x86, 0x52, 0x7a, 0x60, 0x15, 0x42, 0x92, 0x08, 0x85, 0x7a, 0x50, 0x85, 0x7a, 0x10, 0x05, 0x52, 0xf2, 0xe9, 0xf9, 0xf9, 0xe9, 0x39, 0xa9, 0x30, 0xa3, 0xd2, 0xf4, 0x4b, 0x32, 0x73, 0x53, 0x8b, 0x4b, 0x12, 0x73, 0x0b, 0x20, 0x7a, 0x95, 0x1c, 0xb9, 0x58, 0x43, 0x32, 0x32, 0xf3, 0xd2, 0x85, 0x2c, 0xb8, 0x38, 0xe1, 0x72, 0x12, 0xcc, 0x0a, 0x8c, 0x1a, 0xdc, 0x46, 0x52, 0x7a, 0x10, 0xdd, 0x7a, 0x30, 0xdd, 0x7a, 0x21, 0x30, 0x15, 0x41, 0x08, 0xc5, 0x4e, 0x56, 0x51, 0x16, 0x24, 0xbb, 0xdf, 0x1a, 0x42, 0x27, 0xb1, 0x81, 0xd5, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0xfa, 0x5e, 0xce, 0x08, 0x02, 0x01, 0x00, 0x00, } protobuild-0.3.0/examples/nogrpc/nogrpc.proto000066400000000000000000000005341433225625300213670ustar00rootroot00000000000000syntax = "proto3"; // This package will be generated without the grpc plugin enabled, // demonstrating the overrides feature. package protobuild.example.nogrpc; import "google/protobuf/timestamp.proto"; option go_package = "github.com/containerd/protobuild/examples/nogrpc/;nogrpc"; message Thing { google.protobuf.Timestamp timestamp = 3; } protobuild-0.3.0/examples/v2/000077500000000000000000000000001433225625300160475ustar00rootroot00000000000000protobuild-0.3.0/examples/v2/doc.go000066400000000000000000000013601433225625300171430ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // Package foo demonstrates a protobuf package. // // We include a doc.go file in here to let protobuild know to place a // Go/Protobuf package. package v2 protobuild-0.3.0/examples/v2/foo.pb.go000066400000000000000000000163321433225625300175660ustar00rootroot00000000000000// Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v3.18.1 // source: github.com/containerd/protobuild/examples/v2/foo.proto package v2 import ( internal "github.com/containerd/protobuild/internal" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" timestamppb "google.golang.org/protobuf/types/known/timestamppb" reflect "reflect" sync "sync" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) type DoRequest struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields Timestamp *timestamppb.Timestamp `protobuf:"bytes,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` } func (x *DoRequest) Reset() { *x = DoRequest{} if protoimpl.UnsafeEnabled { mi := &file_github_com_containerd_protobuild_examples_v2_foo_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *DoRequest) String() string { return protoimpl.X.MessageStringOf(x) } func (*DoRequest) ProtoMessage() {} func (x *DoRequest) ProtoReflect() protoreflect.Message { mi := &file_github_com_containerd_protobuild_examples_v2_foo_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use DoRequest.ProtoReflect.Descriptor instead. func (*DoRequest) Descriptor() ([]byte, []int) { return file_github_com_containerd_protobuild_examples_v2_foo_proto_rawDescGZIP(), []int{0} } func (x *DoRequest) GetTimestamp() *timestamppb.Timestamp { if x != nil { return x.Timestamp } return nil } var File_github_com_containerd_protobuild_examples_v2_foo_proto protoreflect.FileDescriptor var file_github_com_containerd_protobuild_examples_v2_foo_proto_rawDesc = []byte{ 0x0a, 0x36, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x2f, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x73, 0x2f, 0x76, 0x32, 0x2f, 0x66, 0x6f, 0x6f, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x15, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x76, 0x32, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x45, 0x0a, 0x09, 0x44, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x38, 0x0a, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x32, 0x45, 0x0a, 0x03, 0x46, 0x6f, 0x6f, 0x12, 0x3e, 0x0a, 0x02, 0x44, 0x6f, 0x12, 0x20, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x76, 0x32, 0x2e, 0x44, 0x6f, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x16, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x42, 0x32, 0x5a, 0x30, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65, 0x72, 0x64, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x69, 0x6c, 0x64, 0x2f, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x73, 0x2f, 0x76, 0x32, 0x2f, 0x3b, 0x76, 0x32, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_github_com_containerd_protobuild_examples_v2_foo_proto_rawDescOnce sync.Once file_github_com_containerd_protobuild_examples_v2_foo_proto_rawDescData = file_github_com_containerd_protobuild_examples_v2_foo_proto_rawDesc ) func file_github_com_containerd_protobuild_examples_v2_foo_proto_rawDescGZIP() []byte { file_github_com_containerd_protobuild_examples_v2_foo_proto_rawDescOnce.Do(func() { file_github_com_containerd_protobuild_examples_v2_foo_proto_rawDescData = protoimpl.X.CompressGZIP(file_github_com_containerd_protobuild_examples_v2_foo_proto_rawDescData) }) return file_github_com_containerd_protobuild_examples_v2_foo_proto_rawDescData } var file_github_com_containerd_protobuild_examples_v2_foo_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_github_com_containerd_protobuild_examples_v2_foo_proto_goTypes = []interface{}{ (*DoRequest)(nil), // 0: protobuild.example.v2.DoRequest (*timestamppb.Timestamp)(nil), // 1: google.protobuf.Timestamp (*internal.Empty)(nil), // 2: google.protobuf.Empty } var file_github_com_containerd_protobuild_examples_v2_foo_proto_depIdxs = []int32{ 1, // 0: protobuild.example.v2.DoRequest.timestamp:type_name -> google.protobuf.Timestamp 0, // 1: protobuild.example.v2.Foo.Do:input_type -> protobuild.example.v2.DoRequest 2, // 2: protobuild.example.v2.Foo.Do:output_type -> google.protobuf.Empty 2, // [2:3] is the sub-list for method output_type 1, // [1:2] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_github_com_containerd_protobuild_examples_v2_foo_proto_init() } func file_github_com_containerd_protobuild_examples_v2_foo_proto_init() { if File_github_com_containerd_protobuild_examples_v2_foo_proto != nil { return } if !protoimpl.UnsafeEnabled { file_github_com_containerd_protobuild_examples_v2_foo_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*DoRequest); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_github_com_containerd_protobuild_examples_v2_foo_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 1, }, GoTypes: file_github_com_containerd_protobuild_examples_v2_foo_proto_goTypes, DependencyIndexes: file_github_com_containerd_protobuild_examples_v2_foo_proto_depIdxs, MessageInfos: file_github_com_containerd_protobuild_examples_v2_foo_proto_msgTypes, }.Build() File_github_com_containerd_protobuild_examples_v2_foo_proto = out.File file_github_com_containerd_protobuild_examples_v2_foo_proto_rawDesc = nil file_github_com_containerd_protobuild_examples_v2_foo_proto_goTypes = nil file_github_com_containerd_protobuild_examples_v2_foo_proto_depIdxs = nil } protobuild-0.3.0/examples/v2/foo.proto000066400000000000000000000005231433225625300177170ustar00rootroot00000000000000syntax = "proto3"; package protobuild.example.v2; import "google/protobuf/empty.proto"; import "google/protobuf/timestamp.proto"; option go_package = "github.com/containerd/protobuild/examples/v2/;v2"; service Foo { rpc Do(DoRequest) returns (google.protobuf.Empty); } message DoRequest { google.protobuf.Timestamp timestamp = 3; } protobuild-0.3.0/examples/v2/foo_grpc.pb.go000066400000000000000000000063351433225625300206030ustar00rootroot00000000000000// Code generated by protoc-gen-go-grpc. DO NOT EDIT. package v2 import ( context "context" grpc "google.golang.org/grpc" codes "google.golang.org/grpc/codes" status "google.golang.org/grpc/status" emptypb "google.golang.org/protobuf/types/known/emptypb" ) // This is a compile-time assertion to ensure that this generated file // is compatible with the grpc package it is being compiled against. // Requires gRPC-Go v1.32.0 or later. const _ = grpc.SupportPackageIsVersion7 // FooClient is the client API for Foo service. // // For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. type FooClient interface { Do(ctx context.Context, in *DoRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) } type fooClient struct { cc grpc.ClientConnInterface } func NewFooClient(cc grpc.ClientConnInterface) FooClient { return &fooClient{cc} } func (c *fooClient) Do(ctx context.Context, in *DoRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) { out := new(emptypb.Empty) err := c.cc.Invoke(ctx, "/protobuild.example.v2.Foo/Do", in, out, opts...) if err != nil { return nil, err } return out, nil } // FooServer is the server API for Foo service. // All implementations must embed UnimplementedFooServer // for forward compatibility type FooServer interface { Do(context.Context, *DoRequest) (*emptypb.Empty, error) mustEmbedUnimplementedFooServer() } // UnimplementedFooServer must be embedded to have forward compatible implementations. type UnimplementedFooServer struct { } func (UnimplementedFooServer) Do(context.Context, *DoRequest) (*emptypb.Empty, error) { return nil, status.Errorf(codes.Unimplemented, "method Do not implemented") } func (UnimplementedFooServer) mustEmbedUnimplementedFooServer() {} // UnsafeFooServer may be embedded to opt out of forward compatibility for this service. // Use of this interface is not recommended, as added methods to FooServer will // result in compilation errors. type UnsafeFooServer interface { mustEmbedUnimplementedFooServer() } func RegisterFooServer(s grpc.ServiceRegistrar, srv FooServer) { s.RegisterService(&Foo_ServiceDesc, srv) } func _Foo_Do_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(DoRequest) if err := dec(in); err != nil { return nil, err } if interceptor == nil { return srv.(FooServer).Do(ctx, in) } info := &grpc.UnaryServerInfo{ Server: srv, FullMethod: "/protobuild.example.v2.Foo/Do", } handler := func(ctx context.Context, req interface{}) (interface{}, error) { return srv.(FooServer).Do(ctx, req.(*DoRequest)) } return interceptor(ctx, in, info, handler) } // Foo_ServiceDesc is the grpc.ServiceDesc for Foo service. // It's only intended for direct use with grpc.RegisterService, // and not to be introspected or modified (even as a copy) var Foo_ServiceDesc = grpc.ServiceDesc{ ServiceName: "protobuild.example.v2.Foo", HandlerType: (*FooServer)(nil), Methods: []grpc.MethodDesc{ { MethodName: "Do", Handler: _Foo_Do_Handler, }, }, Streams: []grpc.StreamDesc{}, Metadata: "github.com/containerd/protobuild/examples/v2/foo.proto", } protobuild-0.3.0/examples/v2/next.pb.txt000077500000000000000000000034671433225625300202030ustar00rootroot00000000000000file { name: "google/protobuf/empty.proto" package: "google.protobuf" message_type { name: "Empty" } options { java_package: "com.google.protobuf" java_outer_classname: "EmptyProto" java_multiple_files: true go_package: "google.golang.org/protobuf/types/known/emptypb" cc_enable_arenas: true objc_class_prefix: "GPB" csharp_namespace: "Google.Protobuf.WellKnownTypes" } syntax: "proto3" } file { name: "google/protobuf/timestamp.proto" package: "google.protobuf" message_type { name: "Timestamp" field { name: "seconds" number: 1 label: LABEL_OPTIONAL type: TYPE_INT64 json_name: "seconds" } field { name: "nanos" number: 2 label: LABEL_OPTIONAL type: TYPE_INT32 json_name: "nanos" } } options { java_package: "com.google.protobuf" java_outer_classname: "TimestampProto" java_multiple_files: true go_package: "google.golang.org/protobuf/types/known/timestamppb" cc_enable_arenas: true objc_class_prefix: "GPB" csharp_namespace: "Google.Protobuf.WellKnownTypes" } syntax: "proto3" } file { name: "github.com/containerd/protobuild/examples/v2/foo.proto" package: "protobuild.example.v2" dependency: "google/protobuf/empty.proto" dependency: "google/protobuf/timestamp.proto" message_type { name: "DoRequest" field { name: "timestamp" number: 3 label: LABEL_OPTIONAL type: TYPE_MESSAGE type_name: ".google.protobuf.Timestamp" json_name: "timestamp" } } service { name: "Foo" method { name: "Do" input_type: ".protobuild.example.v2.DoRequest" output_type: ".google.protobuf.Empty" } } options { go_package: "github.com/containerd/protobuild/examples/v2/;v2" } syntax: "proto3" } protobuild-0.3.0/go.mod000066400000000000000000000003451433225625300150120ustar00rootroot00000000000000module github.com/containerd/protobuild go 1.13 require ( github.com/golang/protobuf v1.5.0 github.com/pelletier/go-toml v1.8.1 golang.org/x/tools v0.1.9 google.golang.org/grpc v1.28.1 google.golang.org/protobuf v1.27.1 ) protobuild-0.3.0/go.sum000066400000000000000000000203051433225625300150350ustar00rootroot00000000000000cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= github.com/golang/protobuf v1.5.0 h1:LUVKkCeviFUMKqHa4tXIIij/lbhnMbP7Fn5wKdKkRh4= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/pelletier/go-toml v1.8.1 h1:1Nf83orprkJyknT6h7zbuEGUEjcyVlCxSUGTENmNCRM= github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/mod v0.5.1 h1:OJxoQ/rynoF0dcCdI7cLPktw/hR2cueqYfjm43oqK38= golang.org/x/mod v0.5.1/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f h1:OfiFi4JbukWwe3lzw+xunroH1mnC1e2Gy5cxNJApiSY= golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20211019181941-9d821ace8654 h1:id054HUawV2/6IGm2IV8KZQjqtwAOo2CYlOToYqa0d0= golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.9 h1:j9KsMiaP1c3B0OTQGth0/k+miLGTgLsAFUCrF2vLcF8= golang.org/x/tools v0.1.9/go.mod h1:nABZi5QlRsZVlzPpHl034qft6wpY4eDcsTt5AaioBiU= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55 h1:gSJIx1SDwno+2ElGhA4+qG2zF97qiUzTM+rQ0klBOcE= google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.28.1 h1:C1QC6KzgSiLyBabDi87BbjaGreoRgGUF5nOyvfrAZ1k= google.golang.org/grpc v1.28.1/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= protobuild-0.3.0/internal/000077500000000000000000000000001433225625300155165ustar00rootroot00000000000000protobuild-0.3.0/internal/emptypb.go000066400000000000000000000013401433225625300175230ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // This package is written for demonstrating Protobuild's "packages" override. // Not for production. package internal type Empty struct{} protobuild-0.3.0/main.go000066400000000000000000000300631433225625300151570ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "bytes" "errors" "flag" "fmt" "io/ioutil" "log" "os" "os/exec" "path" "path/filepath" "strconv" "strings" "syscall" "github.com/golang/protobuf/protoc-gen-go/descriptor" ) // defines several variables for parameterizing the protoc command. We can pull // this out into a toml files in cases where we to vary this per package. var ( configPath string dryRun bool quiet bool ) func init() { flag.StringVar(&configPath, "f", "Protobuild.toml", "override default config location") flag.BoolVar(&dryRun, "dryrun", false, "prints commands without running") flag.BoolVar(&quiet, "quiet", false, "suppress verbose output") } func parseVersion(s string) (int, error) { if s == "unstable" { return 0, nil } v, err := strconv.Atoi(s) if err != nil { return 0, fmt.Errorf("unknown file version %q: %w", s, err) } if v < 1 || v > 2 { return 0, fmt.Errorf(`unknown file version %q; valid versions are "unstable", "1" and "2"`, s) } return v, nil } func importPath(base, target string) (string, error) { rel, err := filepath.Rel(base, target) if err != nil { return "", err } return filepath.ToSlash(rel), nil } func main() { flag.Parse() c, err := readConfig(configPath) if err != nil { log.Fatalln(err) } version, err := parseVersion(c.Version) if err != nil { log.Fatalln(err) } pkgInfos, err := goPkgInfo(flag.Args()...) if err != nil { log.Fatalln(err) } gopath, err := gopathSrc() if err != nil { log.Fatalln(err) } gopathCurrent, err := gopathCurrent() if err != nil { log.Fatalln(err) } // For some reason, the golang protobuf generator makes the god awful // decision to output the files relative to the gopath root. It doesn't do // this only in the case where you give it ".". outputDir := filepath.Join(gopathCurrent, "src") // Index overrides by target import path overrides := map[string]struct { Prefixes []string Generator string Generators []string Parameters map[string]map[string]string Plugins *[]string }{} for _, override := range c.Overrides { for _, prefix := range override.Prefixes { overrides[prefix] = override } } // Create include paths used to find the descriptor proto. As a special case // we search the vendor directory relative to the current working directory. // This handles the case where a user has vendored their descriptor proto. var descriptorIncludes []string descriptorIncludes = append(descriptorIncludes, c.Includes.Before...) for _, vendorPath := range c.Includes.Vendored { descriptorIncludes = append(descriptorIncludes, filepath.Join("vendor", vendorPath)) } descriptorIncludes = append(descriptorIncludes, c.Includes.Packages...) descriptorIncludes = append(descriptorIncludes, c.Includes.After...) descProto, includeDir, err := descriptorProto(descriptorIncludes) if err != nil { log.Fatalln(err) } // Aggregate descriptors for each descriptor prefix. descriptorSets := map[string]*descriptorSet{} for _, stable := range c.Descriptors { descriptorSets[stable.Prefix] = newDescriptorSet(stable.IgnoreFiles, descProto, includeDir) } shouldGenerateDescriptors := func(p string) bool { for prefix := range descriptorSets { if strings.HasPrefix(p, prefix) { return true } } return false } var descriptors []*descriptor.FileDescriptorSet for _, pkg := range pkgInfos { var includes []string includes = append(includes, c.Includes.Before...) vendor, err := closestVendorDir(pkg.Dir) if err != nil { if err != errVendorNotFound { log.Fatalln(err) } } if vendor != "" { // TODO(stevvooe): The use of the closest vendor directory is a // little naive. We should probably resolve all possible vendor // directories or at least match Go's behavior. // we also special case the inclusion of gogoproto in the vendor dir. // We could parameterize this better if we find it to be a common case. var vendoredIncludesResolved []string for _, vendoredInclude := range c.Includes.Vendored { vendoredIncludesResolved = append(vendoredIncludesResolved, filepath.Join(vendor, vendoredInclude)) } // Also do this for pkg includes. for _, pkgInclude := range c.Includes.Packages { vendoredIncludesResolved = append(vendoredIncludesResolved, filepath.Join(vendor, pkgInclude)) } includes = append(includes, vendoredIncludesResolved...) includes = append(includes, vendor) } else if len(c.Includes.Vendored) > 0 { log.Println("ignoring vendored includes: vendor directory not found") } // handle packages that we want to have as an include root from any of // the gopaths. for _, pkg := range c.Includes.Packages { includes = append(includes, gopathJoin(gopath, pkg)) } includes = append(includes, gopath) includes = append(includes, c.Includes.After...) protoc := protocCmd{ Generators: generators(c.Generators, outputDir), Files: pkg.ProtoFiles, OutputDir: outputDir, Includes: includes, Version: version, Names: c.Generators, Plugins: c.Plugins, ImportPath: pkg.GoImportPath, PackageMap: c.Packages, } importDirPath, err := importPath(outputDir, pkg.Dir) if err != nil { log.Fatalln(err) } parameters := map[string]map[string]string{} for proto, pkg := range c.Packages { parameters["go"] = mergeMap(parameters["go"], map[string]string{ fmt.Sprintf("M%s", proto): pkg, }) } for k, v := range c.Parameters { parameters[k] = mergeMap(parameters[k], v) } if override, ok := overrides[importDirPath]; ok { // selectively apply the overrides to the protoc structure. if len(override.Generators) > 0 { protoc.Names = override.Generators protoc.Generators = generators(override.Generators, outputDir) } if override.Plugins != nil { protoc.Plugins = *override.Plugins } for k, v := range override.Parameters { parameters[k] = mergeMap(parameters[k], v) } } // Set parameters per generator for i := range protoc.Generators { protoc.Generators[i].Parameters = parameters[protoc.Generators[i].Name] } var ( genDescriptors = shouldGenerateDescriptors(importDirPath) dfp *os.File // tempfile for descriptors ) if genDescriptors { dfp, err = ioutil.TempFile("", "descriptors.pb-") if err != nil { log.Fatalln(err) } protoc.Descriptors = dfp.Name() } arg, err := protoc.mkcmd() if err != nil { log.Fatalln(err) } if !quiet { fmt.Println(arg) } if dryRun { continue } if err := protoc.run(); err != nil { if quiet { log.Println(arg) } if err, ok := err.(*exec.ExitError); ok { if status, ok := err.Sys().(syscall.WaitStatus); ok { os.Exit(status.ExitStatus()) // proxy protoc exit status } } log.Fatalln(err) } if genDescriptors { desc, err := readDesc(protoc.Descriptors) if err != nil { log.Fatalln(err) } for path, set := range descriptorSets { if strings.HasPrefix(importDirPath, path) { set.add(desc.File...) } } descriptors = append(descriptors, desc) // clean up descriptors file if err := os.Remove(dfp.Name()); err != nil { log.Fatalln(err) } if err := dfp.Close(); err != nil { log.Fatalln(err) } } } for _, descriptorConfig := range c.Descriptors { fp, err := os.OpenFile(descriptorConfig.Target, os.O_TRUNC|os.O_WRONLY|os.O_CREATE, 0777) if err != nil { log.Fatalln(err) } defer fp.Sync() defer fp.Close() set := descriptorSets[descriptorConfig.Prefix] if len(set.merged.File) == 0 { continue // just skip if there is nothing. } if err := set.marshalTo(fp); err != nil { log.Fatalln(err) } } } func generators(names []string, outDir string) []generator { g := make([]generator, len(names)) for i, name := range names { g[i].Name = name g[i].OutputDir = outDir } return g } type protoGoPkgInfo struct { Dir string GoImportPath string ProtoFiles []string } // goPkgInfo hunts down packages with proto files. func goPkgInfo(golistpath ...string) ([]protoGoPkgInfo, error) { args := []string{ "list", "-e", "-f", "{{.ImportPath}} {{.Dir}}"} args = append(args, golistpath...) cmd := exec.Command("go", args...) p, err := cmd.Output() if err != nil { return nil, err } var pkgInfos []protoGoPkgInfo lines := bytes.Split(p, []byte("\n")) for _, line := range lines { if len(line) == 0 { continue } parts := bytes.Fields(line) if len(parts) != 2 { return nil, fmt.Errorf("bad output from command: %s", p) } pkgInfo := protoGoPkgInfo{ Dir: string(parts[1]), GoImportPath: string(parts[0]), } protoFiles, err := filepath.Glob(filepath.Join(pkgInfo.Dir, "*.proto")) if err != nil { return nil, err } if len(protoFiles) == 0 { continue // not a proto directory, skip } pkgInfo.ProtoFiles = protoFiles pkgInfos = append(pkgInfos, pkgInfo) } return pkgInfos, nil } func gopaths() ([]string, error) { cmd := exec.Command("go", "env", "GOPATH") out, err := cmd.Output() if err != nil { return nil, err } gp := strings.TrimSpace(string(out)) if gp == "" { return nil, errors.New("go env GOPATH is empty") } return strings.Split(gp, string(filepath.ListSeparator)), nil } // gopathSrc modifies GOPATH elements from env to include the src directory. func gopathSrc() (string, error) { gps, err := gopaths() if err != nil { return "", err } if len(gps) == 0 { return "", fmt.Errorf("must be run from a gopath") } var elements []string for _, element := range gps { elements = append(elements, filepath.Join(element, "src")) } return strings.Join(elements, string(filepath.ListSeparator)), nil } // gopathCurrent provides the top-level gopath for the current generation. func gopathCurrent() (string, error) { gps, err := gopaths() if err != nil { return "", err } if len(gps) == 0 { return "", fmt.Errorf("must be run from a gopath") } return gps[0], nil } // gopathJoin combines the element with each path item and then recombines the set. func gopathJoin(gopath, element string) string { gps := strings.Split(gopath, string(filepath.ListSeparator)) var elements []string for _, p := range gps { elements = append(elements, filepath.Join(p, element)) } return strings.Join(elements, string(filepath.ListSeparator)) } // descriptorProto returns the full path to google/protobuf/descriptor.proto // which might be different depending on whether it was installed. The argument // is the list of paths to check. func descriptorProto(paths []string) (string, string, error) { const descProto = "google/protobuf/descriptor.proto" for _, dir := range paths { file := path.Join(dir, descProto) if _, err := os.Stat(file); err == nil { return file, dir, err } } return "", "", fmt.Errorf("File %q not found (looked in: %v)", descProto, paths) } var errVendorNotFound = fmt.Errorf("no vendor dir found") // closestVendorDir walks up from dir until it finds the vendor directory. func closestVendorDir(dir string) (string, error) { dir = filepath.Clean(dir) for dir != filepath.Join(filepath.VolumeName(dir), string(filepath.Separator)) { vendor := filepath.Join(dir, "vendor") fi, err := os.Stat(vendor) if err != nil { if os.IsNotExist(err) { // up we go! dir = filepath.Dir(dir) continue } return "", err } if !fi.IsDir() { // up we go! dir = filepath.Dir(dir) continue } return vendor, nil } return "", errVendorNotFound } func mergeMap(m1, m2 map[string]string) map[string]string { if m1 == nil { m1 = map[string]string{} } for k, v := range m2 { m1[k] = v } return m1 } protobuild-0.3.0/main_test.go000066400000000000000000000016431433225625300162200ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import "testing" func TestImportPath(t *testing.T) { path, err := importPath("/home/alice/go/src", "/home/alice/go/src/github.com/containerd/foobar") if err != nil { t.Fatalf("got %s", err) } expected := "github.com/containerd/foobar" if path != expected { t.Fatalf("got %s, expected %s", path, expected) } } protobuild-0.3.0/protoc.go000066400000000000000000000052761433225625300155510ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import ( "bytes" "fmt" "os" "os/exec" "path/filepath" "strings" "text/template" ) var ( tmpl = template.Must(template.New("protoc").Parse(`protoc -I {{- range $index, $include := .Includes -}} {{if $index}}` + string(filepath.ListSeparator) + `{{end -}} {{.}} {{- end -}} {{- if .Descriptors}} --include_imports --descriptor_set_out={{.Descriptors}}{{- end -}} {{ if lt .Version 2 }} {{- range $index, $name := .Names }} --{{- $name -}}_out={{- $.GoOutV1 }}{{- end -}} {{- else -}} {{- range $gen := .Generators }} --{{- $gen.Name -}}_out={{- $gen.OutputDir }} {{- range $k, $v := $gen.Parameters }} --{{- $gen.Name -}}_opt={{- $k -}}={{- $v -}}{{- end -}} {{- end -}} {{- end -}} {{- range .Files}} {{.}}{{end -}} `)) ) type generator struct { Name string OutputDir string Parameters map[string]string } // protocParams defines inputs to a protoc command string. type protocCmd struct { Generators []generator Includes []string Descriptors string Files []string // Version is Protobuild's version. Version int // V1 fields Names []string OutputDir string PackageMap map[string]string Plugins []string ImportPath string } func (p *protocCmd) mkcmd() (string, error) { var buf bytes.Buffer if err := tmpl.Execute(&buf, p); err != nil { return "", err } return buf.String(), nil } // GoOutV1 returns the parameter for --go_out= for protoc-gen-go < 1.4.0. // Note that plugins and import_path are no longer supported by // newer protoc-gen-go versions. func (p *protocCmd) GoOutV1() string { var result string if len(p.Plugins) > 0 { result += "plugins=" + strings.Join(p.Plugins, "+") + "," } result += "import_path=" + p.ImportPath for proto, pkg := range p.PackageMap { result += fmt.Sprintf(",M%s=%s", proto, pkg) } result += ":" + p.OutputDir return result } func (p *protocCmd) run() error { arg, err := p.mkcmd() if err != nil { return err } // pass to sh -c so we don't need to re-split here. args := []string{shArg, arg} cmd := exec.Command(shCmd, args...) cmd.Stderr = os.Stderr cmd.Stdout = os.Stdout return cmd.Run() } protobuild-0.3.0/protoc_test.go000066400000000000000000000051601433225625300166000ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main import "testing" func TestMkcmd(t *testing.T) { testcases := []struct { name string cmd protocCmd expectedV1 string expectedV2 string }{ { name: "basic", cmd: protocCmd{Names: []string{"go"}, Generators: []generator{{Name: "go"}}}, expectedV1: "protoc -I --go_out=import_path=:", expectedV2: "protoc -I --go_out=", }, { name: "plugin", cmd: protocCmd{Names: []string{"go"}, Plugins: []string{"grpc"}, Generators: []generator{{Name: "go"}}}, expectedV1: "protoc -I --go_out=plugins=grpc,import_path=:", expectedV2: "protoc -I --go_out=", }, { name: "use protoc-gen-go-grpc instead of plugins", cmd: protocCmd{Names: []string{"go", "go-grpc"}, Generators: []generator{{Name: "go"}, {Name: "go-grpc"}}}, expectedV1: "protoc -I --go_out=import_path=: --go-grpc_out=import_path=:", expectedV2: "protoc -I --go_out= --go-grpc_out=", }, { name: "use custom parameters", cmd: protocCmd{ Names: []string{"go", "go-ttrpc"}, Generators: []generator{ { Name: "go", Parameters: map[string]string{ "Mpath": "newpath", }, }, { Name: "go-ttrpc", Parameters: map[string]string{ "prefix": "TTRPC", }, }, }, }, expectedV1: "protoc -I --go_out=import_path=: --go-ttrpc_out=import_path=:", expectedV2: "protoc -I --go_out= --go_opt=Mpath=newpath --go-ttrpc_out= --go-ttrpc_opt=prefix=TTRPC", }, } for _, tc := range testcases { t.Run(tc.name+"V1", func(t *testing.T) { cmd := &tc.cmd cmd.Version = 1 s, err := cmd.mkcmd() if err != nil { t.Fatalf("err must be nil but %+v", err) } if s != tc.expectedV1 { t.Fatalf(`s must be %q, but %q`, tc.expectedV1, s) } }) t.Run(tc.name+"V2", func(t *testing.T) { cmd := &tc.cmd cmd.Version = 2 s, err := cmd.mkcmd() if err != nil { t.Fatalf("err must be nil but %+v", err) } if s != tc.expectedV2 { t.Fatalf(`s must be %q, but %q`, tc.expectedV2, s) } }) } } protobuild-0.3.0/protoc_unix.go000066400000000000000000000012341433225625300166020ustar00rootroot00000000000000// +build !windows /* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main const ( shCmd = "sh" shArg = "-c" ) protobuild-0.3.0/protoc_windows.go000066400000000000000000000012151433225625300173100ustar00rootroot00000000000000/* Copyright The containerd Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package main const ( shCmd = "cmd.exe" shArg = "/c" ) protobuild-0.3.0/v2.toml000066400000000000000000000003621433225625300151270ustar00rootroot00000000000000version = "2" generators = ["go", "go-grpc"] [packages] "google/protobuf/empty.proto" = "github.com/containerd/protobuild/internal" [[descriptors]] prefix = "github.com/containerd/protobuild/examples/v2" target = "examples/v2/next.pb.txt"