VOL-2629 Modified Makefile to use containerized tools.
Modified existing containers to build internally, rather than bind-mounting the whole project & running make targets.
This repo has C dependencies, which must be made available, which complicates the usage of containerized tools. Some tool containers are augmented before use.
"build-" targets will continue to use locally installed golang.
"release-" targets will use containerized tools, and will cross-compile only bbsimctl.
Change-Id: I02c999a29361d26aa9198d1f03b2b050febfe954
diff --git a/.gitignore b/.gitignore
index 050d517..2bb1068 100644
--- a/.gitignore
+++ b/.gitignore
@@ -8,3 +8,4 @@
*.logs
*.trace
.idea
+sca-report/
diff --git a/.golangci.yml b/.golangci.yml
new file mode 100644
index 0000000..da0158b
--- /dev/null
+++ b/.golangci.yml
@@ -0,0 +1,25 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+run:
+ modules-download-mode: vendor
+
+linters:
+ enable:
+ #- gochecknoglobals
+ #- gochecknoinits
+ #- gocritic
+ - gofmt
+ #- golint
+ #- unparam
diff --git a/Makefile b/Makefile
index c92ae39..4db46d1 100644
--- a/Makefile
+++ b/Makefile
@@ -24,67 +24,90 @@
DOCKER_PORTS ?= -p 50070:50070 -p 50060:50060 -p 50071:50071 -p 50072:50072 -p 50073:50073 -p 50074:50074
TYPE ?= minimal
-## protobuf related
-VOLTHA_PROTOS ?= $(shell GO111MODULE=on go list -f '{{ .Dir }}' -m github.com/opencord/voltha-protos/v2)
-GOOGLEAPI ?= $(shell GO111MODULE=on go list -f '{{ .Dir }}' -m github.com/grpc-ecosystem/grpc-gateway)
-TOOLS_DIR := tools
-TOOLS_BIN := $(TOOLS_DIR)/bin/
+# tool containers
+VOLTHA_TOOLS_VERSION ?= 2.1.0
-export PATH=$(shell echo $$PATH):$(PWD)/$(TOOLS_BIN)
+GO = docker run --rm --user $$(id -u):$$(id -g) -v ${CURDIR}:/app $(shell test -t 0 && echo "-it") -v gocache:/.cache -v gocache-${VOLTHA_TOOLS_VERSION}:/go/pkg voltha/voltha-ci-tools:${VOLTHA_TOOLS_VERSION}-golang go
+GO_SH = docker run --rm --user $$(id -u):$$(id -g) -v ${CURDIR}:/app $(shell test -t 0 && echo "-it") -v gocache:/.cache -v gocache-${VOLTHA_TOOLS_VERSION}:/go/pkg voltha/voltha-ci-tools:${VOLTHA_TOOLS_VERSION}-golang sh -c '
+BBSIM_BUILDER = docker run --rm --user $$(id -u):$$(id -g) -v ${CURDIR}:/app $(shell test -t 0 && echo "-it") -v gocache:/.cache -v gocache-${VOLTHA_TOOLS_VERSION}:/go/pkg bbsim-builder go
+GO_JUNIT_REPORT = docker run --rm --user $$(id -u):$$(id -g) -v ${CURDIR}:/app -i voltha/voltha-ci-tools:${VOLTHA_TOOLS_VERSION}-go-junit-report go-junit-report
+GOCOVER_COBERTURA = docker run --rm --user $$(id -u):$$(id -g) -v ${CURDIR}:/app -i voltha/voltha-ci-tools:${VOLTHA_TOOLS_VERSION}-gocover-cobertura gocover-cobertura
+BBSIM_LINTER = docker run --rm --user $$(id -u):$$(id -g) -v ${CURDIR}:/app $(shell test -t 0 && echo "-it") -v gocache:/.cache -v gocache-${VOLTHA_TOOLS_VERSION}:/go/pkg bbsim-linter:${VOLTHA_TOOLS_VERSION}-golangci-lint golangci-lint
+HADOLINT = docker run --rm --user $$(id -u):$$(id -g) -v ${CURDIR}:/app $(shell test -t 0 && echo "-it") voltha/voltha-ci-tools:${VOLTHA_TOOLS_VERSION}-hadolint hadolint
+PROTOC = docker run --rm --user $$(id -u):$$(id -g) -v ${CURDIR}:/app $(shell test -t 0 && echo "-it") -v gocache-${VOLTHA_TOOLS_VERSION}:/go/pkg voltha/voltha-ci-tools:${VOLTHA_TOOLS_VERSION}-protoc protoc
+
+builder:
+ @docker build -t bbsim-builder:latest -f build/ci/builder.Dockerfile build/ci/
+
+linter:
+ # since this repo depends on C libs (libpcap), they are first added into a local container
+ @[[ "$(docker images -q bbsim-linter:${VOLTHA_TOOLS_VERSION}-golangci-lint 2> /dev/null)" != "" ]] || \
+ docker build --build-arg=VOLTHA_TOOLS_VERSION=${VOLTHA_TOOLS_VERSION} -t bbsim-linter:${VOLTHA_TOOLS_VERSION}-golangci-lint -f build/ci/linter.Dockerfile build/ci/
+
# Public targets
all: help
-# go installed tools.go
-GO_TOOLS := github.com/golang/protobuf/protoc-gen-go \
- github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway \
- github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
-
-# tools
-GO_TOOLS_BIN := $(addprefix $(TOOLS_BIN), $(notdir $(GO_TOOLS)))
-GO_TOOLS_VENDOR := $(addprefix vendor/, $(GO_TOOLS))
-
-TEST_PACKAGES := github.com/opencord/bbsim/cmd/... \
- github.com/opencord/bbsim/internal/...
-
-setup_tools: $(GO_TOOLS_BIN)
- GO111MODULE=on go mod download all
-
-$(GO_TOOLS_BIN): $(GO_TOOLS_VENDOR)
- GO111MODULE=on GOBIN="$(PWD)/$(TOOLS_BIN)" go install $(GO_TOOLS)
-
-protos: setup_tools api/bbsim/bbsim.pb.go api/bbsim/bbsim.pb.gw.go api/legacy/bbsim.pb.go api/legacy/bbsim.pb.gw.go # @HELP Build proto files
-
-dep: protos # @HELP Download the dependencies to the vendor folder
- GO111MODULE=on go mod vendor
- GO111MODULE=on go mod tidy
- GO111MODULE=on go mod verify
-
-_build: dep protos fmt build-bbsim build-bbsimctl build-bbr
+protos: api/bbsim/bbsim.pb.go api/bbsim/bbsim.pb.gw.go api/legacy/bbsim.pb.go api/legacy/bbsim.pb.gw.go # @HELP Build proto files
.PHONY: build
-build: # @HELP Build the binaries (it runs inside a docker container and output the built code on your local file system)
- docker build -t ${DOCKER_REGISTRY}${DOCKER_REPOSITORY}bbsim-builder:${DOCKER_TAG} -f build/ci/Dockerfile.builder .
- docker run --rm -v $(shell pwd):/bbsim ${DOCKER_REGISTRY}${DOCKER_REPOSITORY}bbsim-builder:${DOCKER_TAG} /bin/sh -c "cd /bbsim; make _build"
+build: protos build-bbsim build-bbsimctl build-bbr
+
+## lint and unit tests
+
+lint-dockerfile:
+ @echo "Running Dockerfile lint check..."
+ @${HADOLINT} $$(find ./build -name "Dockerfile*")
+ @echo "Dockerfile lint check OK"
+
+lint-mod:
+ @echo "Running dependency check..."
+ @${GO} mod verify
+ @echo "Dependency check OK. Running vendor check..."
+ @git status > /dev/null
+ @git diff-index --quiet HEAD -- go.mod go.sum vendor || (echo "ERROR: Staged or modified files must be committed before running this test" && git status -- go.mod go.sum vendor && exit 1)
+ @[[ `git ls-files --exclude-standard --others go.mod go.sum vendor` == "" ]] || (echo "ERROR: Untracked files must be cleaned up before running this test" && git status -- go.mod go.sum vendor && exit 1)
+ ${GO} mod tidy
+ ${GO} mod vendor
+ @git status > /dev/null
+ @git diff-index --quiet HEAD -- go.mod go.sum vendor || (echo "ERROR: Modified files detected after running go mod tidy / go mod vendor" && git status -- go.mod go.sum vendor && git checkout -- go.mod go.sum vendor && exit 1)
+ @[[ `git ls-files --exclude-standard --others go.mod go.sum vendor` == "" ]] || (echo "ERROR: Untracked files detected after running go mod tidy / go mod vendor" && git status -- go.mod go.sum vendor && git checkout -- go.mod go.sum vendor && exit 1)
+ @echo "Vendor check OK."
+
+lint: lint-mod lint-dockerfile
+
+sca: linter
+ @rm -rf ./sca-report
+ @mkdir -p ./sca-report
+ @echo "Running static code analysis..."
+ @${BBSIM_LINTER} run --deadline=4m --out-format junit-xml ./... | tee ./sca-report/sca-report.xml
+ @echo ""
+ @echo "Static code analysis OK"
test: test-unit test-bbr
-test-unit: clean dep fmt local-omci-sim # @HELP Execute unit tests
- GO111MODULE=on go test -v -mod vendor $(TEST_PACKAGES) -timeout 10s -covermode count -coverprofile ./tests/results/go-test-coverage.out 2>&1 | tee ./tests/results/go-test-results.out
- go-junit-report < ./tests/results/go-test-results.out > ./tests/results/go-test-results.xml
- gocover-cobertura < ./tests/results/go-test-coverage.out > ./tests/results/go-test-coverage.xml
+test-unit: clean local-omci-sim builder # @HELP Execute unit tests
+ @mkdir -p ./tests/results
+ @${BBSIM_BUILDER} test -mod=vendor -v -coverprofile ./tests/results/go-test-coverage.out -covermode count ./... 2>&1 | tee ./tests/results/go-test-results.out ;\
+ RETURN=$$? ;\
+ ${GO_JUNIT_REPORT} < ./tests/results/go-test-results.out > ./tests/results/go-test-results.xml ;\
+ ${GOCOVER_COBERTURA} < ./tests/results/go-test-coverage.out > ./tests/results/go-test-coverage.xml ;\
+ exit $$RETURN
-test-bbr: build-bbr docker-build # @HELP Validate that BBSim and BBR are working together
+test-bbr: release-bbr docker-build # @HELP Validate that BBSim and BBR are working together
DOCKER_RUN_ARGS="-auth -dhcp -pon 2 -onu 2" make docker-run
sleep 5
- ./bbr -pon 2 -onu 2
+ ./$(RELEASE_DIR)/$(RELEASE_BBR_NAME)-linux-amd64 -pon 2 -onu 2
docker rm -f bbsim
-fmt:
- go fmt ./...
+mod-update: # @HELP Download the dependencies to the vendor folder
+ ${GO} mod tidy
+ ${GO} mod vendor
docker-build: local-omci-sim# @HELP Build the BBSim docker container (contains BBSimCtl too)
- docker build -t ${DOCKER_REGISTRY}${DOCKER_REPOSITORY}bbsim:${DOCKER_TAG} -f build/package/Dockerfile .
+ docker build \
+ -t ${DOCKER_REGISTRY}${DOCKER_REPOSITORY}bbsim:${DOCKER_TAG} \
+ -f build/package/Dockerfile .
docker-push: # @HELP Push the docker container to a registry
docker push ${DOCKER_REGISTRY}${DOCKER_REPOSITORY}bbsim:${DOCKER_TAG}
@@ -113,31 +136,42 @@
RELEASE_DIR ?= release
RELEASE_OS_ARCH ?= linux-amd64 linux-arm64 windows-amd64 darwin-amd64
-RELEASE_BBR_NAME ?= bbr
-RELEASE_BBR_BINS := $(foreach rel,$(RELEASE_OS_ARCH),$(RELEASE_DIR)/$(RELEASE_BBR_NAME)-$(rel))
-RELEASE_BBSIM_NAME ?= bbsimctl
-RELEASE_BBSIM_BINS := $(foreach rel,$(RELEASE_OS_ARCH),$(RELEASE_DIR)/$(RELEASE_BBSIM_NAME)-$(rel))
+RELEASE_BBR_NAME ?= bbr
+RELEASE_BBSIM_NAME ?= bbsim
+RELEASE_BBSIMCTL_NAME ?= bbsimctl
-$(RELEASE_BBR_BINS):
- export GOOS=$(rel_os) ;\
- export GOARCH=$(rel_arch) ;\
- GO111MODULE=on go build -i -v -mod vendor \
- -ldflags "-w -X main.buildTime=$(shell date +”%Y/%m/%d-%H:%M:%S”) \
- -X main.gitStatus=${GIT_STATUS} \
- -X main.version=${VERSION}" \
- -o "$@" ./cmd/bbr
+release-bbr: builder
+ @echo "$(RELEASE_BBR_NAME)-linux-amd64"
+ @${BBSIM_BUILDER} build -mod vendor \
+ -ldflags "-w -X main.buildTime=$(shell date +%Y/%m/%d-%H:%M:%S) \
+ -X main.commitHash=$(shell git log --pretty=format:%H -n 1) \
+ -X main.gitStatus=${GIT_STATUS} \
+ -X main.version=${VERSION}" \
+ -o "$(RELEASE_DIR)/$(RELEASE_BBR_NAME)-linux-amd64" ./cmd/bbr
-$(RELEASE_BBSIM_BINS):
- export GOOS=$(rel_os) ;\
- export GOARCH=$(rel_arch) ;\
- GO111MODULE=on go build -i -v -mod vendor \
- -ldflags "-w -X main.buildTime=$(shell date +”%Y/%m/%d-%H:%M:%S”) \
- -X main.gitStatus=${GIT_STATUS} \
- -X main.version=${VERSION}" \
- -o "$@" ./cmd/bbsim
+release-bbsim: builder
+ @echo "$(RELEASE_BBSIM_NAME)-linux-amd64"
+ @${BBSIM_BUILDER} build -mod vendor \
+ -ldflags "-w -X main.buildTime=$(shell date +%Y/%m/%d-%H:%M:%S) \
+ -X main.commitHash=$(shell git log --pretty=format:%H -n 1) \
+ -X main.gitStatus=${GIT_STATUS} \
+ -X main.version=${VERSION}" \
+ -o "$(RELEASE_DIR)/$(RELEASE_BBSIM_NAME)-linux-amd64" ./cmd/bbsim
-.PHONY: release $(RELEASE_BBR_BINS) $(RELEASE_BBSIM_BINS)
-release: dep protos $(RELEASE_BBR_BINS) $(RELEASE_BBSIM_BINS) # @HELP Creates release ready bynaries for BBSimctl and BBR artifacts
+release-bbsimctl:
+ @${GO_SH} set -eo pipefail; \
+ for os_arch in ${RELEASE_OS_ARCH}; do \
+ echo "$(RELEASE_BBSIMCTL_NAME)-$$os_arch"; \
+ GOOS="$${os_arch%-*}" GOARCH="$${os_arch#*-}" go build -mod vendor \
+ -ldflags "-w -X github.com/opencord/bbsim/internal/bbsimctl/config.BuildTime=$(shell date +%Y/%m/%d-%H:%M:%S) \
+ -X github.com/opencord/bbsim/internal/bbsimctl/config.CommitHash=$(shell git log --pretty=format:%H -n 1) \
+ -X github.com/opencord/bbsim/internal/bbsimctl/config.GitStatus=${GIT_STATUS} \
+ -X github.com/opencord/bbsim/internal/bbsimctl/config.Version=${VERSION}" \
+ -o "$(RELEASE_DIR)/$(RELEASE_BBSIMCTL_NAME)-$$os_arch" ./cmd/bbsimctl; \
+ done'
+
+.PHONY: release release-bbr release-bbsim release-bbsimctl
+release: release-bbr release-bbsim release-bbsimctl # @HELP Creates release ready bynaries for BBSimctl and BBR artifacts
swagger: docs/swagger/bbsim/bbsim.swagger.json docs/swagger/leagacy/bbsim.swagger.json # @HELP Generate swagger documentation for BBSim API
help: # @HELP Print the command options
@@ -164,68 +198,83 @@
# Internals
clean:
- rm -f bbsim
- rm -f bbsimctl
- rm -f bbr
- rm -rf tools/bin
+ @rm -f bbsim
+ @rm -f bbsimctl
+ @rm -f bbr
+ @rm -rf tools/bin
+ @rm -rf release/*
build-bbr: local-omci-sim
- GO111MODULE=on go build -i -v -mod vendor \
- -ldflags "-w -X main.buildTime=$(shell date +”%Y/%m/%d-%H:%M:%S”) \
- -X main.commitHash=$(shell git log --pretty=format:%H -n 1) \
- -X main.gitStatus=${GIT_STATUS} \
- -X main.version=${VERSION}" \
- ./cmd/bbr
+ @go build -mod vendor \
+ -ldflags "-w -X main.buildTime=$(shell date +%Y/%m/%d-%H:%M:%S) \
+ -X main.commitHash=$(shell git log --pretty=format:%H -n 1) \
+ -X main.gitStatus=${GIT_STATUS} \
+ -X main.version=${VERSION}" \
+ ./cmd/bbr
build-bbsim:
- GO111MODULE=on go build -i -v -mod vendor \
- -ldflags "-w -X main.buildTime=$(shell date +”%Y/%m/%d-%H:%M:%S”) \
- -X main.commitHash=$(shell git log --pretty=format:%H -n 1) \
- -X main.gitStatus=${GIT_STATUS} \
- -X main.version=${VERSION}" \
- ./cmd/bbsim
+ @go build -mod vendor \
+ -ldflags "-w -X main.buildTime=$(shell date +%Y/%m/%d-%H:%M:%S) \
+ -X main.commitHash=$(shell git log --pretty=format:%H -n 1) \
+ -X main.gitStatus=${GIT_STATUS} \
+ -X main.version=${VERSION}" \
+ ./cmd/bbsim
build-bbsimctl:
- GO111MODULE=on go build -i -v -mod vendor \
- -ldflags "-w -X github.com/opencord/bbsim/internal/bbsimctl/config.BuildTime=$(shell date +”%Y/%m/%d-%H:%M:%S”) \
- -X github.com/opencord/bbsim/internal/bbsimctl/config.CommitHash=$(shell git log --pretty=format:%H -n 1) \
- -X github.com/opencord/bbsim/internal/bbsimctl/config.GitStatus=${GIT_STATUS} \
- -X github.com/opencord/bbsim/internal/bbsimctl/config.Version=${VERSION}" \
- ./cmd/bbsimctl
+ @go build -mod vendor \
+ -ldflags "-w -X github.com/opencord/bbsim/internal/bbsimctl/config.BuildTime=$(shell date +%Y/%m/%d-%H:%M:%S) \
+ -X github.com/opencord/bbsim/internal/bbsimctl/config.CommitHash=$(shell git log --pretty=format:%H -n 1) \
+ -X github.com/opencord/bbsim/internal/bbsimctl/config.GitStatus=${GIT_STATUS} \
+ -X github.com/opencord/bbsim/internal/bbsimctl/config.Version=${VERSION}" \
+ ./cmd/bbsimctl
-api/openolt/openolt.pb.go: api/openolt/openolt.proto
- @protoc -I. \
- -I${GOOGLEAPI}/third_party/googleapis \
- --go_out=plugins=grpc:./ \
- $<
+setup_tools:
+ @echo "Downloading dependencies..."
+ @${GO} mod download github.com/grpc-ecosystem/grpc-gateway github.com/opencord/voltha-protos/v2
+ @echo "Dependencies downloaded OK"
-api/bbsim/bbsim.pb.go api/bbsim/bbsim.pb.gw.go: api/bbsim/bbsim.proto api/bbsim/bbsim.yaml
- @protoc -I. \
- -I${GOOGLEAPI}/third_party/googleapis \
- -I${VOLTHA_PROTOS}/protos/ \
- --go_out=plugins=grpc:./ \
- --grpc-gateway_out=logtostderr=true,grpc_api_configuration=api/bbsim/bbsim.yaml,allow_delete_body=true:./ \
- $<
+VOLTHA_PROTOS ?= $(shell ${GO} list -f '{{ .Dir }}' -m github.com/opencord/voltha-protos/v2)
+GOOGLEAPI ?= $(shell ${GO} list -f '{{ .Dir }}' -m github.com/grpc-ecosystem/grpc-gateway)
-api/legacy/bbsim.pb.go api/legacy/bbsim.pb.gw.go: api/legacy/bbsim.proto
- @protoc -I. \
- -I${GOOGLEAPI}/third_party/googleapis/ \
- -I${GOOGLEAPI}/ \
- -I${VOLTHA_PROTOS}/protos/ \
- --go_out=plugins=grpc:./ \
- --grpc-gateway_out=logtostderr=true,allow_delete_body=true:./ \
- $<
+.PHONY: api/openolt/openolt.pb.go api/bbsim/bbsim.pb.go api/bbsim/bbsim.pb.gw.go api/legacy/bbsim.pb.go api/legacy/bbsim.pb.gw.go docs/swagger/bbsim/bbsim.swagger.json docs/swagger/leagacy/bbsim.swagger.json
+api/openolt/openolt.pb.go: api/openolt/openolt.proto setup_tools
+ @echo $@
+ @${PROTOC} -I. \
+ -I${GOOGLEAPI}/third_party/googleapis \
+ --go_out=plugins=grpc:./ \
+ $<
-docs/swagger/bbsim/bbsim.swagger.json: api/bbsim/bbsim.yaml
- @protoc -I ./api \
- -I${GOOGLEAPI}/ \
- -I${VOLTHA_PROTOS}/protos/ \
- --swagger_out=logtostderr=true,allow_delete_body=true,grpc_api_configuration=$<:docs/swagger/ \
- api/bbsim/bbsim.proto
+api/bbsim/bbsim.pb.go api/bbsim/bbsim.pb.gw.go: api/bbsim/bbsim.proto api/bbsim/bbsim.yaml setup_tools
+ @echo $@
+ @${PROTOC} -I. \
+ -I${GOOGLEAPI}/third_party/googleapis \
+ -I${VOLTHA_PROTOS}/protos/ \
+ --go_out=plugins=grpc:./ \
+ --grpc-gateway_out=logtostderr=true,grpc_api_configuration=api/bbsim/bbsim.yaml,allow_delete_body=true:./ \
+ $<
-docs/swagger/leagacy/bbsim.swagger.json: api/legacy/bbsim.proto
- @protoc -I ./api \
- -I${GOOGLEAPI}/ \
- -I${VOLTHA_PROTOS}/protos/ \
- --swagger_out=logtostderr=true,allow_delete_body=true:docs/swagger/ \
- $<
+api/legacy/bbsim.pb.go api/legacy/bbsim.pb.gw.go: api/legacy/bbsim.proto setup_tools
+ @echo $@
+ @${PROTOC} -I. \
+ -I${GOOGLEAPI}/third_party/googleapis/ \
+ -I${GOOGLEAPI}/ \
+ -I${VOLTHA_PROTOS}/protos/ \
+ --go_out=plugins=grpc:./ \
+ --grpc-gateway_out=logtostderr=true,allow_delete_body=true:./ \
+ $<
+
+docs/swagger/bbsim/bbsim.swagger.json: api/bbsim/bbsim.yaml setup_tools
+ @echo $@
+ @${PROTOC} -I ./api \
+ -I${GOOGLEAPI}/ \
+ -I${VOLTHA_PROTOS}/protos/ \
+ --swagger_out=logtostderr=true,allow_delete_body=true,grpc_api_configuration=$<:docs/swagger/ \
+ api/bbsim/bbsim.proto
+
+docs/swagger/leagacy/bbsim.swagger.json: api/legacy/bbsim.proto setup_tools
+ @echo $@
+ @${PROTOC} -I ./api \
+ -I${GOOGLEAPI}/ \
+ -I${VOLTHA_PROTOS}/protos/ \
+ --swagger_out=logtostderr=true,allow_delete_body=true:docs/swagger/ \
+ $<
diff --git a/api/bbsim/bbsim.pb.go b/api/bbsim/bbsim.pb.go
index 729aadd..7d3a9ee 100644
--- a/api/bbsim/bbsim.pb.go
+++ b/api/bbsim/bbsim.pb.go
@@ -1174,11 +1174,11 @@
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
-var _ grpc.ClientConnInterface
+var _ grpc.ClientConn
// 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
+const _ = grpc.SupportPackageIsVersion4
// BBSimClient is the client API for BBSim service.
//
@@ -1208,10 +1208,10 @@
}
type bBSimClient struct {
- cc grpc.ClientConnInterface
+ cc *grpc.ClientConn
}
-func NewBBSimClient(cc grpc.ClientConnInterface) BBSimClient {
+func NewBBSimClient(cc *grpc.ClientConn) BBSimClient {
return &bBSimClient{cc}
}
diff --git a/build/ci/Dockerfile.builder b/build/ci/Dockerfile.builder
deleted file mode 100644
index 0acc2b3..0000000
--- a/build/ci/Dockerfile.builder
+++ /dev/null
@@ -1,32 +0,0 @@
-# Copyright 2018-present Open Networking Foundation
-#
-# 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 container is used to provide a build environment so that we don't need
-# the prereqs installed on a CI machine
-
-FROM golang:1.12-stretch
-
-# install prereqs
-ENV PROTOC_VERSION 3.6.1
-ENV PROTOC_SHA256SUM 6003de742ea3fcf703cfec1cd4a3380fd143081a2eb0e559065563496af27807
-
-RUN apt-get update \
- && apt-get install -y unzip libpcap-dev \
- && curl -L -o /tmp/protoc-${PROTOC_VERSION}-linux-x86_64.zip https://github.com/google/protobuf/releases/download/v${PROTOC_VERSION}/protoc-${PROTOC_VERSION}-linux-x86_64.zip \
- && echo "$PROTOC_SHA256SUM /tmp/protoc-${PROTOC_VERSION}-linux-x86_64.zip" | sha256sum -c - \
- && unzip /tmp/protoc-${PROTOC_VERSION}-linux-x86_64.zip -d /tmp/protoc3 \
- && mv /tmp/protoc3/bin/* /usr/local/bin/ \
- && mv /tmp/protoc3/include/* /usr/local/include/ \
- && go get -v github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway \
- && go get -v github.com/golang/protobuf/protoc-gen-go
\ No newline at end of file
diff --git a/build/ci/builder.Dockerfile b/build/ci/builder.Dockerfile
new file mode 100644
index 0000000..94ab871
--- /dev/null
+++ b/build/ci/builder.Dockerfile
@@ -0,0 +1,23 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+FROM golang:1.13.8-stretch
+
+RUN apt-get update && apt-get install -y \
+ build-essential libpcap-dev && \
+ mkdir -m 777 /.cache /go/pkg
+
+ENV CGO_ENABLED=1
+
+WORKDIR /app
\ No newline at end of file
diff --git a/build/ci/linter.Dockerfile b/build/ci/linter.Dockerfile
new file mode 100644
index 0000000..bc3274a
--- /dev/null
+++ b/build/ci/linter.Dockerfile
@@ -0,0 +1,19 @@
+# Copyright 2020-present Open Networking Foundation
+#
+# 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.
+
+ARG VOLTHA_TOOLS_VERSION
+FROM voltha/voltha-ci-tools:${VOLTHA_TOOLS_VERSION}-golangci-lint
+
+# install repo-specific C dependencies
+RUN apk add --no-cache build-base libpcap-dev
diff --git a/build/package/Dockerfile b/build/package/Dockerfile
index d5caae0..2fa4633 100644
--- a/build/package/Dockerfile
+++ b/build/package/Dockerfile
@@ -15,35 +15,32 @@
# bbsim dockerfile
# builder parent
-FROM golang:1.12-stretch as builder
+FROM golang:1.13.8-stretch as builder
-# install prereqs
-ENV PROTOC_VERSION 3.7.0
-ENV PROTOC_SHA256SUM a1b8ed22d6dc53c5b8680a6f1760a305b33ef471bece482e92728f00ba2a2969
+RUN apt-get update && apt-get install -y build-essential libpcap-dev
-RUN apt-get update \
- && apt-get install -y unzip libpcap-dev \
- && curl -L -o /tmp/protoc-${PROTOC_VERSION}-linux-x86_64.zip https://github.com/google/protobuf/releases/download/v${PROTOC_VERSION}/protoc-${PROTOC_VERSION}-linux-x86_64.zip \
- && echo "$PROTOC_SHA256SUM /tmp/protoc-${PROTOC_VERSION}-linux-x86_64.zip" | sha256sum -c - \
- && unzip /tmp/protoc-${PROTOC_VERSION}-linux-x86_64.zip -d /tmp/protoc3 \
- && mv /tmp/protoc3/bin/* /usr/local/bin/ \
- && mv /tmp/protoc3/include/* /usr/local/include/ \
- && go get -v github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway \
- && go get -v github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger \
- && go get -v github.com/golang/protobuf/protoc-gen-go
+ENV CGO_ENABLED=1
-WORKDIR /go/src/github.com/opencord/bbsim
-ENV GO111MODULE=on
-ENV GOPROXY=https://proxy.golang.org
+WORKDIR /app
# copy and build
COPY . ./
-RUN make protos
-RUN make build-bbsim
-RUN make build-bbsimctl
+
+RUN go build -mod vendor \
+ -ldflags "-w -X main.buildTime=$(date +%Y/%m/%d-%H:%M:%S) \
+ -X main.commitHash=$(git log --pretty=format:%H -n 1) \
+ -X main.gitStatus=${GIT_STATUS} \
+ -X main.version=${VERSION}" \
+ ./cmd/bbsim && \
+ go build -mod vendor \
+ -ldflags "-w -X github.com/opencord/bbsim/internal/bbsimctl/config.BuildTime=$(date +%Y/%m/%d-%H:%M:%S) \
+ -X github.com/opencord/bbsim/internal/bbsimctl/config.CommitHash=$(git log --pretty=format:%H -n 1) \
+ -X github.com/opencord/bbsim/internal/bbsimctl/config.GitStatus=${GIT_STATUS} \
+ -X github.com/opencord/bbsim/internal/bbsimctl/config.Version=${VERSION}" \
+ ./cmd/bbsimctl
# runtime parent
-FROM golang:1.12-stretch
+FROM ubuntu:18.04
# runtime prereqs
# the symlink on libpcap is because both alpine and debian come with 1.8.x, but
@@ -51,7 +48,7 @@
# https://packages.debian.org/stretch/libpcap0.8-dev
RUN apt-get update \
&& apt-get install -y libpcap-dev isc-dhcp-server network-manager tcpdump\
- && ln -s /usr/lib/libpcap.so.1.8.1 /usr/lib/libpcap.so.0.8
+ && ln -s /usr/lib/libpcap.so.1.8.1 /usr/lib/libpcap.so.0.9
COPY ./configs/dhcpd.conf /etc/dhcp/
RUN mv /usr/sbin/dhcpd /usr/local/bin/ \
@@ -59,8 +56,8 @@
&& touch /var/lib/dhcp/dhcpd.leases
WORKDIR /app
-COPY --from=builder /go/src/github.com/opencord/bbsim/bbsim /app/bbsim
-COPY --from=builder /go/src/github.com/opencord/bbsim/bbsimctl /usr/bin/bbsimctl
+COPY --from=builder /app/bbsim /app/bbsim
+COPY --from=builder /app/bbsimctl /usr/bin/bbsimctl
RUN mv /usr/sbin/tcpdump /usr/bin/tcpdump
RUN chmod a+x /app/bbsim
RUN chmod a+x /usr/bin/bbsimctl
diff --git a/internal/bbsim/alarmsim/alarmsim.go b/internal/bbsim/alarmsim/alarmsim.go
index aa80212..b5b62c1 100644
--- a/internal/bbsim/alarmsim/alarmsim.go
+++ b/internal/bbsim/alarmsim/alarmsim.go
@@ -19,6 +19,7 @@
import (
"context"
"fmt"
+ "github.com/opencord/bbsim/internal/common"
"strconv"
"github.com/opencord/bbsim/api/bbsim"
@@ -28,43 +29,13 @@
"google.golang.org/grpc/status"
)
-// OnuAlarmNameMap string to enum map
-var OnuAlarmNameMap = map[string]bbsim.AlarmType_Types{
- "DyingGasp": bbsim.AlarmType_DYING_GASP,
- "StartupFailure": bbsim.AlarmType_ONU_STARTUP_FAILURE,
- "SignalDegrade": bbsim.AlarmType_ONU_SIGNAL_DEGRADE,
- "DriftOfWindow": bbsim.AlarmType_ONU_DRIFT_OF_WINDOW,
- "LossOfOmciChannel": bbsim.AlarmType_ONU_LOSS_OF_OMCI_CHANNEL,
- "SignalsFailure": bbsim.AlarmType_ONU_SIGNALS_FAILURE,
- "TransmissionInterference": bbsim.AlarmType_ONU_TRANSMISSION_INTERFERENCE_WARNING,
- "ActivationFailure": bbsim.AlarmType_ONU_ACTIVATION_FAILURE,
- "ProcessingError": bbsim.AlarmType_ONU_PROCESSING_ERROR,
- "LossOfKeySyncFailure": bbsim.AlarmType_ONU_LOSS_OF_KEY_SYNC_FAILURE,
-
- // Break out OnuAlarm into its subcases.
- "LossOfSignal": bbsim.AlarmType_ONU_ALARM_LOS,
- "LossOfBurst": bbsim.AlarmType_ONU_ALARM_LOB,
- "LOPC_MISS": bbsim.AlarmType_ONU_ALARM_LOPC_MISS,
- "LOPC_MIC_ERROR": bbsim.AlarmType_ONU_ALARM_LOPC_MIC_ERROR,
- "LossOfFrame": bbsim.AlarmType_ONU_ALARM_LOFI,
- "LossOfPloam": bbsim.AlarmType_ONU_ALARM_LOAMI,
-}
-
-// OltAlarmNameMap string to enum map
-var OltAlarmNameMap = map[string]bbsim.AlarmType_Types{
- // PON / Non-onu-specific
- "PonLossOfSignal": bbsim.AlarmType_LOS,
- // NNI / Non-onu-specific
- "NniLossOfSignal": bbsim.AlarmType_LOS,
-}
-
-func AlarmNameToEnum(name string) (*bbsim.AlarmType_Types, error) {
- v, okay := OnuAlarmNameMap[name]
+func AlarmNameToEnum(name string) (bbsim.AlarmType_Types, error) {
+ v, okay := common.ONUAlarms[name]
if !okay {
- return nil, fmt.Errorf("Unknown Alarm Name: %v", name)
+ return 0, fmt.Errorf("Unknown Alarm Name: %v", name)
}
- return &v, nil
+ return v, nil
}
// Find a key in the optional AlarmParameters, convert it to an integer,
@@ -92,7 +63,7 @@
return nil, err
}
- if *alarmType != bbsim.AlarmType_LOS {
+ if alarmType != bbsim.AlarmType_LOS {
// No ONU Id for LOS
onu, err = o.FindOnuBySn(req.SerialNumber)
if err != nil {
@@ -100,7 +71,7 @@
}
}
- switch *alarmType {
+ switch alarmType {
case bbsim.AlarmType_DYING_GASP:
alarm = &openolt.AlarmIndication{
Data: &openolt.AlarmIndication_DyingGaspInd{&openolt.DyingGaspIndication{
@@ -242,7 +213,7 @@
}},
}
default:
- return nil, fmt.Errorf("Unknown alarm type %v", req.AlarmType)
+ return nil, fmt.Errorf("Unknown ONU alarm type %v", req.AlarmType)
}
return alarm, nil
diff --git a/internal/bbsimctl/commands/oltalarms.go b/internal/bbsimctl/commands/oltalarms.go
index f251b83..b68ca83 100755
--- a/internal/bbsimctl/commands/oltalarms.go
+++ b/internal/bbsimctl/commands/oltalarms.go
@@ -20,13 +20,13 @@
import (
"context"
"fmt"
+ "github.com/opencord/bbsim/internal/common"
"os"
"strings"
"github.com/jessevdk/go-flags"
"github.com/olekukonko/tablewriter"
pb "github.com/opencord/bbsim/api/bbsim"
- "github.com/opencord/bbsim/internal/bbsim/alarmsim"
"github.com/opencord/bbsim/internal/bbsimctl/config"
log "github.com/sirupsen/logrus"
)
@@ -79,12 +79,12 @@
InterfaceID: uint32(o.Args.IntfID),
Status: "on"}
- if string(o.Args.Name) == "PonLossOfSignal" {
+ if string(o.Args.Name) == common.OltPonLos {
req.InterfaceType = "pon"
- } else if string(o.Args.Name) == "NniLossOfSignal" {
+ } else if string(o.Args.Name) == common.OltNniLos {
req.InterfaceType = "nni"
} else {
- return fmt.Errorf("Unknown alarm type")
+ return fmt.Errorf("Unknown OLT alarm type")
}
res, err := client.SetOltAlarmIndication(ctx, &req)
@@ -109,12 +109,12 @@
InterfaceID: uint32(o.Args.IntfID),
Status: "off"}
- if string(o.Args.Name) == "PonLossOfSignal" {
+ if string(o.Args.Name) == common.OltPonLos {
req.InterfaceType = "pon"
- } else if string(o.Args.Name) == "NniLossOfSignal" {
+ } else if string(o.Args.Name) == common.OltNniLos {
req.InterfaceType = "nni"
} else {
- return fmt.Errorf("Unknown alarm type")
+ return fmt.Errorf("Unknown OLT alarm type")
}
res, err := client.SetOltAlarmIndication(ctx, &req)
@@ -135,9 +135,9 @@
fmt.Fprintf(os.Stdout, "OLT Alarms List:\n")
OltAlarmstable.SetHeader([]string{"OLT Alarms"})
- alarmNames := make([]AlarmListOutput, len(alarmsim.OltAlarmNameMap))
+ alarmNames := make([]AlarmListOutput, len(common.OLTAlarms))
i := 0
- for k := range alarmsim.OltAlarmNameMap {
+ for k := range common.OLTAlarms {
alarmNames[i] = AlarmListOutput{Name: k}
OltAlarmsValue = append(OltAlarmsValue, []string{k})
i++
@@ -151,7 +151,7 @@
func (o *OltAlarmNameString) Complete(match string) []flags.Completion {
list := make([]flags.Completion, 0)
- for k := range alarmsim.OltAlarmNameMap {
+ for k := range common.OLTAlarms {
if strings.HasPrefix(k, match) {
list = append(list, flags.Completion{Item: k})
}
diff --git a/internal/bbsimctl/commands/onualarms.go b/internal/bbsimctl/commands/onualarms.go
index dcf53a3..fb1d00e 100755
--- a/internal/bbsimctl/commands/onualarms.go
+++ b/internal/bbsimctl/commands/onualarms.go
@@ -20,13 +20,13 @@
import (
"context"
"fmt"
+ "github.com/opencord/bbsim/internal/common"
"os"
"strings"
"github.com/jessevdk/go-flags"
"github.com/olekukonko/tablewriter"
pb "github.com/opencord/bbsim/api/bbsim"
- "github.com/opencord/bbsim/internal/bbsim/alarmsim"
"github.com/opencord/bbsim/internal/bbsimctl/config"
log "github.com/sirupsen/logrus"
)
@@ -129,16 +129,16 @@
return nil
}
-// Execute OLT alarm list
+// Execute ONU alarm list
func (o *AlarmList) Execute(args []string) error {
OnuAlarmsValue := [][]string{}
OnuAlarmstable := tablewriter.NewWriter(os.Stdout)
fmt.Fprintf(os.Stdout, "ONU Alarms List:\n")
OnuAlarmstable.SetHeader([]string{"ONU Alarms"})
- alarmNames := make([]AlarmListOutput, len(alarmsim.OnuAlarmNameMap))
+ alarmNames := make([]AlarmListOutput, len(common.ONUAlarms))
i := 0
- for k := range alarmsim.OnuAlarmNameMap {
+ for k := range common.ONUAlarms {
alarmNames[i] = AlarmListOutput{Name: k}
OnuAlarmsValue = append(OnuAlarmsValue, []string{k})
i++
@@ -152,7 +152,7 @@
func (onuSn *AlarmNameString) Complete(match string) []flags.Completion {
list := make([]flags.Completion, 0)
- for k := range alarmsim.OnuAlarmNameMap {
+ for k := range common.ONUAlarms {
if strings.HasPrefix(k, match) {
list = append(list, flags.Completion{Item: k})
}
diff --git a/internal/common/alarms.go b/internal/common/alarms.go
new file mode 100644
index 0000000..5102372
--- /dev/null
+++ b/internal/common/alarms.go
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2020-present Open Networking Foundation
+
+ * 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 common
+
+import (
+ "github.com/opencord/bbsim/api/bbsim"
+)
+
+var ONUAlarms = make(map[string]bbsim.AlarmType_Types)
+
+func init() {
+ for id, name := range bbsim.AlarmType_Types_name {
+ if id := bbsim.AlarmType_Types(id); id != bbsim.AlarmType_LOS {
+ ONUAlarms[name] = id
+ }
+ }
+}
+
+const OltNniLos = "OLT_NNI_LOS"
+const OltPonLos = "OLG_PON_LOS"
+
+var OLTAlarms = map[string]bbsim.AlarmType_Types{
+ OltNniLos: bbsim.AlarmType_LOS,
+ OltPonLos: bbsim.AlarmType_LOS,
+}
diff --git a/tools/main.go b/tools/main.go
index b387490..4d093a2 100644
--- a/tools/main.go
+++ b/tools/main.go
@@ -13,14 +13,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
// +build tools
package tools
import (
// protocol buffer compiler plugins
- _ "github.com/golang/protobuf/protoc-gen-go"
- _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway"
- _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger"
+ _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options"
)
diff --git a/vendor/github.com/ghodss/yaml/.gitignore b/vendor/github.com/ghodss/yaml/.gitignore
deleted file mode 100644
index e256a31..0000000
--- a/vendor/github.com/ghodss/yaml/.gitignore
+++ /dev/null
@@ -1,20 +0,0 @@
-# OSX leaves these everywhere on SMB shares
-._*
-
-# Eclipse files
-.classpath
-.project
-.settings/**
-
-# Emacs save files
-*~
-
-# Vim-related files
-[._]*.s[a-w][a-z]
-[._]s[a-w][a-z]
-*.un~
-Session.vim
-.netrwhist
-
-# Go test binaries
-*.test
diff --git a/vendor/github.com/ghodss/yaml/.travis.yml b/vendor/github.com/ghodss/yaml/.travis.yml
deleted file mode 100644
index 0e9d6ed..0000000
--- a/vendor/github.com/ghodss/yaml/.travis.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-language: go
-go:
- - 1.3
- - 1.4
-script:
- - go test
- - go build
diff --git a/vendor/github.com/ghodss/yaml/LICENSE b/vendor/github.com/ghodss/yaml/LICENSE
deleted file mode 100644
index 7805d36..0000000
--- a/vendor/github.com/ghodss/yaml/LICENSE
+++ /dev/null
@@ -1,50 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Sam Ghods
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-
-
-Copyright (c) 2012 The Go Authors. All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are
-met:
-
- * Redistributions of source code must retain the above copyright
-notice, this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above
-copyright notice, this list of conditions and the following disclaimer
-in the documentation and/or other materials provided with the
-distribution.
- * Neither the name of Google Inc. nor the names of its
-contributors may be used to endorse or promote products derived from
-this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/vendor/github.com/ghodss/yaml/README.md b/vendor/github.com/ghodss/yaml/README.md
deleted file mode 100644
index 0200f75..0000000
--- a/vendor/github.com/ghodss/yaml/README.md
+++ /dev/null
@@ -1,121 +0,0 @@
-# YAML marshaling and unmarshaling support for Go
-
-[![Build Status](https://travis-ci.org/ghodss/yaml.svg)](https://travis-ci.org/ghodss/yaml)
-
-## Introduction
-
-A wrapper around [go-yaml](https://github.com/go-yaml/yaml) designed to enable a better way of handling YAML when marshaling to and from structs.
-
-In short, this library first converts YAML to JSON using go-yaml and then uses `json.Marshal` and `json.Unmarshal` to convert to or from the struct. This means that it effectively reuses the JSON struct tags as well as the custom JSON methods `MarshalJSON` and `UnmarshalJSON` unlike go-yaml. For a detailed overview of the rationale behind this method, [see this blog post](http://ghodss.com/2014/the-right-way-to-handle-yaml-in-golang/).
-
-## Compatibility
-
-This package uses [go-yaml](https://github.com/go-yaml/yaml) and therefore supports [everything go-yaml supports](https://github.com/go-yaml/yaml#compatibility).
-
-## Caveats
-
-**Caveat #1:** When using `yaml.Marshal` and `yaml.Unmarshal`, binary data should NOT be preceded with the `!!binary` YAML tag. If you do, go-yaml will convert the binary data from base64 to native binary data, which is not compatible with JSON. You can still use binary in your YAML files though - just store them without the `!!binary` tag and decode the base64 in your code (e.g. in the custom JSON methods `MarshalJSON` and `UnmarshalJSON`). This also has the benefit that your YAML and your JSON binary data will be decoded exactly the same way. As an example:
-
-```
-BAD:
- exampleKey: !!binary gIGC
-
-GOOD:
- exampleKey: gIGC
-... and decode the base64 data in your code.
-```
-
-**Caveat #2:** When using `YAMLToJSON` directly, maps with keys that are maps will result in an error since this is not supported by JSON. This error will occur in `Unmarshal` as well since you can't unmarshal map keys anyways since struct fields can't be keys.
-
-## Installation and usage
-
-To install, run:
-
-```
-$ go get github.com/ghodss/yaml
-```
-
-And import using:
-
-```
-import "github.com/ghodss/yaml"
-```
-
-Usage is very similar to the JSON library:
-
-```go
-package main
-
-import (
- "fmt"
-
- "github.com/ghodss/yaml"
-)
-
-type Person struct {
- Name string `json:"name"` // Affects YAML field names too.
- Age int `json:"age"`
-}
-
-func main() {
- // Marshal a Person struct to YAML.
- p := Person{"John", 30}
- y, err := yaml.Marshal(p)
- if err != nil {
- fmt.Printf("err: %v\n", err)
- return
- }
- fmt.Println(string(y))
- /* Output:
- age: 30
- name: John
- */
-
- // Unmarshal the YAML back into a Person struct.
- var p2 Person
- err = yaml.Unmarshal(y, &p2)
- if err != nil {
- fmt.Printf("err: %v\n", err)
- return
- }
- fmt.Println(p2)
- /* Output:
- {John 30}
- */
-}
-```
-
-`yaml.YAMLToJSON` and `yaml.JSONToYAML` methods are also available:
-
-```go
-package main
-
-import (
- "fmt"
-
- "github.com/ghodss/yaml"
-)
-
-func main() {
- j := []byte(`{"name": "John", "age": 30}`)
- y, err := yaml.JSONToYAML(j)
- if err != nil {
- fmt.Printf("err: %v\n", err)
- return
- }
- fmt.Println(string(y))
- /* Output:
- name: John
- age: 30
- */
- j2, err := yaml.YAMLToJSON(y)
- if err != nil {
- fmt.Printf("err: %v\n", err)
- return
- }
- fmt.Println(string(j2))
- /* Output:
- {"age":30,"name":"John"}
- */
-}
-```
diff --git a/vendor/github.com/ghodss/yaml/fields.go b/vendor/github.com/ghodss/yaml/fields.go
deleted file mode 100644
index 5860074..0000000
--- a/vendor/github.com/ghodss/yaml/fields.go
+++ /dev/null
@@ -1,501 +0,0 @@
-// Copyright 2013 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-package yaml
-
-import (
- "bytes"
- "encoding"
- "encoding/json"
- "reflect"
- "sort"
- "strings"
- "sync"
- "unicode"
- "unicode/utf8"
-)
-
-// indirect walks down v allocating pointers as needed,
-// until it gets to a non-pointer.
-// if it encounters an Unmarshaler, indirect stops and returns that.
-// if decodingNull is true, indirect stops at the last pointer so it can be set to nil.
-func indirect(v reflect.Value, decodingNull bool) (json.Unmarshaler, encoding.TextUnmarshaler, reflect.Value) {
- // If v is a named type and is addressable,
- // start with its address, so that if the type has pointer methods,
- // we find them.
- if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() {
- v = v.Addr()
- }
- for {
- // Load value from interface, but only if the result will be
- // usefully addressable.
- if v.Kind() == reflect.Interface && !v.IsNil() {
- e := v.Elem()
- if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) {
- v = e
- continue
- }
- }
-
- if v.Kind() != reflect.Ptr {
- break
- }
-
- if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() {
- break
- }
- if v.IsNil() {
- if v.CanSet() {
- v.Set(reflect.New(v.Type().Elem()))
- } else {
- v = reflect.New(v.Type().Elem())
- }
- }
- if v.Type().NumMethod() > 0 {
- if u, ok := v.Interface().(json.Unmarshaler); ok {
- return u, nil, reflect.Value{}
- }
- if u, ok := v.Interface().(encoding.TextUnmarshaler); ok {
- return nil, u, reflect.Value{}
- }
- }
- v = v.Elem()
- }
- return nil, nil, v
-}
-
-// A field represents a single field found in a struct.
-type field struct {
- name string
- nameBytes []byte // []byte(name)
- equalFold func(s, t []byte) bool // bytes.EqualFold or equivalent
-
- tag bool
- index []int
- typ reflect.Type
- omitEmpty bool
- quoted bool
-}
-
-func fillField(f field) field {
- f.nameBytes = []byte(f.name)
- f.equalFold = foldFunc(f.nameBytes)
- return f
-}
-
-// byName sorts field by name, breaking ties with depth,
-// then breaking ties with "name came from json tag", then
-// breaking ties with index sequence.
-type byName []field
-
-func (x byName) Len() int { return len(x) }
-
-func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
-
-func (x byName) Less(i, j int) bool {
- if x[i].name != x[j].name {
- return x[i].name < x[j].name
- }
- if len(x[i].index) != len(x[j].index) {
- return len(x[i].index) < len(x[j].index)
- }
- if x[i].tag != x[j].tag {
- return x[i].tag
- }
- return byIndex(x).Less(i, j)
-}
-
-// byIndex sorts field by index sequence.
-type byIndex []field
-
-func (x byIndex) Len() int { return len(x) }
-
-func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
-
-func (x byIndex) Less(i, j int) bool {
- for k, xik := range x[i].index {
- if k >= len(x[j].index) {
- return false
- }
- if xik != x[j].index[k] {
- return xik < x[j].index[k]
- }
- }
- return len(x[i].index) < len(x[j].index)
-}
-
-// typeFields returns a list of fields that JSON should recognize for the given type.
-// The algorithm is breadth-first search over the set of structs to include - the top struct
-// and then any reachable anonymous structs.
-func typeFields(t reflect.Type) []field {
- // Anonymous fields to explore at the current level and the next.
- current := []field{}
- next := []field{{typ: t}}
-
- // Count of queued names for current level and the next.
- count := map[reflect.Type]int{}
- nextCount := map[reflect.Type]int{}
-
- // Types already visited at an earlier level.
- visited := map[reflect.Type]bool{}
-
- // Fields found.
- var fields []field
-
- for len(next) > 0 {
- current, next = next, current[:0]
- count, nextCount = nextCount, map[reflect.Type]int{}
-
- for _, f := range current {
- if visited[f.typ] {
- continue
- }
- visited[f.typ] = true
-
- // Scan f.typ for fields to include.
- for i := 0; i < f.typ.NumField(); i++ {
- sf := f.typ.Field(i)
- if sf.PkgPath != "" { // unexported
- continue
- }
- tag := sf.Tag.Get("json")
- if tag == "-" {
- continue
- }
- name, opts := parseTag(tag)
- if !isValidTag(name) {
- name = ""
- }
- index := make([]int, len(f.index)+1)
- copy(index, f.index)
- index[len(f.index)] = i
-
- ft := sf.Type
- if ft.Name() == "" && ft.Kind() == reflect.Ptr {
- // Follow pointer.
- ft = ft.Elem()
- }
-
- // Record found field and index sequence.
- if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct {
- tagged := name != ""
- if name == "" {
- name = sf.Name
- }
- fields = append(fields, fillField(field{
- name: name,
- tag: tagged,
- index: index,
- typ: ft,
- omitEmpty: opts.Contains("omitempty"),
- quoted: opts.Contains("string"),
- }))
- if count[f.typ] > 1 {
- // If there were multiple instances, add a second,
- // so that the annihilation code will see a duplicate.
- // It only cares about the distinction between 1 or 2,
- // so don't bother generating any more copies.
- fields = append(fields, fields[len(fields)-1])
- }
- continue
- }
-
- // Record new anonymous struct to explore in next round.
- nextCount[ft]++
- if nextCount[ft] == 1 {
- next = append(next, fillField(field{name: ft.Name(), index: index, typ: ft}))
- }
- }
- }
- }
-
- sort.Sort(byName(fields))
-
- // Delete all fields that are hidden by the Go rules for embedded fields,
- // except that fields with JSON tags are promoted.
-
- // The fields are sorted in primary order of name, secondary order
- // of field index length. Loop over names; for each name, delete
- // hidden fields by choosing the one dominant field that survives.
- out := fields[:0]
- for advance, i := 0, 0; i < len(fields); i += advance {
- // One iteration per name.
- // Find the sequence of fields with the name of this first field.
- fi := fields[i]
- name := fi.name
- for advance = 1; i+advance < len(fields); advance++ {
- fj := fields[i+advance]
- if fj.name != name {
- break
- }
- }
- if advance == 1 { // Only one field with this name
- out = append(out, fi)
- continue
- }
- dominant, ok := dominantField(fields[i : i+advance])
- if ok {
- out = append(out, dominant)
- }
- }
-
- fields = out
- sort.Sort(byIndex(fields))
-
- return fields
-}
-
-// dominantField looks through the fields, all of which are known to
-// have the same name, to find the single field that dominates the
-// others using Go's embedding rules, modified by the presence of
-// JSON tags. If there are multiple top-level fields, the boolean
-// will be false: This condition is an error in Go and we skip all
-// the fields.
-func dominantField(fields []field) (field, bool) {
- // The fields are sorted in increasing index-length order. The winner
- // must therefore be one with the shortest index length. Drop all
- // longer entries, which is easy: just truncate the slice.
- length := len(fields[0].index)
- tagged := -1 // Index of first tagged field.
- for i, f := range fields {
- if len(f.index) > length {
- fields = fields[:i]
- break
- }
- if f.tag {
- if tagged >= 0 {
- // Multiple tagged fields at the same level: conflict.
- // Return no field.
- return field{}, false
- }
- tagged = i
- }
- }
- if tagged >= 0 {
- return fields[tagged], true
- }
- // All remaining fields have the same length. If there's more than one,
- // we have a conflict (two fields named "X" at the same level) and we
- // return no field.
- if len(fields) > 1 {
- return field{}, false
- }
- return fields[0], true
-}
-
-var fieldCache struct {
- sync.RWMutex
- m map[reflect.Type][]field
-}
-
-// cachedTypeFields is like typeFields but uses a cache to avoid repeated work.
-func cachedTypeFields(t reflect.Type) []field {
- fieldCache.RLock()
- f := fieldCache.m[t]
- fieldCache.RUnlock()
- if f != nil {
- return f
- }
-
- // Compute fields without lock.
- // Might duplicate effort but won't hold other computations back.
- f = typeFields(t)
- if f == nil {
- f = []field{}
- }
-
- fieldCache.Lock()
- if fieldCache.m == nil {
- fieldCache.m = map[reflect.Type][]field{}
- }
- fieldCache.m[t] = f
- fieldCache.Unlock()
- return f
-}
-
-func isValidTag(s string) bool {
- if s == "" {
- return false
- }
- for _, c := range s {
- switch {
- case strings.ContainsRune("!#$%&()*+-./:<=>?@[]^_{|}~ ", c):
- // Backslash and quote chars are reserved, but
- // otherwise any punctuation chars are allowed
- // in a tag name.
- default:
- if !unicode.IsLetter(c) && !unicode.IsDigit(c) {
- return false
- }
- }
- }
- return true
-}
-
-const (
- caseMask = ^byte(0x20) // Mask to ignore case in ASCII.
- kelvin = '\u212a'
- smallLongEss = '\u017f'
-)
-
-// foldFunc returns one of four different case folding equivalence
-// functions, from most general (and slow) to fastest:
-//
-// 1) bytes.EqualFold, if the key s contains any non-ASCII UTF-8
-// 2) equalFoldRight, if s contains special folding ASCII ('k', 'K', 's', 'S')
-// 3) asciiEqualFold, no special, but includes non-letters (including _)
-// 4) simpleLetterEqualFold, no specials, no non-letters.
-//
-// The letters S and K are special because they map to 3 runes, not just 2:
-// * S maps to s and to U+017F 'Å¿' Latin small letter long s
-// * k maps to K and to U+212A 'K' Kelvin sign
-// See http://play.golang.org/p/tTxjOc0OGo
-//
-// The returned function is specialized for matching against s and
-// should only be given s. It's not curried for performance reasons.
-func foldFunc(s []byte) func(s, t []byte) bool {
- nonLetter := false
- special := false // special letter
- for _, b := range s {
- if b >= utf8.RuneSelf {
- return bytes.EqualFold
- }
- upper := b & caseMask
- if upper < 'A' || upper > 'Z' {
- nonLetter = true
- } else if upper == 'K' || upper == 'S' {
- // See above for why these letters are special.
- special = true
- }
- }
- if special {
- return equalFoldRight
- }
- if nonLetter {
- return asciiEqualFold
- }
- return simpleLetterEqualFold
-}
-
-// equalFoldRight is a specialization of bytes.EqualFold when s is
-// known to be all ASCII (including punctuation), but contains an 's',
-// 'S', 'k', or 'K', requiring a Unicode fold on the bytes in t.
-// See comments on foldFunc.
-func equalFoldRight(s, t []byte) bool {
- for _, sb := range s {
- if len(t) == 0 {
- return false
- }
- tb := t[0]
- if tb < utf8.RuneSelf {
- if sb != tb {
- sbUpper := sb & caseMask
- if 'A' <= sbUpper && sbUpper <= 'Z' {
- if sbUpper != tb&caseMask {
- return false
- }
- } else {
- return false
- }
- }
- t = t[1:]
- continue
- }
- // sb is ASCII and t is not. t must be either kelvin
- // sign or long s; sb must be s, S, k, or K.
- tr, size := utf8.DecodeRune(t)
- switch sb {
- case 's', 'S':
- if tr != smallLongEss {
- return false
- }
- case 'k', 'K':
- if tr != kelvin {
- return false
- }
- default:
- return false
- }
- t = t[size:]
-
- }
- if len(t) > 0 {
- return false
- }
- return true
-}
-
-// asciiEqualFold is a specialization of bytes.EqualFold for use when
-// s is all ASCII (but may contain non-letters) and contains no
-// special-folding letters.
-// See comments on foldFunc.
-func asciiEqualFold(s, t []byte) bool {
- if len(s) != len(t) {
- return false
- }
- for i, sb := range s {
- tb := t[i]
- if sb == tb {
- continue
- }
- if ('a' <= sb && sb <= 'z') || ('A' <= sb && sb <= 'Z') {
- if sb&caseMask != tb&caseMask {
- return false
- }
- } else {
- return false
- }
- }
- return true
-}
-
-// simpleLetterEqualFold is a specialization of bytes.EqualFold for
-// use when s is all ASCII letters (no underscores, etc) and also
-// doesn't contain 'k', 'K', 's', or 'S'.
-// See comments on foldFunc.
-func simpleLetterEqualFold(s, t []byte) bool {
- if len(s) != len(t) {
- return false
- }
- for i, b := range s {
- if b&caseMask != t[i]&caseMask {
- return false
- }
- }
- return true
-}
-
-// tagOptions is the string following a comma in a struct field's "json"
-// tag, or the empty string. It does not include the leading comma.
-type tagOptions string
-
-// parseTag splits a struct field's json tag into its name and
-// comma-separated options.
-func parseTag(tag string) (string, tagOptions) {
- if idx := strings.Index(tag, ","); idx != -1 {
- return tag[:idx], tagOptions(tag[idx+1:])
- }
- return tag, tagOptions("")
-}
-
-// Contains reports whether a comma-separated list of options
-// contains a particular substr flag. substr must be surrounded by a
-// string boundary or commas.
-func (o tagOptions) Contains(optionName string) bool {
- if len(o) == 0 {
- return false
- }
- s := string(o)
- for s != "" {
- var next string
- i := strings.Index(s, ",")
- if i >= 0 {
- s, next = s[:i], s[i+1:]
- }
- if s == optionName {
- return true
- }
- s = next
- }
- return false
-}
diff --git a/vendor/github.com/ghodss/yaml/yaml.go b/vendor/github.com/ghodss/yaml/yaml.go
deleted file mode 100644
index 4fb4054..0000000
--- a/vendor/github.com/ghodss/yaml/yaml.go
+++ /dev/null
@@ -1,277 +0,0 @@
-package yaml
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "reflect"
- "strconv"
-
- "gopkg.in/yaml.v2"
-)
-
-// Marshals the object into JSON then converts JSON to YAML and returns the
-// YAML.
-func Marshal(o interface{}) ([]byte, error) {
- j, err := json.Marshal(o)
- if err != nil {
- return nil, fmt.Errorf("error marshaling into JSON: %v", err)
- }
-
- y, err := JSONToYAML(j)
- if err != nil {
- return nil, fmt.Errorf("error converting JSON to YAML: %v", err)
- }
-
- return y, nil
-}
-
-// Converts YAML to JSON then uses JSON to unmarshal into an object.
-func Unmarshal(y []byte, o interface{}) error {
- vo := reflect.ValueOf(o)
- j, err := yamlToJSON(y, &vo)
- if err != nil {
- return fmt.Errorf("error converting YAML to JSON: %v", err)
- }
-
- err = json.Unmarshal(j, o)
- if err != nil {
- return fmt.Errorf("error unmarshaling JSON: %v", err)
- }
-
- return nil
-}
-
-// Convert JSON to YAML.
-func JSONToYAML(j []byte) ([]byte, error) {
- // Convert the JSON to an object.
- var jsonObj interface{}
- // We are using yaml.Unmarshal here (instead of json.Unmarshal) because the
- // Go JSON library doesn't try to pick the right number type (int, float,
- // etc.) when unmarshalling to interface{}, it just picks float64
- // universally. go-yaml does go through the effort of picking the right
- // number type, so we can preserve number type throughout this process.
- err := yaml.Unmarshal(j, &jsonObj)
- if err != nil {
- return nil, err
- }
-
- // Marshal this object into YAML.
- return yaml.Marshal(jsonObj)
-}
-
-// Convert YAML to JSON. Since JSON is a subset of YAML, passing JSON through
-// this method should be a no-op.
-//
-// Things YAML can do that are not supported by JSON:
-// * In YAML you can have binary and null keys in your maps. These are invalid
-// in JSON. (int and float keys are converted to strings.)
-// * Binary data in YAML with the !!binary tag is not supported. If you want to
-// use binary data with this library, encode the data as base64 as usual but do
-// not use the !!binary tag in your YAML. This will ensure the original base64
-// encoded data makes it all the way through to the JSON.
-func YAMLToJSON(y []byte) ([]byte, error) {
- return yamlToJSON(y, nil)
-}
-
-func yamlToJSON(y []byte, jsonTarget *reflect.Value) ([]byte, error) {
- // Convert the YAML to an object.
- var yamlObj interface{}
- err := yaml.Unmarshal(y, &yamlObj)
- if err != nil {
- return nil, err
- }
-
- // YAML objects are not completely compatible with JSON objects (e.g. you
- // can have non-string keys in YAML). So, convert the YAML-compatible object
- // to a JSON-compatible object, failing with an error if irrecoverable
- // incompatibilties happen along the way.
- jsonObj, err := convertToJSONableObject(yamlObj, jsonTarget)
- if err != nil {
- return nil, err
- }
-
- // Convert this object to JSON and return the data.
- return json.Marshal(jsonObj)
-}
-
-func convertToJSONableObject(yamlObj interface{}, jsonTarget *reflect.Value) (interface{}, error) {
- var err error
-
- // Resolve jsonTarget to a concrete value (i.e. not a pointer or an
- // interface). We pass decodingNull as false because we're not actually
- // decoding into the value, we're just checking if the ultimate target is a
- // string.
- if jsonTarget != nil {
- ju, tu, pv := indirect(*jsonTarget, false)
- // We have a JSON or Text Umarshaler at this level, so we can't be trying
- // to decode into a string.
- if ju != nil || tu != nil {
- jsonTarget = nil
- } else {
- jsonTarget = &pv
- }
- }
-
- // If yamlObj is a number or a boolean, check if jsonTarget is a string -
- // if so, coerce. Else return normal.
- // If yamlObj is a map or array, find the field that each key is
- // unmarshaling to, and when you recurse pass the reflect.Value for that
- // field back into this function.
- switch typedYAMLObj := yamlObj.(type) {
- case map[interface{}]interface{}:
- // JSON does not support arbitrary keys in a map, so we must convert
- // these keys to strings.
- //
- // From my reading of go-yaml v2 (specifically the resolve function),
- // keys can only have the types string, int, int64, float64, binary
- // (unsupported), or null (unsupported).
- strMap := make(map[string]interface{})
- for k, v := range typedYAMLObj {
- // Resolve the key to a string first.
- var keyString string
- switch typedKey := k.(type) {
- case string:
- keyString = typedKey
- case int:
- keyString = strconv.Itoa(typedKey)
- case int64:
- // go-yaml will only return an int64 as a key if the system
- // architecture is 32-bit and the key's value is between 32-bit
- // and 64-bit. Otherwise the key type will simply be int.
- keyString = strconv.FormatInt(typedKey, 10)
- case float64:
- // Stolen from go-yaml to use the same conversion to string as
- // the go-yaml library uses to convert float to string when
- // Marshaling.
- s := strconv.FormatFloat(typedKey, 'g', -1, 32)
- switch s {
- case "+Inf":
- s = ".inf"
- case "-Inf":
- s = "-.inf"
- case "NaN":
- s = ".nan"
- }
- keyString = s
- case bool:
- if typedKey {
- keyString = "true"
- } else {
- keyString = "false"
- }
- default:
- return nil, fmt.Errorf("Unsupported map key of type: %s, key: %+#v, value: %+#v",
- reflect.TypeOf(k), k, v)
- }
-
- // jsonTarget should be a struct or a map. If it's a struct, find
- // the field it's going to map to and pass its reflect.Value. If
- // it's a map, find the element type of the map and pass the
- // reflect.Value created from that type. If it's neither, just pass
- // nil - JSON conversion will error for us if it's a real issue.
- if jsonTarget != nil {
- t := *jsonTarget
- if t.Kind() == reflect.Struct {
- keyBytes := []byte(keyString)
- // Find the field that the JSON library would use.
- var f *field
- fields := cachedTypeFields(t.Type())
- for i := range fields {
- ff := &fields[i]
- if bytes.Equal(ff.nameBytes, keyBytes) {
- f = ff
- break
- }
- // Do case-insensitive comparison.
- if f == nil && ff.equalFold(ff.nameBytes, keyBytes) {
- f = ff
- }
- }
- if f != nil {
- // Find the reflect.Value of the most preferential
- // struct field.
- jtf := t.Field(f.index[0])
- strMap[keyString], err = convertToJSONableObject(v, &jtf)
- if err != nil {
- return nil, err
- }
- continue
- }
- } else if t.Kind() == reflect.Map {
- // Create a zero value of the map's element type to use as
- // the JSON target.
- jtv := reflect.Zero(t.Type().Elem())
- strMap[keyString], err = convertToJSONableObject(v, &jtv)
- if err != nil {
- return nil, err
- }
- continue
- }
- }
- strMap[keyString], err = convertToJSONableObject(v, nil)
- if err != nil {
- return nil, err
- }
- }
- return strMap, nil
- case []interface{}:
- // We need to recurse into arrays in case there are any
- // map[interface{}]interface{}'s inside and to convert any
- // numbers to strings.
-
- // If jsonTarget is a slice (which it really should be), find the
- // thing it's going to map to. If it's not a slice, just pass nil
- // - JSON conversion will error for us if it's a real issue.
- var jsonSliceElemValue *reflect.Value
- if jsonTarget != nil {
- t := *jsonTarget
- if t.Kind() == reflect.Slice {
- // By default slices point to nil, but we need a reflect.Value
- // pointing to a value of the slice type, so we create one here.
- ev := reflect.Indirect(reflect.New(t.Type().Elem()))
- jsonSliceElemValue = &ev
- }
- }
-
- // Make and use a new array.
- arr := make([]interface{}, len(typedYAMLObj))
- for i, v := range typedYAMLObj {
- arr[i], err = convertToJSONableObject(v, jsonSliceElemValue)
- if err != nil {
- return nil, err
- }
- }
- return arr, nil
- default:
- // If the target type is a string and the YAML type is a number,
- // convert the YAML type to a string.
- if jsonTarget != nil && (*jsonTarget).Kind() == reflect.String {
- // Based on my reading of go-yaml, it may return int, int64,
- // float64, or uint64.
- var s string
- switch typedVal := typedYAMLObj.(type) {
- case int:
- s = strconv.FormatInt(int64(typedVal), 10)
- case int64:
- s = strconv.FormatInt(typedVal, 10)
- case float64:
- s = strconv.FormatFloat(typedVal, 'g', -1, 32)
- case uint64:
- s = strconv.FormatUint(typedVal, 10)
- case bool:
- if typedVal {
- s = "true"
- } else {
- s = "false"
- }
- }
- if len(s) > 0 {
- yamlObj = interface{}(s)
- }
- }
- return yamlObj, nil
- }
-
- return nil, nil
-}
diff --git a/vendor/github.com/golang/glog/LICENSE b/vendor/github.com/golang/glog/LICENSE
deleted file mode 100644
index 37ec93a..0000000
--- a/vendor/github.com/golang/glog/LICENSE
+++ /dev/null
@@ -1,191 +0,0 @@
-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:
-
-You must give any other recipients of the Work or Derivative Works a copy of
-this License; and
-You must cause any modified files to carry prominent notices stating that You
-changed the files; and
-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
-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.
diff --git a/vendor/github.com/golang/glog/README b/vendor/github.com/golang/glog/README
deleted file mode 100644
index 387b4eb..0000000
--- a/vendor/github.com/golang/glog/README
+++ /dev/null
@@ -1,44 +0,0 @@
-glog
-====
-
-Leveled execution logs for Go.
-
-This is an efficient pure Go implementation of leveled logs in the
-manner of the open source C++ package
- https://github.com/google/glog
-
-By binding methods to booleans it is possible to use the log package
-without paying the expense of evaluating the arguments to the log.
-Through the -vmodule flag, the package also provides fine-grained
-control over logging at the file level.
-
-The comment from glog.go introduces the ideas:
-
- Package glog implements logging analogous to the Google-internal
- C++ INFO/ERROR/V setup. It provides functions Info, Warning,
- Error, Fatal, plus formatting variants such as Infof. It
- also provides V-style logging controlled by the -v and
- -vmodule=file=2 flags.
-
- Basic examples:
-
- glog.Info("Prepare to repel boarders")
-
- glog.Fatalf("Initialization failed: %s", err)
-
- See the documentation for the V function for an explanation
- of these examples:
-
- if glog.V(2) {
- glog.Info("Starting transaction...")
- }
-
- glog.V(2).Infoln("Processed", nItems, "elements")
-
-
-The repository contains an open source version of the log package
-used inside Google. The master copy of the source lives inside
-Google, not here. The code in this repo is for export only and is not itself
-under development. Feature requests will be ignored.
-
-Send bug reports to golang-nuts@googlegroups.com.
diff --git a/vendor/github.com/golang/glog/glog.go b/vendor/github.com/golang/glog/glog.go
deleted file mode 100644
index 54bd7af..0000000
--- a/vendor/github.com/golang/glog/glog.go
+++ /dev/null
@@ -1,1180 +0,0 @@
-// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/
-//
-// Copyright 2013 Google Inc. All Rights Reserved.
-//
-// 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 glog implements logging analogous to the Google-internal C++ INFO/ERROR/V setup.
-// It provides functions Info, Warning, Error, Fatal, plus formatting variants such as
-// Infof. It also provides V-style logging controlled by the -v and -vmodule=file=2 flags.
-//
-// Basic examples:
-//
-// glog.Info("Prepare to repel boarders")
-//
-// glog.Fatalf("Initialization failed: %s", err)
-//
-// See the documentation for the V function for an explanation of these examples:
-//
-// if glog.V(2) {
-// glog.Info("Starting transaction...")
-// }
-//
-// glog.V(2).Infoln("Processed", nItems, "elements")
-//
-// Log output is buffered and written periodically using Flush. Programs
-// should call Flush before exiting to guarantee all log output is written.
-//
-// By default, all log statements write to files in a temporary directory.
-// This package provides several flags that modify this behavior.
-// As a result, flag.Parse must be called before any logging is done.
-//
-// -logtostderr=false
-// Logs are written to standard error instead of to files.
-// -alsologtostderr=false
-// Logs are written to standard error as well as to files.
-// -stderrthreshold=ERROR
-// Log events at or above this severity are logged to standard
-// error as well as to files.
-// -log_dir=""
-// Log files will be written to this directory instead of the
-// default temporary directory.
-//
-// Other flags provide aids to debugging.
-//
-// -log_backtrace_at=""
-// When set to a file and line number holding a logging statement,
-// such as
-// -log_backtrace_at=gopherflakes.go:234
-// a stack trace will be written to the Info log whenever execution
-// hits that statement. (Unlike with -vmodule, the ".go" must be
-// present.)
-// -v=0
-// Enable V-leveled logging at the specified level.
-// -vmodule=""
-// The syntax of the argument is a comma-separated list of pattern=N,
-// where pattern is a literal file name (minus the ".go" suffix) or
-// "glob" pattern and N is a V level. For instance,
-// -vmodule=gopher*=3
-// sets the V level to 3 in all Go files whose names begin "gopher".
-//
-package glog
-
-import (
- "bufio"
- "bytes"
- "errors"
- "flag"
- "fmt"
- "io"
- stdLog "log"
- "os"
- "path/filepath"
- "runtime"
- "strconv"
- "strings"
- "sync"
- "sync/atomic"
- "time"
-)
-
-// severity identifies the sort of log: info, warning etc. It also implements
-// the flag.Value interface. The -stderrthreshold flag is of type severity and
-// should be modified only through the flag.Value interface. The values match
-// the corresponding constants in C++.
-type severity int32 // sync/atomic int32
-
-// These constants identify the log levels in order of increasing severity.
-// A message written to a high-severity log file is also written to each
-// lower-severity log file.
-const (
- infoLog severity = iota
- warningLog
- errorLog
- fatalLog
- numSeverity = 4
-)
-
-const severityChar = "IWEF"
-
-var severityName = []string{
- infoLog: "INFO",
- warningLog: "WARNING",
- errorLog: "ERROR",
- fatalLog: "FATAL",
-}
-
-// get returns the value of the severity.
-func (s *severity) get() severity {
- return severity(atomic.LoadInt32((*int32)(s)))
-}
-
-// set sets the value of the severity.
-func (s *severity) set(val severity) {
- atomic.StoreInt32((*int32)(s), int32(val))
-}
-
-// String is part of the flag.Value interface.
-func (s *severity) String() string {
- return strconv.FormatInt(int64(*s), 10)
-}
-
-// Get is part of the flag.Value interface.
-func (s *severity) Get() interface{} {
- return *s
-}
-
-// Set is part of the flag.Value interface.
-func (s *severity) Set(value string) error {
- var threshold severity
- // Is it a known name?
- if v, ok := severityByName(value); ok {
- threshold = v
- } else {
- v, err := strconv.Atoi(value)
- if err != nil {
- return err
- }
- threshold = severity(v)
- }
- logging.stderrThreshold.set(threshold)
- return nil
-}
-
-func severityByName(s string) (severity, bool) {
- s = strings.ToUpper(s)
- for i, name := range severityName {
- if name == s {
- return severity(i), true
- }
- }
- return 0, false
-}
-
-// OutputStats tracks the number of output lines and bytes written.
-type OutputStats struct {
- lines int64
- bytes int64
-}
-
-// Lines returns the number of lines written.
-func (s *OutputStats) Lines() int64 {
- return atomic.LoadInt64(&s.lines)
-}
-
-// Bytes returns the number of bytes written.
-func (s *OutputStats) Bytes() int64 {
- return atomic.LoadInt64(&s.bytes)
-}
-
-// Stats tracks the number of lines of output and number of bytes
-// per severity level. Values must be read with atomic.LoadInt64.
-var Stats struct {
- Info, Warning, Error OutputStats
-}
-
-var severityStats = [numSeverity]*OutputStats{
- infoLog: &Stats.Info,
- warningLog: &Stats.Warning,
- errorLog: &Stats.Error,
-}
-
-// Level is exported because it appears in the arguments to V and is
-// the type of the v flag, which can be set programmatically.
-// It's a distinct type because we want to discriminate it from logType.
-// Variables of type level are only changed under logging.mu.
-// The -v flag is read only with atomic ops, so the state of the logging
-// module is consistent.
-
-// Level is treated as a sync/atomic int32.
-
-// Level specifies a level of verbosity for V logs. *Level implements
-// flag.Value; the -v flag is of type Level and should be modified
-// only through the flag.Value interface.
-type Level int32
-
-// get returns the value of the Level.
-func (l *Level) get() Level {
- return Level(atomic.LoadInt32((*int32)(l)))
-}
-
-// set sets the value of the Level.
-func (l *Level) set(val Level) {
- atomic.StoreInt32((*int32)(l), int32(val))
-}
-
-// String is part of the flag.Value interface.
-func (l *Level) String() string {
- return strconv.FormatInt(int64(*l), 10)
-}
-
-// Get is part of the flag.Value interface.
-func (l *Level) Get() interface{} {
- return *l
-}
-
-// Set is part of the flag.Value interface.
-func (l *Level) Set(value string) error {
- v, err := strconv.Atoi(value)
- if err != nil {
- return err
- }
- logging.mu.Lock()
- defer logging.mu.Unlock()
- logging.setVState(Level(v), logging.vmodule.filter, false)
- return nil
-}
-
-// moduleSpec represents the setting of the -vmodule flag.
-type moduleSpec struct {
- filter []modulePat
-}
-
-// modulePat contains a filter for the -vmodule flag.
-// It holds a verbosity level and a file pattern to match.
-type modulePat struct {
- pattern string
- literal bool // The pattern is a literal string
- level Level
-}
-
-// match reports whether the file matches the pattern. It uses a string
-// comparison if the pattern contains no metacharacters.
-func (m *modulePat) match(file string) bool {
- if m.literal {
- return file == m.pattern
- }
- match, _ := filepath.Match(m.pattern, file)
- return match
-}
-
-func (m *moduleSpec) String() string {
- // Lock because the type is not atomic. TODO: clean this up.
- logging.mu.Lock()
- defer logging.mu.Unlock()
- var b bytes.Buffer
- for i, f := range m.filter {
- if i > 0 {
- b.WriteRune(',')
- }
- fmt.Fprintf(&b, "%s=%d", f.pattern, f.level)
- }
- return b.String()
-}
-
-// Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the
-// struct is not exported.
-func (m *moduleSpec) Get() interface{} {
- return nil
-}
-
-var errVmoduleSyntax = errors.New("syntax error: expect comma-separated list of filename=N")
-
-// Syntax: -vmodule=recordio=2,file=1,gfs*=3
-func (m *moduleSpec) Set(value string) error {
- var filter []modulePat
- for _, pat := range strings.Split(value, ",") {
- if len(pat) == 0 {
- // Empty strings such as from a trailing comma can be ignored.
- continue
- }
- patLev := strings.Split(pat, "=")
- if len(patLev) != 2 || len(patLev[0]) == 0 || len(patLev[1]) == 0 {
- return errVmoduleSyntax
- }
- pattern := patLev[0]
- v, err := strconv.Atoi(patLev[1])
- if err != nil {
- return errors.New("syntax error: expect comma-separated list of filename=N")
- }
- if v < 0 {
- return errors.New("negative value for vmodule level")
- }
- if v == 0 {
- continue // Ignore. It's harmless but no point in paying the overhead.
- }
- // TODO: check syntax of filter?
- filter = append(filter, modulePat{pattern, isLiteral(pattern), Level(v)})
- }
- logging.mu.Lock()
- defer logging.mu.Unlock()
- logging.setVState(logging.verbosity, filter, true)
- return nil
-}
-
-// isLiteral reports whether the pattern is a literal string, that is, has no metacharacters
-// that require filepath.Match to be called to match the pattern.
-func isLiteral(pattern string) bool {
- return !strings.ContainsAny(pattern, `\*?[]`)
-}
-
-// traceLocation represents the setting of the -log_backtrace_at flag.
-type traceLocation struct {
- file string
- line int
-}
-
-// isSet reports whether the trace location has been specified.
-// logging.mu is held.
-func (t *traceLocation) isSet() bool {
- return t.line > 0
-}
-
-// match reports whether the specified file and line matches the trace location.
-// The argument file name is the full path, not the basename specified in the flag.
-// logging.mu is held.
-func (t *traceLocation) match(file string, line int) bool {
- if t.line != line {
- return false
- }
- if i := strings.LastIndex(file, "/"); i >= 0 {
- file = file[i+1:]
- }
- return t.file == file
-}
-
-func (t *traceLocation) String() string {
- // Lock because the type is not atomic. TODO: clean this up.
- logging.mu.Lock()
- defer logging.mu.Unlock()
- return fmt.Sprintf("%s:%d", t.file, t.line)
-}
-
-// Get is part of the (Go 1.2) flag.Getter interface. It always returns nil for this flag type since the
-// struct is not exported
-func (t *traceLocation) Get() interface{} {
- return nil
-}
-
-var errTraceSyntax = errors.New("syntax error: expect file.go:234")
-
-// Syntax: -log_backtrace_at=gopherflakes.go:234
-// Note that unlike vmodule the file extension is included here.
-func (t *traceLocation) Set(value string) error {
- if value == "" {
- // Unset.
- t.line = 0
- t.file = ""
- }
- fields := strings.Split(value, ":")
- if len(fields) != 2 {
- return errTraceSyntax
- }
- file, line := fields[0], fields[1]
- if !strings.Contains(file, ".") {
- return errTraceSyntax
- }
- v, err := strconv.Atoi(line)
- if err != nil {
- return errTraceSyntax
- }
- if v <= 0 {
- return errors.New("negative or zero value for level")
- }
- logging.mu.Lock()
- defer logging.mu.Unlock()
- t.line = v
- t.file = file
- return nil
-}
-
-// flushSyncWriter is the interface satisfied by logging destinations.
-type flushSyncWriter interface {
- Flush() error
- Sync() error
- io.Writer
-}
-
-func init() {
- flag.BoolVar(&logging.toStderr, "logtostderr", false, "log to standard error instead of files")
- flag.BoolVar(&logging.alsoToStderr, "alsologtostderr", false, "log to standard error as well as files")
- flag.Var(&logging.verbosity, "v", "log level for V logs")
- flag.Var(&logging.stderrThreshold, "stderrthreshold", "logs at or above this threshold go to stderr")
- flag.Var(&logging.vmodule, "vmodule", "comma-separated list of pattern=N settings for file-filtered logging")
- flag.Var(&logging.traceLocation, "log_backtrace_at", "when logging hits line file:N, emit a stack trace")
-
- // Default stderrThreshold is ERROR.
- logging.stderrThreshold = errorLog
-
- logging.setVState(0, nil, false)
- go logging.flushDaemon()
-}
-
-// Flush flushes all pending log I/O.
-func Flush() {
- logging.lockAndFlushAll()
-}
-
-// loggingT collects all the global state of the logging setup.
-type loggingT struct {
- // Boolean flags. Not handled atomically because the flag.Value interface
- // does not let us avoid the =true, and that shorthand is necessary for
- // compatibility. TODO: does this matter enough to fix? Seems unlikely.
- toStderr bool // The -logtostderr flag.
- alsoToStderr bool // The -alsologtostderr flag.
-
- // Level flag. Handled atomically.
- stderrThreshold severity // The -stderrthreshold flag.
-
- // freeList is a list of byte buffers, maintained under freeListMu.
- freeList *buffer
- // freeListMu maintains the free list. It is separate from the main mutex
- // so buffers can be grabbed and printed to without holding the main lock,
- // for better parallelization.
- freeListMu sync.Mutex
-
- // mu protects the remaining elements of this structure and is
- // used to synchronize logging.
- mu sync.Mutex
- // file holds writer for each of the log types.
- file [numSeverity]flushSyncWriter
- // pcs is used in V to avoid an allocation when computing the caller's PC.
- pcs [1]uintptr
- // vmap is a cache of the V Level for each V() call site, identified by PC.
- // It is wiped whenever the vmodule flag changes state.
- vmap map[uintptr]Level
- // filterLength stores the length of the vmodule filter chain. If greater
- // than zero, it means vmodule is enabled. It may be read safely
- // using sync.LoadInt32, but is only modified under mu.
- filterLength int32
- // traceLocation is the state of the -log_backtrace_at flag.
- traceLocation traceLocation
- // These flags are modified only under lock, although verbosity may be fetched
- // safely using atomic.LoadInt32.
- vmodule moduleSpec // The state of the -vmodule flag.
- verbosity Level // V logging level, the value of the -v flag/
-}
-
-// buffer holds a byte Buffer for reuse. The zero value is ready for use.
-type buffer struct {
- bytes.Buffer
- tmp [64]byte // temporary byte array for creating headers.
- next *buffer
-}
-
-var logging loggingT
-
-// setVState sets a consistent state for V logging.
-// l.mu is held.
-func (l *loggingT) setVState(verbosity Level, filter []modulePat, setFilter bool) {
- // Turn verbosity off so V will not fire while we are in transition.
- logging.verbosity.set(0)
- // Ditto for filter length.
- atomic.StoreInt32(&logging.filterLength, 0)
-
- // Set the new filters and wipe the pc->Level map if the filter has changed.
- if setFilter {
- logging.vmodule.filter = filter
- logging.vmap = make(map[uintptr]Level)
- }
-
- // Things are consistent now, so enable filtering and verbosity.
- // They are enabled in order opposite to that in V.
- atomic.StoreInt32(&logging.filterLength, int32(len(filter)))
- logging.verbosity.set(verbosity)
-}
-
-// getBuffer returns a new, ready-to-use buffer.
-func (l *loggingT) getBuffer() *buffer {
- l.freeListMu.Lock()
- b := l.freeList
- if b != nil {
- l.freeList = b.next
- }
- l.freeListMu.Unlock()
- if b == nil {
- b = new(buffer)
- } else {
- b.next = nil
- b.Reset()
- }
- return b
-}
-
-// putBuffer returns a buffer to the free list.
-func (l *loggingT) putBuffer(b *buffer) {
- if b.Len() >= 256 {
- // Let big buffers die a natural death.
- return
- }
- l.freeListMu.Lock()
- b.next = l.freeList
- l.freeList = b
- l.freeListMu.Unlock()
-}
-
-var timeNow = time.Now // Stubbed out for testing.
-
-/*
-header formats a log header as defined by the C++ implementation.
-It returns a buffer containing the formatted header and the user's file and line number.
-The depth specifies how many stack frames above lives the source line to be identified in the log message.
-
-Log lines have this form:
- Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg...
-where the fields are defined as follows:
- L A single character, representing the log level (eg 'I' for INFO)
- mm The month (zero padded; ie May is '05')
- dd The day (zero padded)
- hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds
- threadid The space-padded thread ID as returned by GetTID()
- file The file name
- line The line number
- msg The user-supplied message
-*/
-func (l *loggingT) header(s severity, depth int) (*buffer, string, int) {
- _, file, line, ok := runtime.Caller(3 + depth)
- if !ok {
- file = "???"
- line = 1
- } else {
- slash := strings.LastIndex(file, "/")
- if slash >= 0 {
- file = file[slash+1:]
- }
- }
- return l.formatHeader(s, file, line), file, line
-}
-
-// formatHeader formats a log header using the provided file name and line number.
-func (l *loggingT) formatHeader(s severity, file string, line int) *buffer {
- now := timeNow()
- if line < 0 {
- line = 0 // not a real line number, but acceptable to someDigits
- }
- if s > fatalLog {
- s = infoLog // for safety.
- }
- buf := l.getBuffer()
-
- // Avoid Fprintf, for speed. The format is so simple that we can do it quickly by hand.
- // It's worth about 3X. Fprintf is hard.
- _, month, day := now.Date()
- hour, minute, second := now.Clock()
- // Lmmdd hh:mm:ss.uuuuuu threadid file:line]
- buf.tmp[0] = severityChar[s]
- buf.twoDigits(1, int(month))
- buf.twoDigits(3, day)
- buf.tmp[5] = ' '
- buf.twoDigits(6, hour)
- buf.tmp[8] = ':'
- buf.twoDigits(9, minute)
- buf.tmp[11] = ':'
- buf.twoDigits(12, second)
- buf.tmp[14] = '.'
- buf.nDigits(6, 15, now.Nanosecond()/1000, '0')
- buf.tmp[21] = ' '
- buf.nDigits(7, 22, pid, ' ') // TODO: should be TID
- buf.tmp[29] = ' '
- buf.Write(buf.tmp[:30])
- buf.WriteString(file)
- buf.tmp[0] = ':'
- n := buf.someDigits(1, line)
- buf.tmp[n+1] = ']'
- buf.tmp[n+2] = ' '
- buf.Write(buf.tmp[:n+3])
- return buf
-}
-
-// Some custom tiny helper functions to print the log header efficiently.
-
-const digits = "0123456789"
-
-// twoDigits formats a zero-prefixed two-digit integer at buf.tmp[i].
-func (buf *buffer) twoDigits(i, d int) {
- buf.tmp[i+1] = digits[d%10]
- d /= 10
- buf.tmp[i] = digits[d%10]
-}
-
-// nDigits formats an n-digit integer at buf.tmp[i],
-// padding with pad on the left.
-// It assumes d >= 0.
-func (buf *buffer) nDigits(n, i, d int, pad byte) {
- j := n - 1
- for ; j >= 0 && d > 0; j-- {
- buf.tmp[i+j] = digits[d%10]
- d /= 10
- }
- for ; j >= 0; j-- {
- buf.tmp[i+j] = pad
- }
-}
-
-// someDigits formats a zero-prefixed variable-width integer at buf.tmp[i].
-func (buf *buffer) someDigits(i, d int) int {
- // Print into the top, then copy down. We know there's space for at least
- // a 10-digit number.
- j := len(buf.tmp)
- for {
- j--
- buf.tmp[j] = digits[d%10]
- d /= 10
- if d == 0 {
- break
- }
- }
- return copy(buf.tmp[i:], buf.tmp[j:])
-}
-
-func (l *loggingT) println(s severity, args ...interface{}) {
- buf, file, line := l.header(s, 0)
- fmt.Fprintln(buf, args...)
- l.output(s, buf, file, line, false)
-}
-
-func (l *loggingT) print(s severity, args ...interface{}) {
- l.printDepth(s, 1, args...)
-}
-
-func (l *loggingT) printDepth(s severity, depth int, args ...interface{}) {
- buf, file, line := l.header(s, depth)
- fmt.Fprint(buf, args...)
- if buf.Bytes()[buf.Len()-1] != '\n' {
- buf.WriteByte('\n')
- }
- l.output(s, buf, file, line, false)
-}
-
-func (l *loggingT) printf(s severity, format string, args ...interface{}) {
- buf, file, line := l.header(s, 0)
- fmt.Fprintf(buf, format, args...)
- if buf.Bytes()[buf.Len()-1] != '\n' {
- buf.WriteByte('\n')
- }
- l.output(s, buf, file, line, false)
-}
-
-// printWithFileLine behaves like print but uses the provided file and line number. If
-// alsoLogToStderr is true, the log message always appears on standard error; it
-// will also appear in the log file unless --logtostderr is set.
-func (l *loggingT) printWithFileLine(s severity, file string, line int, alsoToStderr bool, args ...interface{}) {
- buf := l.formatHeader(s, file, line)
- fmt.Fprint(buf, args...)
- if buf.Bytes()[buf.Len()-1] != '\n' {
- buf.WriteByte('\n')
- }
- l.output(s, buf, file, line, alsoToStderr)
-}
-
-// output writes the data to the log files and releases the buffer.
-func (l *loggingT) output(s severity, buf *buffer, file string, line int, alsoToStderr bool) {
- l.mu.Lock()
- if l.traceLocation.isSet() {
- if l.traceLocation.match(file, line) {
- buf.Write(stacks(false))
- }
- }
- data := buf.Bytes()
- if !flag.Parsed() {
- os.Stderr.Write([]byte("ERROR: logging before flag.Parse: "))
- os.Stderr.Write(data)
- } else if l.toStderr {
- os.Stderr.Write(data)
- } else {
- if alsoToStderr || l.alsoToStderr || s >= l.stderrThreshold.get() {
- os.Stderr.Write(data)
- }
- if l.file[s] == nil {
- if err := l.createFiles(s); err != nil {
- os.Stderr.Write(data) // Make sure the message appears somewhere.
- l.exit(err)
- }
- }
- switch s {
- case fatalLog:
- l.file[fatalLog].Write(data)
- fallthrough
- case errorLog:
- l.file[errorLog].Write(data)
- fallthrough
- case warningLog:
- l.file[warningLog].Write(data)
- fallthrough
- case infoLog:
- l.file[infoLog].Write(data)
- }
- }
- if s == fatalLog {
- // If we got here via Exit rather than Fatal, print no stacks.
- if atomic.LoadUint32(&fatalNoStacks) > 0 {
- l.mu.Unlock()
- timeoutFlush(10 * time.Second)
- os.Exit(1)
- }
- // Dump all goroutine stacks before exiting.
- // First, make sure we see the trace for the current goroutine on standard error.
- // If -logtostderr has been specified, the loop below will do that anyway
- // as the first stack in the full dump.
- if !l.toStderr {
- os.Stderr.Write(stacks(false))
- }
- // Write the stack trace for all goroutines to the files.
- trace := stacks(true)
- logExitFunc = func(error) {} // If we get a write error, we'll still exit below.
- for log := fatalLog; log >= infoLog; log-- {
- if f := l.file[log]; f != nil { // Can be nil if -logtostderr is set.
- f.Write(trace)
- }
- }
- l.mu.Unlock()
- timeoutFlush(10 * time.Second)
- os.Exit(255) // C++ uses -1, which is silly because it's anded with 255 anyway.
- }
- l.putBuffer(buf)
- l.mu.Unlock()
- if stats := severityStats[s]; stats != nil {
- atomic.AddInt64(&stats.lines, 1)
- atomic.AddInt64(&stats.bytes, int64(len(data)))
- }
-}
-
-// timeoutFlush calls Flush and returns when it completes or after timeout
-// elapses, whichever happens first. This is needed because the hooks invoked
-// by Flush may deadlock when glog.Fatal is called from a hook that holds
-// a lock.
-func timeoutFlush(timeout time.Duration) {
- done := make(chan bool, 1)
- go func() {
- Flush() // calls logging.lockAndFlushAll()
- done <- true
- }()
- select {
- case <-done:
- case <-time.After(timeout):
- fmt.Fprintln(os.Stderr, "glog: Flush took longer than", timeout)
- }
-}
-
-// stacks is a wrapper for runtime.Stack that attempts to recover the data for all goroutines.
-func stacks(all bool) []byte {
- // We don't know how big the traces are, so grow a few times if they don't fit. Start large, though.
- n := 10000
- if all {
- n = 100000
- }
- var trace []byte
- for i := 0; i < 5; i++ {
- trace = make([]byte, n)
- nbytes := runtime.Stack(trace, all)
- if nbytes < len(trace) {
- return trace[:nbytes]
- }
- n *= 2
- }
- return trace
-}
-
-// logExitFunc provides a simple mechanism to override the default behavior
-// of exiting on error. Used in testing and to guarantee we reach a required exit
-// for fatal logs. Instead, exit could be a function rather than a method but that
-// would make its use clumsier.
-var logExitFunc func(error)
-
-// exit is called if there is trouble creating or writing log files.
-// It flushes the logs and exits the program; there's no point in hanging around.
-// l.mu is held.
-func (l *loggingT) exit(err error) {
- fmt.Fprintf(os.Stderr, "log: exiting because of error: %s\n", err)
- // If logExitFunc is set, we do that instead of exiting.
- if logExitFunc != nil {
- logExitFunc(err)
- return
- }
- l.flushAll()
- os.Exit(2)
-}
-
-// syncBuffer joins a bufio.Writer to its underlying file, providing access to the
-// file's Sync method and providing a wrapper for the Write method that provides log
-// file rotation. There are conflicting methods, so the file cannot be embedded.
-// l.mu is held for all its methods.
-type syncBuffer struct {
- logger *loggingT
- *bufio.Writer
- file *os.File
- sev severity
- nbytes uint64 // The number of bytes written to this file
-}
-
-func (sb *syncBuffer) Sync() error {
- return sb.file.Sync()
-}
-
-func (sb *syncBuffer) Write(p []byte) (n int, err error) {
- if sb.nbytes+uint64(len(p)) >= MaxSize {
- if err := sb.rotateFile(time.Now()); err != nil {
- sb.logger.exit(err)
- }
- }
- n, err = sb.Writer.Write(p)
- sb.nbytes += uint64(n)
- if err != nil {
- sb.logger.exit(err)
- }
- return
-}
-
-// rotateFile closes the syncBuffer's file and starts a new one.
-func (sb *syncBuffer) rotateFile(now time.Time) error {
- if sb.file != nil {
- sb.Flush()
- sb.file.Close()
- }
- var err error
- sb.file, _, err = create(severityName[sb.sev], now)
- sb.nbytes = 0
- if err != nil {
- return err
- }
-
- sb.Writer = bufio.NewWriterSize(sb.file, bufferSize)
-
- // Write header.
- var buf bytes.Buffer
- fmt.Fprintf(&buf, "Log file created at: %s\n", now.Format("2006/01/02 15:04:05"))
- fmt.Fprintf(&buf, "Running on machine: %s\n", host)
- fmt.Fprintf(&buf, "Binary: Built with %s %s for %s/%s\n", runtime.Compiler, runtime.Version(), runtime.GOOS, runtime.GOARCH)
- fmt.Fprintf(&buf, "Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg\n")
- n, err := sb.file.Write(buf.Bytes())
- sb.nbytes += uint64(n)
- return err
-}
-
-// bufferSize sizes the buffer associated with each log file. It's large
-// so that log records can accumulate without the logging thread blocking
-// on disk I/O. The flushDaemon will block instead.
-const bufferSize = 256 * 1024
-
-// createFiles creates all the log files for severity from sev down to infoLog.
-// l.mu is held.
-func (l *loggingT) createFiles(sev severity) error {
- now := time.Now()
- // Files are created in decreasing severity order, so as soon as we find one
- // has already been created, we can stop.
- for s := sev; s >= infoLog && l.file[s] == nil; s-- {
- sb := &syncBuffer{
- logger: l,
- sev: s,
- }
- if err := sb.rotateFile(now); err != nil {
- return err
- }
- l.file[s] = sb
- }
- return nil
-}
-
-const flushInterval = 30 * time.Second
-
-// flushDaemon periodically flushes the log file buffers.
-func (l *loggingT) flushDaemon() {
- for _ = range time.NewTicker(flushInterval).C {
- l.lockAndFlushAll()
- }
-}
-
-// lockAndFlushAll is like flushAll but locks l.mu first.
-func (l *loggingT) lockAndFlushAll() {
- l.mu.Lock()
- l.flushAll()
- l.mu.Unlock()
-}
-
-// flushAll flushes all the logs and attempts to "sync" their data to disk.
-// l.mu is held.
-func (l *loggingT) flushAll() {
- // Flush from fatal down, in case there's trouble flushing.
- for s := fatalLog; s >= infoLog; s-- {
- file := l.file[s]
- if file != nil {
- file.Flush() // ignore error
- file.Sync() // ignore error
- }
- }
-}
-
-// CopyStandardLogTo arranges for messages written to the Go "log" package's
-// default logs to also appear in the Google logs for the named and lower
-// severities. Subsequent changes to the standard log's default output location
-// or format may break this behavior.
-//
-// Valid names are "INFO", "WARNING", "ERROR", and "FATAL". If the name is not
-// recognized, CopyStandardLogTo panics.
-func CopyStandardLogTo(name string) {
- sev, ok := severityByName(name)
- if !ok {
- panic(fmt.Sprintf("log.CopyStandardLogTo(%q): unrecognized severity name", name))
- }
- // Set a log format that captures the user's file and line:
- // d.go:23: message
- stdLog.SetFlags(stdLog.Lshortfile)
- stdLog.SetOutput(logBridge(sev))
-}
-
-// logBridge provides the Write method that enables CopyStandardLogTo to connect
-// Go's standard logs to the logs provided by this package.
-type logBridge severity
-
-// Write parses the standard logging line and passes its components to the
-// logger for severity(lb).
-func (lb logBridge) Write(b []byte) (n int, err error) {
- var (
- file = "???"
- line = 1
- text string
- )
- // Split "d.go:23: message" into "d.go", "23", and "message".
- if parts := bytes.SplitN(b, []byte{':'}, 3); len(parts) != 3 || len(parts[0]) < 1 || len(parts[2]) < 1 {
- text = fmt.Sprintf("bad log format: %s", b)
- } else {
- file = string(parts[0])
- text = string(parts[2][1:]) // skip leading space
- line, err = strconv.Atoi(string(parts[1]))
- if err != nil {
- text = fmt.Sprintf("bad line number: %s", b)
- line = 1
- }
- }
- // printWithFileLine with alsoToStderr=true, so standard log messages
- // always appear on standard error.
- logging.printWithFileLine(severity(lb), file, line, true, text)
- return len(b), nil
-}
-
-// setV computes and remembers the V level for a given PC
-// when vmodule is enabled.
-// File pattern matching takes the basename of the file, stripped
-// of its .go suffix, and uses filepath.Match, which is a little more
-// general than the *? matching used in C++.
-// l.mu is held.
-func (l *loggingT) setV(pc uintptr) Level {
- fn := runtime.FuncForPC(pc)
- file, _ := fn.FileLine(pc)
- // The file is something like /a/b/c/d.go. We want just the d.
- if strings.HasSuffix(file, ".go") {
- file = file[:len(file)-3]
- }
- if slash := strings.LastIndex(file, "/"); slash >= 0 {
- file = file[slash+1:]
- }
- for _, filter := range l.vmodule.filter {
- if filter.match(file) {
- l.vmap[pc] = filter.level
- return filter.level
- }
- }
- l.vmap[pc] = 0
- return 0
-}
-
-// Verbose is a boolean type that implements Infof (like Printf) etc.
-// See the documentation of V for more information.
-type Verbose bool
-
-// V reports whether verbosity at the call site is at least the requested level.
-// The returned value is a boolean of type Verbose, which implements Info, Infoln
-// and Infof. These methods will write to the Info log if called.
-// Thus, one may write either
-// if glog.V(2) { glog.Info("log this") }
-// or
-// glog.V(2).Info("log this")
-// The second form is shorter but the first is cheaper if logging is off because it does
-// not evaluate its arguments.
-//
-// Whether an individual call to V generates a log record depends on the setting of
-// the -v and --vmodule flags; both are off by default. If the level in the call to
-// V is at least the value of -v, or of -vmodule for the source file containing the
-// call, the V call will log.
-func V(level Level) Verbose {
- // This function tries hard to be cheap unless there's work to do.
- // The fast path is two atomic loads and compares.
-
- // Here is a cheap but safe test to see if V logging is enabled globally.
- if logging.verbosity.get() >= level {
- return Verbose(true)
- }
-
- // It's off globally but it vmodule may still be set.
- // Here is another cheap but safe test to see if vmodule is enabled.
- if atomic.LoadInt32(&logging.filterLength) > 0 {
- // Now we need a proper lock to use the logging structure. The pcs field
- // is shared so we must lock before accessing it. This is fairly expensive,
- // but if V logging is enabled we're slow anyway.
- logging.mu.Lock()
- defer logging.mu.Unlock()
- if runtime.Callers(2, logging.pcs[:]) == 0 {
- return Verbose(false)
- }
- v, ok := logging.vmap[logging.pcs[0]]
- if !ok {
- v = logging.setV(logging.pcs[0])
- }
- return Verbose(v >= level)
- }
- return Verbose(false)
-}
-
-// Info is equivalent to the global Info function, guarded by the value of v.
-// See the documentation of V for usage.
-func (v Verbose) Info(args ...interface{}) {
- if v {
- logging.print(infoLog, args...)
- }
-}
-
-// Infoln is equivalent to the global Infoln function, guarded by the value of v.
-// See the documentation of V for usage.
-func (v Verbose) Infoln(args ...interface{}) {
- if v {
- logging.println(infoLog, args...)
- }
-}
-
-// Infof is equivalent to the global Infof function, guarded by the value of v.
-// See the documentation of V for usage.
-func (v Verbose) Infof(format string, args ...interface{}) {
- if v {
- logging.printf(infoLog, format, args...)
- }
-}
-
-// Info logs to the INFO log.
-// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
-func Info(args ...interface{}) {
- logging.print(infoLog, args...)
-}
-
-// InfoDepth acts as Info but uses depth to determine which call frame to log.
-// InfoDepth(0, "msg") is the same as Info("msg").
-func InfoDepth(depth int, args ...interface{}) {
- logging.printDepth(infoLog, depth, args...)
-}
-
-// Infoln logs to the INFO log.
-// Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
-func Infoln(args ...interface{}) {
- logging.println(infoLog, args...)
-}
-
-// Infof logs to the INFO log.
-// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
-func Infof(format string, args ...interface{}) {
- logging.printf(infoLog, format, args...)
-}
-
-// Warning logs to the WARNING and INFO logs.
-// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
-func Warning(args ...interface{}) {
- logging.print(warningLog, args...)
-}
-
-// WarningDepth acts as Warning but uses depth to determine which call frame to log.
-// WarningDepth(0, "msg") is the same as Warning("msg").
-func WarningDepth(depth int, args ...interface{}) {
- logging.printDepth(warningLog, depth, args...)
-}
-
-// Warningln logs to the WARNING and INFO logs.
-// Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
-func Warningln(args ...interface{}) {
- logging.println(warningLog, args...)
-}
-
-// Warningf logs to the WARNING and INFO logs.
-// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
-func Warningf(format string, args ...interface{}) {
- logging.printf(warningLog, format, args...)
-}
-
-// Error logs to the ERROR, WARNING, and INFO logs.
-// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
-func Error(args ...interface{}) {
- logging.print(errorLog, args...)
-}
-
-// ErrorDepth acts as Error but uses depth to determine which call frame to log.
-// ErrorDepth(0, "msg") is the same as Error("msg").
-func ErrorDepth(depth int, args ...interface{}) {
- logging.printDepth(errorLog, depth, args...)
-}
-
-// Errorln logs to the ERROR, WARNING, and INFO logs.
-// Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
-func Errorln(args ...interface{}) {
- logging.println(errorLog, args...)
-}
-
-// Errorf logs to the ERROR, WARNING, and INFO logs.
-// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
-func Errorf(format string, args ...interface{}) {
- logging.printf(errorLog, format, args...)
-}
-
-// Fatal logs to the FATAL, ERROR, WARNING, and INFO logs,
-// including a stack trace of all running goroutines, then calls os.Exit(255).
-// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
-func Fatal(args ...interface{}) {
- logging.print(fatalLog, args...)
-}
-
-// FatalDepth acts as Fatal but uses depth to determine which call frame to log.
-// FatalDepth(0, "msg") is the same as Fatal("msg").
-func FatalDepth(depth int, args ...interface{}) {
- logging.printDepth(fatalLog, depth, args...)
-}
-
-// Fatalln logs to the FATAL, ERROR, WARNING, and INFO logs,
-// including a stack trace of all running goroutines, then calls os.Exit(255).
-// Arguments are handled in the manner of fmt.Println; a newline is appended if missing.
-func Fatalln(args ...interface{}) {
- logging.println(fatalLog, args...)
-}
-
-// Fatalf logs to the FATAL, ERROR, WARNING, and INFO logs,
-// including a stack trace of all running goroutines, then calls os.Exit(255).
-// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
-func Fatalf(format string, args ...interface{}) {
- logging.printf(fatalLog, format, args...)
-}
-
-// fatalNoStacks is non-zero if we are to exit without dumping goroutine stacks.
-// It allows Exit and relatives to use the Fatal logs.
-var fatalNoStacks uint32
-
-// Exit logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
-// Arguments are handled in the manner of fmt.Print; a newline is appended if missing.
-func Exit(args ...interface{}) {
- atomic.StoreUint32(&fatalNoStacks, 1)
- logging.print(fatalLog, args...)
-}
-
-// ExitDepth acts as Exit but uses depth to determine which call frame to log.
-// ExitDepth(0, "msg") is the same as Exit("msg").
-func ExitDepth(depth int, args ...interface{}) {
- atomic.StoreUint32(&fatalNoStacks, 1)
- logging.printDepth(fatalLog, depth, args...)
-}
-
-// Exitln logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
-func Exitln(args ...interface{}) {
- atomic.StoreUint32(&fatalNoStacks, 1)
- logging.println(fatalLog, args...)
-}
-
-// Exitf logs to the FATAL, ERROR, WARNING, and INFO logs, then calls os.Exit(1).
-// Arguments are handled in the manner of fmt.Printf; a newline is appended if missing.
-func Exitf(format string, args ...interface{}) {
- atomic.StoreUint32(&fatalNoStacks, 1)
- logging.printf(fatalLog, format, args...)
-}
diff --git a/vendor/github.com/golang/glog/glog_file.go b/vendor/github.com/golang/glog/glog_file.go
deleted file mode 100644
index 65075d2..0000000
--- a/vendor/github.com/golang/glog/glog_file.go
+++ /dev/null
@@ -1,124 +0,0 @@
-// Go support for leveled logs, analogous to https://code.google.com/p/google-glog/
-//
-// Copyright 2013 Google Inc. All Rights Reserved.
-//
-// 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.
-
-// File I/O for logs.
-
-package glog
-
-import (
- "errors"
- "flag"
- "fmt"
- "os"
- "os/user"
- "path/filepath"
- "strings"
- "sync"
- "time"
-)
-
-// MaxSize is the maximum size of a log file in bytes.
-var MaxSize uint64 = 1024 * 1024 * 1800
-
-// logDirs lists the candidate directories for new log files.
-var logDirs []string
-
-// If non-empty, overrides the choice of directory in which to write logs.
-// See createLogDirs for the full list of possible destinations.
-var logDir = flag.String("log_dir", "", "If non-empty, write log files in this directory")
-
-func createLogDirs() {
- if *logDir != "" {
- logDirs = append(logDirs, *logDir)
- }
- logDirs = append(logDirs, os.TempDir())
-}
-
-var (
- pid = os.Getpid()
- program = filepath.Base(os.Args[0])
- host = "unknownhost"
- userName = "unknownuser"
-)
-
-func init() {
- h, err := os.Hostname()
- if err == nil {
- host = shortHostname(h)
- }
-
- current, err := user.Current()
- if err == nil {
- userName = current.Username
- }
-
- // Sanitize userName since it may contain filepath separators on Windows.
- userName = strings.Replace(userName, `\`, "_", -1)
-}
-
-// shortHostname returns its argument, truncating at the first period.
-// For instance, given "www.google.com" it returns "www".
-func shortHostname(hostname string) string {
- if i := strings.Index(hostname, "."); i >= 0 {
- return hostname[:i]
- }
- return hostname
-}
-
-// logName returns a new log file name containing tag, with start time t, and
-// the name for the symlink for tag.
-func logName(tag string, t time.Time) (name, link string) {
- name = fmt.Sprintf("%s.%s.%s.log.%s.%04d%02d%02d-%02d%02d%02d.%d",
- program,
- host,
- userName,
- tag,
- t.Year(),
- t.Month(),
- t.Day(),
- t.Hour(),
- t.Minute(),
- t.Second(),
- pid)
- return name, program + "." + tag
-}
-
-var onceLogDirs sync.Once
-
-// create creates a new log file and returns the file and its filename, which
-// contains tag ("INFO", "FATAL", etc.) and t. If the file is created
-// successfully, create also attempts to update the symlink for that tag, ignoring
-// errors.
-func create(tag string, t time.Time) (f *os.File, filename string, err error) {
- onceLogDirs.Do(createLogDirs)
- if len(logDirs) == 0 {
- return nil, "", errors.New("log: no log dirs")
- }
- name, link := logName(tag, t)
- var lastErr error
- for _, dir := range logDirs {
- fname := filepath.Join(dir, name)
- f, err := os.Create(fname)
- if err == nil {
- symlink := filepath.Join(dir, link)
- os.Remove(symlink) // ignore err
- os.Symlink(name, symlink) // ignore err
- return f, fname, nil
- }
- lastErr = err
- }
- return nil, "", fmt.Errorf("log: cannot create log: %v", lastErr)
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/doc.go b/vendor/github.com/golang/protobuf/protoc-gen-go/doc.go
deleted file mode 100644
index 0d6055d..0000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/doc.go
+++ /dev/null
@@ -1,51 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-/*
- A plugin for the Google protocol buffer compiler to generate Go code.
- Run it by building this program and putting it in your path with the name
- protoc-gen-go
- That word 'go' at the end becomes part of the option string set for the
- protocol compiler, so once the protocol compiler (protoc) is installed
- you can run
- protoc --go_out=output_directory input_directory/file.proto
- to generate Go bindings for the protocol defined by file.proto.
- With that input, the output will be written to
- output_directory/file.pb.go
-
- The generated code is documented in the package comment for
- the library.
-
- See the README and documentation for protocol buffers to learn more:
- https://developers.google.com/protocol-buffers/
-
-*/
-package documentation
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/generator/generator.go b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/generator.go
deleted file mode 100644
index 6f4a902..0000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/generator/generator.go
+++ /dev/null
@@ -1,2806 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-/*
- The code generator for the plugin for the Google protocol buffer compiler.
- It generates Go code from the protocol buffer description files read by the
- main routine.
-*/
-package generator
-
-import (
- "bufio"
- "bytes"
- "compress/gzip"
- "crypto/sha256"
- "encoding/hex"
- "fmt"
- "go/ast"
- "go/build"
- "go/parser"
- "go/printer"
- "go/token"
- "log"
- "os"
- "path"
- "sort"
- "strconv"
- "strings"
- "unicode"
- "unicode/utf8"
-
- "github.com/golang/protobuf/proto"
- "github.com/golang/protobuf/protoc-gen-go/generator/internal/remap"
-
- "github.com/golang/protobuf/protoc-gen-go/descriptor"
- plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
-)
-
-// generatedCodeVersion indicates a version of the generated code.
-// It is incremented whenever an incompatibility between the generated code and
-// proto package is introduced; the generated code references
-// a constant, proto.ProtoPackageIsVersionN (where N is generatedCodeVersion).
-const generatedCodeVersion = 3
-
-// A Plugin provides functionality to add to the output during Go code generation,
-// such as to produce RPC stubs.
-type Plugin interface {
- // Name identifies the plugin.
- Name() string
- // Init is called once after data structures are built but before
- // code generation begins.
- Init(g *Generator)
- // Generate produces the code generated by the plugin for this file,
- // except for the imports, by calling the generator's methods P, In, and Out.
- Generate(file *FileDescriptor)
- // GenerateImports produces the import declarations for this file.
- // It is called after Generate.
- GenerateImports(file *FileDescriptor)
-}
-
-var plugins []Plugin
-
-// RegisterPlugin installs a (second-order) plugin to be run when the Go output is generated.
-// It is typically called during initialization.
-func RegisterPlugin(p Plugin) {
- plugins = append(plugins, p)
-}
-
-// A GoImportPath is the import path of a Go package. e.g., "google.golang.org/genproto/protobuf".
-type GoImportPath string
-
-func (p GoImportPath) String() string { return strconv.Quote(string(p)) }
-
-// A GoPackageName is the name of a Go package. e.g., "protobuf".
-type GoPackageName string
-
-// Each type we import as a protocol buffer (other than FileDescriptorProto) needs
-// a pointer to the FileDescriptorProto that represents it. These types achieve that
-// wrapping by placing each Proto inside a struct with the pointer to its File. The
-// structs have the same names as their contents, with "Proto" removed.
-// FileDescriptor is used to store the things that it points to.
-
-// The file and package name method are common to messages and enums.
-type common struct {
- file *FileDescriptor // File this object comes from.
-}
-
-// GoImportPath is the import path of the Go package containing the type.
-func (c *common) GoImportPath() GoImportPath {
- return c.file.importPath
-}
-
-func (c *common) File() *FileDescriptor { return c.file }
-
-func fileIsProto3(file *descriptor.FileDescriptorProto) bool {
- return file.GetSyntax() == "proto3"
-}
-
-func (c *common) proto3() bool { return fileIsProto3(c.file.FileDescriptorProto) }
-
-// Descriptor represents a protocol buffer message.
-type Descriptor struct {
- common
- *descriptor.DescriptorProto
- parent *Descriptor // The containing message, if any.
- nested []*Descriptor // Inner messages, if any.
- enums []*EnumDescriptor // Inner enums, if any.
- ext []*ExtensionDescriptor // Extensions, if any.
- typename []string // Cached typename vector.
- index int // The index into the container, whether the file or another message.
- path string // The SourceCodeInfo path as comma-separated integers.
- group bool
-}
-
-// TypeName returns the elements of the dotted type name.
-// The package name is not part of this name.
-func (d *Descriptor) TypeName() []string {
- if d.typename != nil {
- return d.typename
- }
- n := 0
- for parent := d; parent != nil; parent = parent.parent {
- n++
- }
- s := make([]string, n)
- for parent := d; parent != nil; parent = parent.parent {
- n--
- s[n] = parent.GetName()
- }
- d.typename = s
- return s
-}
-
-// EnumDescriptor describes an enum. If it's at top level, its parent will be nil.
-// Otherwise it will be the descriptor of the message in which it is defined.
-type EnumDescriptor struct {
- common
- *descriptor.EnumDescriptorProto
- parent *Descriptor // The containing message, if any.
- typename []string // Cached typename vector.
- index int // The index into the container, whether the file or a message.
- path string // The SourceCodeInfo path as comma-separated integers.
-}
-
-// TypeName returns the elements of the dotted type name.
-// The package name is not part of this name.
-func (e *EnumDescriptor) TypeName() (s []string) {
- if e.typename != nil {
- return e.typename
- }
- name := e.GetName()
- if e.parent == nil {
- s = make([]string, 1)
- } else {
- pname := e.parent.TypeName()
- s = make([]string, len(pname)+1)
- copy(s, pname)
- }
- s[len(s)-1] = name
- e.typename = s
- return s
-}
-
-// Everything but the last element of the full type name, CamelCased.
-// The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... .
-func (e *EnumDescriptor) prefix() string {
- if e.parent == nil {
- // If the enum is not part of a message, the prefix is just the type name.
- return CamelCase(*e.Name) + "_"
- }
- typeName := e.TypeName()
- return CamelCaseSlice(typeName[0:len(typeName)-1]) + "_"
-}
-
-// The integer value of the named constant in this enumerated type.
-func (e *EnumDescriptor) integerValueAsString(name string) string {
- for _, c := range e.Value {
- if c.GetName() == name {
- return fmt.Sprint(c.GetNumber())
- }
- }
- log.Fatal("cannot find value for enum constant")
- return ""
-}
-
-// ExtensionDescriptor describes an extension. If it's at top level, its parent will be nil.
-// Otherwise it will be the descriptor of the message in which it is defined.
-type ExtensionDescriptor struct {
- common
- *descriptor.FieldDescriptorProto
- parent *Descriptor // The containing message, if any.
-}
-
-// TypeName returns the elements of the dotted type name.
-// The package name is not part of this name.
-func (e *ExtensionDescriptor) TypeName() (s []string) {
- name := e.GetName()
- if e.parent == nil {
- // top-level extension
- s = make([]string, 1)
- } else {
- pname := e.parent.TypeName()
- s = make([]string, len(pname)+1)
- copy(s, pname)
- }
- s[len(s)-1] = name
- return s
-}
-
-// DescName returns the variable name used for the generated descriptor.
-func (e *ExtensionDescriptor) DescName() string {
- // The full type name.
- typeName := e.TypeName()
- // Each scope of the extension is individually CamelCased, and all are joined with "_" with an "E_" prefix.
- for i, s := range typeName {
- typeName[i] = CamelCase(s)
- }
- return "E_" + strings.Join(typeName, "_")
-}
-
-// ImportedDescriptor describes a type that has been publicly imported from another file.
-type ImportedDescriptor struct {
- common
- o Object
-}
-
-func (id *ImportedDescriptor) TypeName() []string { return id.o.TypeName() }
-
-// FileDescriptor describes an protocol buffer descriptor file (.proto).
-// It includes slices of all the messages and enums defined within it.
-// Those slices are constructed by WrapTypes.
-type FileDescriptor struct {
- *descriptor.FileDescriptorProto
- desc []*Descriptor // All the messages defined in this file.
- enum []*EnumDescriptor // All the enums defined in this file.
- ext []*ExtensionDescriptor // All the top-level extensions defined in this file.
- imp []*ImportedDescriptor // All types defined in files publicly imported by this file.
-
- // Comments, stored as a map of path (comma-separated integers) to the comment.
- comments map[string]*descriptor.SourceCodeInfo_Location
-
- // The full list of symbols that are exported,
- // as a map from the exported object to its symbols.
- // This is used for supporting public imports.
- exported map[Object][]symbol
-
- importPath GoImportPath // Import path of this file's package.
- packageName GoPackageName // Name of this file's Go package.
-
- proto3 bool // whether to generate proto3 code for this file
-}
-
-// VarName is the variable name we'll use in the generated code to refer
-// to the compressed bytes of this descriptor. It is not exported, so
-// it is only valid inside the generated package.
-func (d *FileDescriptor) VarName() string {
- h := sha256.Sum256([]byte(d.GetName()))
- return fmt.Sprintf("fileDescriptor_%s", hex.EncodeToString(h[:8]))
-}
-
-// goPackageOption interprets the file's go_package option.
-// If there is no go_package, it returns ("", "", false).
-// If there's a simple name, it returns ("", pkg, true).
-// If the option implies an import path, it returns (impPath, pkg, true).
-func (d *FileDescriptor) goPackageOption() (impPath GoImportPath, pkg GoPackageName, ok bool) {
- opt := d.GetOptions().GetGoPackage()
- if opt == "" {
- return "", "", false
- }
- // A semicolon-delimited suffix delimits the import path and package name.
- sc := strings.Index(opt, ";")
- if sc >= 0 {
- return GoImportPath(opt[:sc]), cleanPackageName(opt[sc+1:]), true
- }
- // The presence of a slash implies there's an import path.
- slash := strings.LastIndex(opt, "/")
- if slash >= 0 {
- return GoImportPath(opt), cleanPackageName(opt[slash+1:]), true
- }
- return "", cleanPackageName(opt), true
-}
-
-// goFileName returns the output name for the generated Go file.
-func (d *FileDescriptor) goFileName(pathType pathType) string {
- name := *d.Name
- if ext := path.Ext(name); ext == ".proto" || ext == ".protodevel" {
- name = name[:len(name)-len(ext)]
- }
- name += ".pb.go"
-
- if pathType == pathTypeSourceRelative {
- return name
- }
-
- // Does the file have a "go_package" option?
- // If it does, it may override the filename.
- if impPath, _, ok := d.goPackageOption(); ok && impPath != "" {
- // Replace the existing dirname with the declared import path.
- _, name = path.Split(name)
- name = path.Join(string(impPath), name)
- return name
- }
-
- return name
-}
-
-func (d *FileDescriptor) addExport(obj Object, sym symbol) {
- d.exported[obj] = append(d.exported[obj], sym)
-}
-
-// symbol is an interface representing an exported Go symbol.
-type symbol interface {
- // GenerateAlias should generate an appropriate alias
- // for the symbol from the named package.
- GenerateAlias(g *Generator, filename string, pkg GoPackageName)
-}
-
-type messageSymbol struct {
- sym string
- hasExtensions, isMessageSet bool
- oneofTypes []string
-}
-
-type getterSymbol struct {
- name string
- typ string
- typeName string // canonical name in proto world; empty for proto.Message and similar
- genType bool // whether typ contains a generated type (message/group/enum)
-}
-
-func (ms *messageSymbol) GenerateAlias(g *Generator, filename string, pkg GoPackageName) {
- g.P("// ", ms.sym, " from public import ", filename)
- g.P("type ", ms.sym, " = ", pkg, ".", ms.sym)
- for _, name := range ms.oneofTypes {
- g.P("type ", name, " = ", pkg, ".", name)
- }
-}
-
-type enumSymbol struct {
- name string
- proto3 bool // Whether this came from a proto3 file.
-}
-
-func (es enumSymbol) GenerateAlias(g *Generator, filename string, pkg GoPackageName) {
- s := es.name
- g.P("// ", s, " from public import ", filename)
- g.P("type ", s, " = ", pkg, ".", s)
- g.P("var ", s, "_name = ", pkg, ".", s, "_name")
- g.P("var ", s, "_value = ", pkg, ".", s, "_value")
-}
-
-type constOrVarSymbol struct {
- sym string
- typ string // either "const" or "var"
- cast string // if non-empty, a type cast is required (used for enums)
-}
-
-func (cs constOrVarSymbol) GenerateAlias(g *Generator, filename string, pkg GoPackageName) {
- v := string(pkg) + "." + cs.sym
- if cs.cast != "" {
- v = cs.cast + "(" + v + ")"
- }
- g.P(cs.typ, " ", cs.sym, " = ", v)
-}
-
-// Object is an interface abstracting the abilities shared by enums, messages, extensions and imported objects.
-type Object interface {
- GoImportPath() GoImportPath
- TypeName() []string
- File() *FileDescriptor
-}
-
-// Generator is the type whose methods generate the output, stored in the associated response structure.
-type Generator struct {
- *bytes.Buffer
-
- Request *plugin.CodeGeneratorRequest // The input.
- Response *plugin.CodeGeneratorResponse // The output.
-
- Param map[string]string // Command-line parameters.
- PackageImportPath string // Go import path of the package we're generating code for
- ImportPrefix string // String to prefix to imported package file names.
- ImportMap map[string]string // Mapping from .proto file name to import path
-
- Pkg map[string]string // The names under which we import support packages
-
- outputImportPath GoImportPath // Package we're generating code for.
- allFiles []*FileDescriptor // All files in the tree
- allFilesByName map[string]*FileDescriptor // All files by filename.
- genFiles []*FileDescriptor // Those files we will generate output for.
- file *FileDescriptor // The file we are compiling now.
- packageNames map[GoImportPath]GoPackageName // Imported package names in the current file.
- usedPackages map[GoImportPath]bool // Packages used in current file.
- usedPackageNames map[GoPackageName]bool // Package names used in the current file.
- addedImports map[GoImportPath]bool // Additional imports to emit.
- typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax.
- init []string // Lines to emit in the init function.
- indent string
- pathType pathType // How to generate output filenames.
- writeOutput bool
- annotateCode bool // whether to store annotations
- annotations []*descriptor.GeneratedCodeInfo_Annotation // annotations to store
-}
-
-type pathType int
-
-const (
- pathTypeImport pathType = iota
- pathTypeSourceRelative
-)
-
-// New creates a new generator and allocates the request and response protobufs.
-func New() *Generator {
- g := new(Generator)
- g.Buffer = new(bytes.Buffer)
- g.Request = new(plugin.CodeGeneratorRequest)
- g.Response = new(plugin.CodeGeneratorResponse)
- return g
-}
-
-// Error reports a problem, including an error, and exits the program.
-func (g *Generator) Error(err error, msgs ...string) {
- s := strings.Join(msgs, " ") + ":" + err.Error()
- log.Print("protoc-gen-go: error:", s)
- os.Exit(1)
-}
-
-// Fail reports a problem and exits the program.
-func (g *Generator) Fail(msgs ...string) {
- s := strings.Join(msgs, " ")
- log.Print("protoc-gen-go: error:", s)
- os.Exit(1)
-}
-
-// CommandLineParameters breaks the comma-separated list of key=value pairs
-// in the parameter (a member of the request protobuf) into a key/value map.
-// It then sets file name mappings defined by those entries.
-func (g *Generator) CommandLineParameters(parameter string) {
- g.Param = make(map[string]string)
- for _, p := range strings.Split(parameter, ",") {
- if i := strings.Index(p, "="); i < 0 {
- g.Param[p] = ""
- } else {
- g.Param[p[0:i]] = p[i+1:]
- }
- }
-
- g.ImportMap = make(map[string]string)
- pluginList := "none" // Default list of plugin names to enable (empty means all).
- for k, v := range g.Param {
- switch k {
- case "import_prefix":
- g.ImportPrefix = v
- case "import_path":
- g.PackageImportPath = v
- case "paths":
- switch v {
- case "import":
- g.pathType = pathTypeImport
- case "source_relative":
- g.pathType = pathTypeSourceRelative
- default:
- g.Fail(fmt.Sprintf(`Unknown path type %q: want "import" or "source_relative".`, v))
- }
- case "plugins":
- pluginList = v
- case "annotate_code":
- if v == "true" {
- g.annotateCode = true
- }
- default:
- if len(k) > 0 && k[0] == 'M' {
- g.ImportMap[k[1:]] = v
- }
- }
- }
- if pluginList != "" {
- // Amend the set of plugins.
- enabled := make(map[string]bool)
- for _, name := range strings.Split(pluginList, "+") {
- enabled[name] = true
- }
- var nplugins []Plugin
- for _, p := range plugins {
- if enabled[p.Name()] {
- nplugins = append(nplugins, p)
- }
- }
- plugins = nplugins
- }
-}
-
-// DefaultPackageName returns the package name printed for the object.
-// If its file is in a different package, it returns the package name we're using for this file, plus ".".
-// Otherwise it returns the empty string.
-func (g *Generator) DefaultPackageName(obj Object) string {
- importPath := obj.GoImportPath()
- if importPath == g.outputImportPath {
- return ""
- }
- return string(g.GoPackageName(importPath)) + "."
-}
-
-// GoPackageName returns the name used for a package.
-func (g *Generator) GoPackageName(importPath GoImportPath) GoPackageName {
- if name, ok := g.packageNames[importPath]; ok {
- return name
- }
- name := cleanPackageName(baseName(string(importPath)))
- for i, orig := 1, name; g.usedPackageNames[name] || isGoPredeclaredIdentifier[string(name)]; i++ {
- name = orig + GoPackageName(strconv.Itoa(i))
- }
- g.packageNames[importPath] = name
- g.usedPackageNames[name] = true
- return name
-}
-
-// AddImport adds a package to the generated file's import section.
-// It returns the name used for the package.
-func (g *Generator) AddImport(importPath GoImportPath) GoPackageName {
- g.addedImports[importPath] = true
- return g.GoPackageName(importPath)
-}
-
-var globalPackageNames = map[GoPackageName]bool{
- "fmt": true,
- "math": true,
- "proto": true,
-}
-
-// Create and remember a guaranteed unique package name. Pkg is the candidate name.
-// The FileDescriptor parameter is unused.
-func RegisterUniquePackageName(pkg string, f *FileDescriptor) string {
- name := cleanPackageName(pkg)
- for i, orig := 1, name; globalPackageNames[name]; i++ {
- name = orig + GoPackageName(strconv.Itoa(i))
- }
- globalPackageNames[name] = true
- return string(name)
-}
-
-var isGoKeyword = map[string]bool{
- "break": true,
- "case": true,
- "chan": true,
- "const": true,
- "continue": true,
- "default": true,
- "else": true,
- "defer": true,
- "fallthrough": true,
- "for": true,
- "func": true,
- "go": true,
- "goto": true,
- "if": true,
- "import": true,
- "interface": true,
- "map": true,
- "package": true,
- "range": true,
- "return": true,
- "select": true,
- "struct": true,
- "switch": true,
- "type": true,
- "var": true,
-}
-
-var isGoPredeclaredIdentifier = map[string]bool{
- "append": true,
- "bool": true,
- "byte": true,
- "cap": true,
- "close": true,
- "complex": true,
- "complex128": true,
- "complex64": true,
- "copy": true,
- "delete": true,
- "error": true,
- "false": true,
- "float32": true,
- "float64": true,
- "imag": true,
- "int": true,
- "int16": true,
- "int32": true,
- "int64": true,
- "int8": true,
- "iota": true,
- "len": true,
- "make": true,
- "new": true,
- "nil": true,
- "panic": true,
- "print": true,
- "println": true,
- "real": true,
- "recover": true,
- "rune": true,
- "string": true,
- "true": true,
- "uint": true,
- "uint16": true,
- "uint32": true,
- "uint64": true,
- "uint8": true,
- "uintptr": true,
-}
-
-func cleanPackageName(name string) GoPackageName {
- name = strings.Map(badToUnderscore, name)
- // Identifier must not be keyword or predeclared identifier: insert _.
- if isGoKeyword[name] {
- name = "_" + name
- }
- // Identifier must not begin with digit: insert _.
- if r, _ := utf8.DecodeRuneInString(name); unicode.IsDigit(r) {
- name = "_" + name
- }
- return GoPackageName(name)
-}
-
-// defaultGoPackage returns the package name to use,
-// derived from the import path of the package we're building code for.
-func (g *Generator) defaultGoPackage() GoPackageName {
- p := g.PackageImportPath
- if i := strings.LastIndex(p, "/"); i >= 0 {
- p = p[i+1:]
- }
- return cleanPackageName(p)
-}
-
-// SetPackageNames sets the package name for this run.
-// The package name must agree across all files being generated.
-// It also defines unique package names for all imported files.
-func (g *Generator) SetPackageNames() {
- g.outputImportPath = g.genFiles[0].importPath
-
- defaultPackageNames := make(map[GoImportPath]GoPackageName)
- for _, f := range g.genFiles {
- if _, p, ok := f.goPackageOption(); ok {
- defaultPackageNames[f.importPath] = p
- }
- }
- for _, f := range g.genFiles {
- if _, p, ok := f.goPackageOption(); ok {
- // Source file: option go_package = "quux/bar";
- f.packageName = p
- } else if p, ok := defaultPackageNames[f.importPath]; ok {
- // A go_package option in another file in the same package.
- //
- // This is a poor choice in general, since every source file should
- // contain a go_package option. Supported mainly for historical
- // compatibility.
- f.packageName = p
- } else if p := g.defaultGoPackage(); p != "" {
- // Command-line: import_path=quux/bar.
- //
- // The import_path flag sets a package name for files which don't
- // contain a go_package option.
- f.packageName = p
- } else if p := f.GetPackage(); p != "" {
- // Source file: package quux.bar;
- f.packageName = cleanPackageName(p)
- } else {
- // Source filename.
- f.packageName = cleanPackageName(baseName(f.GetName()))
- }
- }
-
- // Check that all files have a consistent package name and import path.
- for _, f := range g.genFiles[1:] {
- if a, b := g.genFiles[0].importPath, f.importPath; a != b {
- g.Fail(fmt.Sprintf("inconsistent package import paths: %v, %v", a, b))
- }
- if a, b := g.genFiles[0].packageName, f.packageName; a != b {
- g.Fail(fmt.Sprintf("inconsistent package names: %v, %v", a, b))
- }
- }
-
- // Names of support packages. These never vary (if there are conflicts,
- // we rename the conflicting package), so this could be removed someday.
- g.Pkg = map[string]string{
- "fmt": "fmt",
- "math": "math",
- "proto": "proto",
- }
-}
-
-// WrapTypes walks the incoming data, wrapping DescriptorProtos, EnumDescriptorProtos
-// and FileDescriptorProtos into file-referenced objects within the Generator.
-// It also creates the list of files to generate and so should be called before GenerateAllFiles.
-func (g *Generator) WrapTypes() {
- g.allFiles = make([]*FileDescriptor, 0, len(g.Request.ProtoFile))
- g.allFilesByName = make(map[string]*FileDescriptor, len(g.allFiles))
- genFileNames := make(map[string]bool)
- for _, n := range g.Request.FileToGenerate {
- genFileNames[n] = true
- }
- for _, f := range g.Request.ProtoFile {
- fd := &FileDescriptor{
- FileDescriptorProto: f,
- exported: make(map[Object][]symbol),
- proto3: fileIsProto3(f),
- }
- // The import path may be set in a number of ways.
- if substitution, ok := g.ImportMap[f.GetName()]; ok {
- // Command-line: M=foo.proto=quux/bar.
- //
- // Explicit mapping of source file to import path.
- fd.importPath = GoImportPath(substitution)
- } else if genFileNames[f.GetName()] && g.PackageImportPath != "" {
- // Command-line: import_path=quux/bar.
- //
- // The import_path flag sets the import path for every file that
- // we generate code for.
- fd.importPath = GoImportPath(g.PackageImportPath)
- } else if p, _, _ := fd.goPackageOption(); p != "" {
- // Source file: option go_package = "quux/bar";
- //
- // The go_package option sets the import path. Most users should use this.
- fd.importPath = p
- } else {
- // Source filename.
- //
- // Last resort when nothing else is available.
- fd.importPath = GoImportPath(path.Dir(f.GetName()))
- }
- // We must wrap the descriptors before we wrap the enums
- fd.desc = wrapDescriptors(fd)
- g.buildNestedDescriptors(fd.desc)
- fd.enum = wrapEnumDescriptors(fd, fd.desc)
- g.buildNestedEnums(fd.desc, fd.enum)
- fd.ext = wrapExtensions(fd)
- extractComments(fd)
- g.allFiles = append(g.allFiles, fd)
- g.allFilesByName[f.GetName()] = fd
- }
- for _, fd := range g.allFiles {
- fd.imp = wrapImported(fd, g)
- }
-
- g.genFiles = make([]*FileDescriptor, 0, len(g.Request.FileToGenerate))
- for _, fileName := range g.Request.FileToGenerate {
- fd := g.allFilesByName[fileName]
- if fd == nil {
- g.Fail("could not find file named", fileName)
- }
- g.genFiles = append(g.genFiles, fd)
- }
-}
-
-// Scan the descriptors in this file. For each one, build the slice of nested descriptors
-func (g *Generator) buildNestedDescriptors(descs []*Descriptor) {
- for _, desc := range descs {
- if len(desc.NestedType) != 0 {
- for _, nest := range descs {
- if nest.parent == desc {
- desc.nested = append(desc.nested, nest)
- }
- }
- if len(desc.nested) != len(desc.NestedType) {
- g.Fail("internal error: nesting failure for", desc.GetName())
- }
- }
- }
-}
-
-func (g *Generator) buildNestedEnums(descs []*Descriptor, enums []*EnumDescriptor) {
- for _, desc := range descs {
- if len(desc.EnumType) != 0 {
- for _, enum := range enums {
- if enum.parent == desc {
- desc.enums = append(desc.enums, enum)
- }
- }
- if len(desc.enums) != len(desc.EnumType) {
- g.Fail("internal error: enum nesting failure for", desc.GetName())
- }
- }
- }
-}
-
-// Construct the Descriptor
-func newDescriptor(desc *descriptor.DescriptorProto, parent *Descriptor, file *FileDescriptor, index int) *Descriptor {
- d := &Descriptor{
- common: common{file},
- DescriptorProto: desc,
- parent: parent,
- index: index,
- }
- if parent == nil {
- d.path = fmt.Sprintf("%d,%d", messagePath, index)
- } else {
- d.path = fmt.Sprintf("%s,%d,%d", parent.path, messageMessagePath, index)
- }
-
- // The only way to distinguish a group from a message is whether
- // the containing message has a TYPE_GROUP field that matches.
- if parent != nil {
- parts := d.TypeName()
- if file.Package != nil {
- parts = append([]string{*file.Package}, parts...)
- }
- exp := "." + strings.Join(parts, ".")
- for _, field := range parent.Field {
- if field.GetType() == descriptor.FieldDescriptorProto_TYPE_GROUP && field.GetTypeName() == exp {
- d.group = true
- break
- }
- }
- }
-
- for _, field := range desc.Extension {
- d.ext = append(d.ext, &ExtensionDescriptor{common{file}, field, d})
- }
-
- return d
-}
-
-// Return a slice of all the Descriptors defined within this file
-func wrapDescriptors(file *FileDescriptor) []*Descriptor {
- sl := make([]*Descriptor, 0, len(file.MessageType)+10)
- for i, desc := range file.MessageType {
- sl = wrapThisDescriptor(sl, desc, nil, file, i)
- }
- return sl
-}
-
-// Wrap this Descriptor, recursively
-func wrapThisDescriptor(sl []*Descriptor, desc *descriptor.DescriptorProto, parent *Descriptor, file *FileDescriptor, index int) []*Descriptor {
- sl = append(sl, newDescriptor(desc, parent, file, index))
- me := sl[len(sl)-1]
- for i, nested := range desc.NestedType {
- sl = wrapThisDescriptor(sl, nested, me, file, i)
- }
- return sl
-}
-
-// Construct the EnumDescriptor
-func newEnumDescriptor(desc *descriptor.EnumDescriptorProto, parent *Descriptor, file *FileDescriptor, index int) *EnumDescriptor {
- ed := &EnumDescriptor{
- common: common{file},
- EnumDescriptorProto: desc,
- parent: parent,
- index: index,
- }
- if parent == nil {
- ed.path = fmt.Sprintf("%d,%d", enumPath, index)
- } else {
- ed.path = fmt.Sprintf("%s,%d,%d", parent.path, messageEnumPath, index)
- }
- return ed
-}
-
-// Return a slice of all the EnumDescriptors defined within this file
-func wrapEnumDescriptors(file *FileDescriptor, descs []*Descriptor) []*EnumDescriptor {
- sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10)
- // Top-level enums.
- for i, enum := range file.EnumType {
- sl = append(sl, newEnumDescriptor(enum, nil, file, i))
- }
- // Enums within messages. Enums within embedded messages appear in the outer-most message.
- for _, nested := range descs {
- for i, enum := range nested.EnumType {
- sl = append(sl, newEnumDescriptor(enum, nested, file, i))
- }
- }
- return sl
-}
-
-// Return a slice of all the top-level ExtensionDescriptors defined within this file.
-func wrapExtensions(file *FileDescriptor) []*ExtensionDescriptor {
- var sl []*ExtensionDescriptor
- for _, field := range file.Extension {
- sl = append(sl, &ExtensionDescriptor{common{file}, field, nil})
- }
- return sl
-}
-
-// Return a slice of all the types that are publicly imported into this file.
-func wrapImported(file *FileDescriptor, g *Generator) (sl []*ImportedDescriptor) {
- for _, index := range file.PublicDependency {
- df := g.fileByName(file.Dependency[index])
- for _, d := range df.desc {
- if d.GetOptions().GetMapEntry() {
- continue
- }
- sl = append(sl, &ImportedDescriptor{common{file}, d})
- }
- for _, e := range df.enum {
- sl = append(sl, &ImportedDescriptor{common{file}, e})
- }
- for _, ext := range df.ext {
- sl = append(sl, &ImportedDescriptor{common{file}, ext})
- }
- }
- return
-}
-
-func extractComments(file *FileDescriptor) {
- file.comments = make(map[string]*descriptor.SourceCodeInfo_Location)
- for _, loc := range file.GetSourceCodeInfo().GetLocation() {
- if loc.LeadingComments == nil {
- continue
- }
- var p []string
- for _, n := range loc.Path {
- p = append(p, strconv.Itoa(int(n)))
- }
- file.comments[strings.Join(p, ",")] = loc
- }
-}
-
-// BuildTypeNameMap builds the map from fully qualified type names to objects.
-// The key names for the map come from the input data, which puts a period at the beginning.
-// It should be called after SetPackageNames and before GenerateAllFiles.
-func (g *Generator) BuildTypeNameMap() {
- g.typeNameToObject = make(map[string]Object)
- for _, f := range g.allFiles {
- // The names in this loop are defined by the proto world, not us, so the
- // package name may be empty. If so, the dotted package name of X will
- // be ".X"; otherwise it will be ".pkg.X".
- dottedPkg := "." + f.GetPackage()
- if dottedPkg != "." {
- dottedPkg += "."
- }
- for _, enum := range f.enum {
- name := dottedPkg + dottedSlice(enum.TypeName())
- g.typeNameToObject[name] = enum
- }
- for _, desc := range f.desc {
- name := dottedPkg + dottedSlice(desc.TypeName())
- g.typeNameToObject[name] = desc
- }
- }
-}
-
-// ObjectNamed, given a fully-qualified input type name as it appears in the input data,
-// returns the descriptor for the message or enum with that name.
-func (g *Generator) ObjectNamed(typeName string) Object {
- o, ok := g.typeNameToObject[typeName]
- if !ok {
- g.Fail("can't find object with type", typeName)
- }
- return o
-}
-
-// AnnotatedAtoms is a list of atoms (as consumed by P) that records the file name and proto AST path from which they originated.
-type AnnotatedAtoms struct {
- source string
- path string
- atoms []interface{}
-}
-
-// Annotate records the file name and proto AST path of a list of atoms
-// so that a later call to P can emit a link from each atom to its origin.
-func Annotate(file *FileDescriptor, path string, atoms ...interface{}) *AnnotatedAtoms {
- return &AnnotatedAtoms{source: *file.Name, path: path, atoms: atoms}
-}
-
-// printAtom prints the (atomic, non-annotation) argument to the generated output.
-func (g *Generator) printAtom(v interface{}) {
- switch v := v.(type) {
- case string:
- g.WriteString(v)
- case *string:
- g.WriteString(*v)
- case bool:
- fmt.Fprint(g, v)
- case *bool:
- fmt.Fprint(g, *v)
- case int:
- fmt.Fprint(g, v)
- case *int32:
- fmt.Fprint(g, *v)
- case *int64:
- fmt.Fprint(g, *v)
- case float64:
- fmt.Fprint(g, v)
- case *float64:
- fmt.Fprint(g, *v)
- case GoPackageName:
- g.WriteString(string(v))
- case GoImportPath:
- g.WriteString(strconv.Quote(string(v)))
- default:
- g.Fail(fmt.Sprintf("unknown type in printer: %T", v))
- }
-}
-
-// P prints the arguments to the generated output. It handles strings and int32s, plus
-// handling indirections because they may be *string, etc. Any inputs of type AnnotatedAtoms may emit
-// annotations in a .meta file in addition to outputting the atoms themselves (if g.annotateCode
-// is true).
-func (g *Generator) P(str ...interface{}) {
- if !g.writeOutput {
- return
- }
- g.WriteString(g.indent)
- for _, v := range str {
- switch v := v.(type) {
- case *AnnotatedAtoms:
- begin := int32(g.Len())
- for _, v := range v.atoms {
- g.printAtom(v)
- }
- if g.annotateCode {
- end := int32(g.Len())
- var path []int32
- for _, token := range strings.Split(v.path, ",") {
- val, err := strconv.ParseInt(token, 10, 32)
- if err != nil {
- g.Fail("could not parse proto AST path: ", err.Error())
- }
- path = append(path, int32(val))
- }
- g.annotations = append(g.annotations, &descriptor.GeneratedCodeInfo_Annotation{
- Path: path,
- SourceFile: &v.source,
- Begin: &begin,
- End: &end,
- })
- }
- default:
- g.printAtom(v)
- }
- }
- g.WriteByte('\n')
-}
-
-// addInitf stores the given statement to be printed inside the file's init function.
-// The statement is given as a format specifier and arguments.
-func (g *Generator) addInitf(stmt string, a ...interface{}) {
- g.init = append(g.init, fmt.Sprintf(stmt, a...))
-}
-
-// In Indents the output one tab stop.
-func (g *Generator) In() { g.indent += "\t" }
-
-// Out unindents the output one tab stop.
-func (g *Generator) Out() {
- if len(g.indent) > 0 {
- g.indent = g.indent[1:]
- }
-}
-
-// GenerateAllFiles generates the output for all the files we're outputting.
-func (g *Generator) GenerateAllFiles() {
- // Initialize the plugins
- for _, p := range plugins {
- p.Init(g)
- }
- // Generate the output. The generator runs for every file, even the files
- // that we don't generate output for, so that we can collate the full list
- // of exported symbols to support public imports.
- genFileMap := make(map[*FileDescriptor]bool, len(g.genFiles))
- for _, file := range g.genFiles {
- genFileMap[file] = true
- }
- for _, file := range g.allFiles {
- g.Reset()
- g.annotations = nil
- g.writeOutput = genFileMap[file]
- g.generate(file)
- if !g.writeOutput {
- continue
- }
- fname := file.goFileName(g.pathType)
- g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
- Name: proto.String(fname),
- Content: proto.String(g.String()),
- })
- if g.annotateCode {
- // Store the generated code annotations in text, as the protoc plugin protocol requires that
- // strings contain valid UTF-8.
- g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
- Name: proto.String(file.goFileName(g.pathType) + ".meta"),
- Content: proto.String(proto.CompactTextString(&descriptor.GeneratedCodeInfo{Annotation: g.annotations})),
- })
- }
- }
-}
-
-// Run all the plugins associated with the file.
-func (g *Generator) runPlugins(file *FileDescriptor) {
- for _, p := range plugins {
- p.Generate(file)
- }
-}
-
-// Fill the response protocol buffer with the generated output for all the files we're
-// supposed to generate.
-func (g *Generator) generate(file *FileDescriptor) {
- g.file = file
- g.usedPackages = make(map[GoImportPath]bool)
- g.packageNames = make(map[GoImportPath]GoPackageName)
- g.usedPackageNames = make(map[GoPackageName]bool)
- g.addedImports = make(map[GoImportPath]bool)
- for name := range globalPackageNames {
- g.usedPackageNames[name] = true
- }
-
- g.P("// This is a compile-time assertion to ensure that this generated file")
- g.P("// is compatible with the proto package it is being compiled against.")
- g.P("// A compilation error at this line likely means your copy of the")
- g.P("// proto package needs to be updated.")
- g.P("const _ = ", g.Pkg["proto"], ".ProtoPackageIsVersion", generatedCodeVersion, " // please upgrade the proto package")
- g.P()
-
- for _, td := range g.file.imp {
- g.generateImported(td)
- }
- for _, enum := range g.file.enum {
- g.generateEnum(enum)
- }
- for _, desc := range g.file.desc {
- // Don't generate virtual messages for maps.
- if desc.GetOptions().GetMapEntry() {
- continue
- }
- g.generateMessage(desc)
- }
- for _, ext := range g.file.ext {
- g.generateExtension(ext)
- }
- g.generateInitFunction()
- g.generateFileDescriptor(file)
-
- // Run the plugins before the imports so we know which imports are necessary.
- g.runPlugins(file)
-
- // Generate header and imports last, though they appear first in the output.
- rem := g.Buffer
- remAnno := g.annotations
- g.Buffer = new(bytes.Buffer)
- g.annotations = nil
- g.generateHeader()
- g.generateImports()
- if !g.writeOutput {
- return
- }
- // Adjust the offsets for annotations displaced by the header and imports.
- for _, anno := range remAnno {
- *anno.Begin += int32(g.Len())
- *anno.End += int32(g.Len())
- g.annotations = append(g.annotations, anno)
- }
- g.Write(rem.Bytes())
-
- // Reformat generated code and patch annotation locations.
- fset := token.NewFileSet()
- original := g.Bytes()
- if g.annotateCode {
- // make a copy independent of g; we'll need it after Reset.
- original = append([]byte(nil), original...)
- }
- fileAST, err := parser.ParseFile(fset, "", original, parser.ParseComments)
- if err != nil {
- // Print out the bad code with line numbers.
- // This should never happen in practice, but it can while changing generated code,
- // so consider this a debugging aid.
- var src bytes.Buffer
- s := bufio.NewScanner(bytes.NewReader(original))
- for line := 1; s.Scan(); line++ {
- fmt.Fprintf(&src, "%5d\t%s\n", line, s.Bytes())
- }
- g.Fail("bad Go source code was generated:", err.Error(), "\n"+src.String())
- }
- ast.SortImports(fset, fileAST)
- g.Reset()
- err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, fileAST)
- if err != nil {
- g.Fail("generated Go source code could not be reformatted:", err.Error())
- }
- if g.annotateCode {
- m, err := remap.Compute(original, g.Bytes())
- if err != nil {
- g.Fail("formatted generated Go source code could not be mapped back to the original code:", err.Error())
- }
- for _, anno := range g.annotations {
- new, ok := m.Find(int(*anno.Begin), int(*anno.End))
- if !ok {
- g.Fail("span in formatted generated Go source code could not be mapped back to the original code")
- }
- *anno.Begin = int32(new.Pos)
- *anno.End = int32(new.End)
- }
- }
-}
-
-// Generate the header, including package definition
-func (g *Generator) generateHeader() {
- g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
- if g.file.GetOptions().GetDeprecated() {
- g.P("// ", g.file.Name, " is a deprecated file.")
- } else {
- g.P("// source: ", g.file.Name)
- }
- g.P()
- g.PrintComments(strconv.Itoa(packagePath))
- g.P()
- g.P("package ", g.file.packageName)
- g.P()
-}
-
-// deprecationComment is the standard comment added to deprecated
-// messages, fields, enums, and enum values.
-var deprecationComment = "// Deprecated: Do not use."
-
-// PrintComments prints any comments from the source .proto file.
-// The path is a comma-separated list of integers.
-// It returns an indication of whether any comments were printed.
-// See descriptor.proto for its format.
-func (g *Generator) PrintComments(path string) bool {
- if !g.writeOutput {
- return false
- }
- if c, ok := g.makeComments(path); ok {
- g.P(c)
- return true
- }
- return false
-}
-
-// makeComments generates the comment string for the field, no "\n" at the end
-func (g *Generator) makeComments(path string) (string, bool) {
- loc, ok := g.file.comments[path]
- if !ok {
- return "", false
- }
- w := new(bytes.Buffer)
- nl := ""
- for _, line := range strings.Split(strings.TrimSuffix(loc.GetLeadingComments(), "\n"), "\n") {
- fmt.Fprintf(w, "%s//%s", nl, line)
- nl = "\n"
- }
- return w.String(), true
-}
-
-func (g *Generator) fileByName(filename string) *FileDescriptor {
- return g.allFilesByName[filename]
-}
-
-// weak returns whether the ith import of the current file is a weak import.
-func (g *Generator) weak(i int32) bool {
- for _, j := range g.file.WeakDependency {
- if j == i {
- return true
- }
- }
- return false
-}
-
-// Generate the imports
-func (g *Generator) generateImports() {
- imports := make(map[GoImportPath]GoPackageName)
- for i, s := range g.file.Dependency {
- fd := g.fileByName(s)
- importPath := fd.importPath
- // Do not import our own package.
- if importPath == g.file.importPath {
- continue
- }
- // Do not import weak imports.
- if g.weak(int32(i)) {
- continue
- }
- // Do not import a package twice.
- if _, ok := imports[importPath]; ok {
- continue
- }
- // We need to import all the dependencies, even if we don't reference them,
- // because other code and tools depend on having the full transitive closure
- // of protocol buffer types in the binary.
- packageName := g.GoPackageName(importPath)
- if _, ok := g.usedPackages[importPath]; !ok {
- packageName = "_"
- }
- imports[importPath] = packageName
- }
- for importPath := range g.addedImports {
- imports[importPath] = g.GoPackageName(importPath)
- }
- // We almost always need a proto import. Rather than computing when we
- // do, which is tricky when there's a plugin, just import it and
- // reference it later. The same argument applies to the fmt and math packages.
- g.P("import (")
- g.P(g.Pkg["fmt"] + ` "fmt"`)
- g.P(g.Pkg["math"] + ` "math"`)
- g.P(g.Pkg["proto"]+" ", GoImportPath(g.ImportPrefix)+"github.com/golang/protobuf/proto")
- for importPath, packageName := range imports {
- g.P(packageName, " ", GoImportPath(g.ImportPrefix)+importPath)
- }
- g.P(")")
- g.P()
- // TODO: may need to worry about uniqueness across plugins
- for _, p := range plugins {
- p.GenerateImports(g.file)
- g.P()
- }
- g.P("// Reference imports to suppress errors if they are not otherwise used.")
- g.P("var _ = ", g.Pkg["proto"], ".Marshal")
- g.P("var _ = ", g.Pkg["fmt"], ".Errorf")
- g.P("var _ = ", g.Pkg["math"], ".Inf")
- g.P()
-}
-
-func (g *Generator) generateImported(id *ImportedDescriptor) {
- df := id.o.File()
- filename := *df.Name
- if df.importPath == g.file.importPath {
- // Don't generate type aliases for files in the same Go package as this one.
- return
- }
- if !supportTypeAliases {
- g.Fail(fmt.Sprintf("%s: public imports require at least go1.9", filename))
- }
- g.usedPackages[df.importPath] = true
-
- for _, sym := range df.exported[id.o] {
- sym.GenerateAlias(g, filename, g.GoPackageName(df.importPath))
- }
-
- g.P()
-}
-
-// Generate the enum definitions for this EnumDescriptor.
-func (g *Generator) generateEnum(enum *EnumDescriptor) {
- // The full type name
- typeName := enum.TypeName()
- // The full type name, CamelCased.
- ccTypeName := CamelCaseSlice(typeName)
- ccPrefix := enum.prefix()
-
- deprecatedEnum := ""
- if enum.GetOptions().GetDeprecated() {
- deprecatedEnum = deprecationComment
- }
- g.PrintComments(enum.path)
- g.P("type ", Annotate(enum.file, enum.path, ccTypeName), " int32", deprecatedEnum)
- g.file.addExport(enum, enumSymbol{ccTypeName, enum.proto3()})
- g.P("const (")
- for i, e := range enum.Value {
- etorPath := fmt.Sprintf("%s,%d,%d", enum.path, enumValuePath, i)
- g.PrintComments(etorPath)
-
- deprecatedValue := ""
- if e.GetOptions().GetDeprecated() {
- deprecatedValue = deprecationComment
- }
-
- name := ccPrefix + *e.Name
- g.P(Annotate(enum.file, etorPath, name), " ", ccTypeName, " = ", e.Number, " ", deprecatedValue)
- g.file.addExport(enum, constOrVarSymbol{name, "const", ccTypeName})
- }
- g.P(")")
- g.P()
- g.P("var ", ccTypeName, "_name = map[int32]string{")
- generated := make(map[int32]bool) // avoid duplicate values
- for _, e := range enum.Value {
- duplicate := ""
- if _, present := generated[*e.Number]; present {
- duplicate = "// Duplicate value: "
- }
- g.P(duplicate, e.Number, ": ", strconv.Quote(*e.Name), ",")
- generated[*e.Number] = true
- }
- g.P("}")
- g.P()
- g.P("var ", ccTypeName, "_value = map[string]int32{")
- for _, e := range enum.Value {
- g.P(strconv.Quote(*e.Name), ": ", e.Number, ",")
- }
- g.P("}")
- g.P()
-
- if !enum.proto3() {
- g.P("func (x ", ccTypeName, ") Enum() *", ccTypeName, " {")
- g.P("p := new(", ccTypeName, ")")
- g.P("*p = x")
- g.P("return p")
- g.P("}")
- g.P()
- }
-
- g.P("func (x ", ccTypeName, ") String() string {")
- g.P("return ", g.Pkg["proto"], ".EnumName(", ccTypeName, "_name, int32(x))")
- g.P("}")
- g.P()
-
- if !enum.proto3() {
- g.P("func (x *", ccTypeName, ") UnmarshalJSON(data []byte) error {")
- g.P("value, err := ", g.Pkg["proto"], ".UnmarshalJSONEnum(", ccTypeName, `_value, data, "`, ccTypeName, `")`)
- g.P("if err != nil {")
- g.P("return err")
- g.P("}")
- g.P("*x = ", ccTypeName, "(value)")
- g.P("return nil")
- g.P("}")
- g.P()
- }
-
- var indexes []string
- for m := enum.parent; m != nil; m = m.parent {
- // XXX: skip groups?
- indexes = append([]string{strconv.Itoa(m.index)}, indexes...)
- }
- indexes = append(indexes, strconv.Itoa(enum.index))
- g.P("func (", ccTypeName, ") EnumDescriptor() ([]byte, []int) {")
- g.P("return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "}")
- g.P("}")
- g.P()
- if enum.file.GetPackage() == "google.protobuf" && enum.GetName() == "NullValue" {
- g.P("func (", ccTypeName, `) XXX_WellKnownType() string { return "`, enum.GetName(), `" }`)
- g.P()
- }
-
- g.generateEnumRegistration(enum)
-}
-
-// The tag is a string like "varint,2,opt,name=fieldname,def=7" that
-// identifies details of the field for the protocol buffer marshaling and unmarshaling
-// code. The fields are:
-// wire encoding
-// protocol tag number
-// opt,req,rep for optional, required, or repeated
-// packed whether the encoding is "packed" (optional; repeated primitives only)
-// name= the original declared name
-// enum= the name of the enum type if it is an enum-typed field.
-// proto3 if this field is in a proto3 message
-// def= string representation of the default value, if any.
-// The default value must be in a representation that can be used at run-time
-// to generate the default value. Thus bools become 0 and 1, for instance.
-func (g *Generator) goTag(message *Descriptor, field *descriptor.FieldDescriptorProto, wiretype string) string {
- optrepreq := ""
- switch {
- case isOptional(field):
- optrepreq = "opt"
- case isRequired(field):
- optrepreq = "req"
- case isRepeated(field):
- optrepreq = "rep"
- }
- var defaultValue string
- if dv := field.DefaultValue; dv != nil { // set means an explicit default
- defaultValue = *dv
- // Some types need tweaking.
- switch *field.Type {
- case descriptor.FieldDescriptorProto_TYPE_BOOL:
- if defaultValue == "true" {
- defaultValue = "1"
- } else {
- defaultValue = "0"
- }
- case descriptor.FieldDescriptorProto_TYPE_STRING,
- descriptor.FieldDescriptorProto_TYPE_BYTES:
- // Nothing to do. Quoting is done for the whole tag.
- case descriptor.FieldDescriptorProto_TYPE_ENUM:
- // For enums we need to provide the integer constant.
- obj := g.ObjectNamed(field.GetTypeName())
- if id, ok := obj.(*ImportedDescriptor); ok {
- // It is an enum that was publicly imported.
- // We need the underlying type.
- obj = id.o
- }
- enum, ok := obj.(*EnumDescriptor)
- if !ok {
- log.Printf("obj is a %T", obj)
- if id, ok := obj.(*ImportedDescriptor); ok {
- log.Printf("id.o is a %T", id.o)
- }
- g.Fail("unknown enum type", CamelCaseSlice(obj.TypeName()))
- }
- defaultValue = enum.integerValueAsString(defaultValue)
- case descriptor.FieldDescriptorProto_TYPE_FLOAT:
- if def := defaultValue; def != "inf" && def != "-inf" && def != "nan" {
- if f, err := strconv.ParseFloat(defaultValue, 32); err == nil {
- defaultValue = fmt.Sprint(float32(f))
- }
- }
- case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
- if def := defaultValue; def != "inf" && def != "-inf" && def != "nan" {
- if f, err := strconv.ParseFloat(defaultValue, 64); err == nil {
- defaultValue = fmt.Sprint(f)
- }
- }
- }
- defaultValue = ",def=" + defaultValue
- }
- enum := ""
- if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM {
- // We avoid using obj.GoPackageName(), because we want to use the
- // original (proto-world) package name.
- obj := g.ObjectNamed(field.GetTypeName())
- if id, ok := obj.(*ImportedDescriptor); ok {
- obj = id.o
- }
- enum = ",enum="
- if pkg := obj.File().GetPackage(); pkg != "" {
- enum += pkg + "."
- }
- enum += CamelCaseSlice(obj.TypeName())
- }
- packed := ""
- if (field.Options != nil && field.Options.GetPacked()) ||
- // Per https://developers.google.com/protocol-buffers/docs/proto3#simple:
- // "In proto3, repeated fields of scalar numeric types use packed encoding by default."
- (message.proto3() && (field.Options == nil || field.Options.Packed == nil) &&
- isRepeated(field) && isScalar(field)) {
- packed = ",packed"
- }
- fieldName := field.GetName()
- name := fieldName
- if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP {
- // We must use the type name for groups instead of
- // the field name to preserve capitalization.
- // type_name in FieldDescriptorProto is fully-qualified,
- // but we only want the local part.
- name = *field.TypeName
- if i := strings.LastIndex(name, "."); i >= 0 {
- name = name[i+1:]
- }
- }
- if json := field.GetJsonName(); field.Extendee == nil && json != "" && json != name {
- // TODO: escaping might be needed, in which case
- // perhaps this should be in its own "json" tag.
- name += ",json=" + json
- }
- name = ",name=" + name
- if message.proto3() {
- name += ",proto3"
- }
- oneof := ""
- if field.OneofIndex != nil {
- oneof = ",oneof"
- }
- return strconv.Quote(fmt.Sprintf("%s,%d,%s%s%s%s%s%s",
- wiretype,
- field.GetNumber(),
- optrepreq,
- packed,
- name,
- enum,
- oneof,
- defaultValue))
-}
-
-func needsStar(typ descriptor.FieldDescriptorProto_Type) bool {
- switch typ {
- case descriptor.FieldDescriptorProto_TYPE_GROUP:
- return false
- case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
- return false
- case descriptor.FieldDescriptorProto_TYPE_BYTES:
- return false
- }
- return true
-}
-
-// TypeName is the printed name appropriate for an item. If the object is in the current file,
-// TypeName drops the package name and underscores the rest.
-// Otherwise the object is from another package; and the result is the underscored
-// package name followed by the item name.
-// The result always has an initial capital.
-func (g *Generator) TypeName(obj Object) string {
- return g.DefaultPackageName(obj) + CamelCaseSlice(obj.TypeName())
-}
-
-// GoType returns a string representing the type name, and the wire type
-func (g *Generator) GoType(message *Descriptor, field *descriptor.FieldDescriptorProto) (typ string, wire string) {
- // TODO: Options.
- switch *field.Type {
- case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
- typ, wire = "float64", "fixed64"
- case descriptor.FieldDescriptorProto_TYPE_FLOAT:
- typ, wire = "float32", "fixed32"
- case descriptor.FieldDescriptorProto_TYPE_INT64:
- typ, wire = "int64", "varint"
- case descriptor.FieldDescriptorProto_TYPE_UINT64:
- typ, wire = "uint64", "varint"
- case descriptor.FieldDescriptorProto_TYPE_INT32:
- typ, wire = "int32", "varint"
- case descriptor.FieldDescriptorProto_TYPE_UINT32:
- typ, wire = "uint32", "varint"
- case descriptor.FieldDescriptorProto_TYPE_FIXED64:
- typ, wire = "uint64", "fixed64"
- case descriptor.FieldDescriptorProto_TYPE_FIXED32:
- typ, wire = "uint32", "fixed32"
- case descriptor.FieldDescriptorProto_TYPE_BOOL:
- typ, wire = "bool", "varint"
- case descriptor.FieldDescriptorProto_TYPE_STRING:
- typ, wire = "string", "bytes"
- case descriptor.FieldDescriptorProto_TYPE_GROUP:
- desc := g.ObjectNamed(field.GetTypeName())
- typ, wire = "*"+g.TypeName(desc), "group"
- case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
- desc := g.ObjectNamed(field.GetTypeName())
- typ, wire = "*"+g.TypeName(desc), "bytes"
- case descriptor.FieldDescriptorProto_TYPE_BYTES:
- typ, wire = "[]byte", "bytes"
- case descriptor.FieldDescriptorProto_TYPE_ENUM:
- desc := g.ObjectNamed(field.GetTypeName())
- typ, wire = g.TypeName(desc), "varint"
- case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
- typ, wire = "int32", "fixed32"
- case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
- typ, wire = "int64", "fixed64"
- case descriptor.FieldDescriptorProto_TYPE_SINT32:
- typ, wire = "int32", "zigzag32"
- case descriptor.FieldDescriptorProto_TYPE_SINT64:
- typ, wire = "int64", "zigzag64"
- default:
- g.Fail("unknown type for", field.GetName())
- }
- if isRepeated(field) {
- typ = "[]" + typ
- } else if message != nil && message.proto3() {
- return
- } else if field.OneofIndex != nil && message != nil {
- return
- } else if needsStar(*field.Type) {
- typ = "*" + typ
- }
- return
-}
-
-func (g *Generator) RecordTypeUse(t string) {
- if _, ok := g.typeNameToObject[t]; !ok {
- return
- }
- importPath := g.ObjectNamed(t).GoImportPath()
- if importPath == g.outputImportPath {
- // Don't record use of objects in our package.
- return
- }
- g.AddImport(importPath)
- g.usedPackages[importPath] = true
-}
-
-// Method names that may be generated. Fields with these names get an
-// underscore appended. Any change to this set is a potential incompatible
-// API change because it changes generated field names.
-var methodNames = [...]string{
- "Reset",
- "String",
- "ProtoMessage",
- "Marshal",
- "Unmarshal",
- "ExtensionRangeArray",
- "ExtensionMap",
- "Descriptor",
-}
-
-// Names of messages in the `google.protobuf` package for which
-// we will generate XXX_WellKnownType methods.
-var wellKnownTypes = map[string]bool{
- "Any": true,
- "Duration": true,
- "Empty": true,
- "Struct": true,
- "Timestamp": true,
-
- "Value": true,
- "ListValue": true,
- "DoubleValue": true,
- "FloatValue": true,
- "Int64Value": true,
- "UInt64Value": true,
- "Int32Value": true,
- "UInt32Value": true,
- "BoolValue": true,
- "StringValue": true,
- "BytesValue": true,
-}
-
-// getterDefault finds the default value for the field to return from a getter,
-// regardless of if it's a built in default or explicit from the source. Returns e.g. "nil", `""`, "Default_MessageType_FieldName"
-func (g *Generator) getterDefault(field *descriptor.FieldDescriptorProto, goMessageType string) string {
- if isRepeated(field) {
- return "nil"
- }
- if def := field.GetDefaultValue(); def != "" {
- defaultConstant := g.defaultConstantName(goMessageType, field.GetName())
- if *field.Type != descriptor.FieldDescriptorProto_TYPE_BYTES {
- return defaultConstant
- }
- return "append([]byte(nil), " + defaultConstant + "...)"
- }
- switch *field.Type {
- case descriptor.FieldDescriptorProto_TYPE_BOOL:
- return "false"
- case descriptor.FieldDescriptorProto_TYPE_STRING:
- return `""`
- case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_BYTES:
- return "nil"
- case descriptor.FieldDescriptorProto_TYPE_ENUM:
- obj := g.ObjectNamed(field.GetTypeName())
- var enum *EnumDescriptor
- if id, ok := obj.(*ImportedDescriptor); ok {
- // The enum type has been publicly imported.
- enum, _ = id.o.(*EnumDescriptor)
- } else {
- enum, _ = obj.(*EnumDescriptor)
- }
- if enum == nil {
- log.Printf("don't know how to generate getter for %s", field.GetName())
- return "nil"
- }
- if len(enum.Value) == 0 {
- return "0 // empty enum"
- }
- first := enum.Value[0].GetName()
- return g.DefaultPackageName(obj) + enum.prefix() + first
- default:
- return "0"
- }
-}
-
-// defaultConstantName builds the name of the default constant from the message
-// type name and the untouched field name, e.g. "Default_MessageType_FieldName"
-func (g *Generator) defaultConstantName(goMessageType, protoFieldName string) string {
- return "Default_" + goMessageType + "_" + CamelCase(protoFieldName)
-}
-
-// The different types of fields in a message and how to actually print them
-// Most of the logic for generateMessage is in the methods of these types.
-//
-// Note that the content of the field is irrelevant, a simpleField can contain
-// anything from a scalar to a group (which is just a message).
-//
-// Extension fields (and message sets) are however handled separately.
-//
-// simpleField - a field that is neiter weak nor oneof, possibly repeated
-// oneofField - field containing list of subfields:
-// - oneofSubField - a field within the oneof
-
-// msgCtx contains the context for the generator functions.
-type msgCtx struct {
- goName string // Go struct name of the message, e.g. MessageName
- message *Descriptor // The descriptor for the message
-}
-
-// fieldCommon contains data common to all types of fields.
-type fieldCommon struct {
- goName string // Go name of field, e.g. "FieldName" or "Descriptor_"
- protoName string // Name of field in proto language, e.g. "field_name" or "descriptor"
- getterName string // Name of the getter, e.g. "GetFieldName" or "GetDescriptor_"
- goType string // The Go type as a string, e.g. "*int32" or "*OtherMessage"
- tags string // The tag string/annotation for the type, e.g. `protobuf:"varint,8,opt,name=region_id,json=regionId"`
- fullPath string // The full path of the field as used by Annotate etc, e.g. "4,0,2,0"
-}
-
-// getProtoName gets the proto name of a field, e.g. "field_name" or "descriptor".
-func (f *fieldCommon) getProtoName() string {
- return f.protoName
-}
-
-// getGoType returns the go type of the field as a string, e.g. "*int32".
-func (f *fieldCommon) getGoType() string {
- return f.goType
-}
-
-// simpleField is not weak, not a oneof, not an extension. Can be required, optional or repeated.
-type simpleField struct {
- fieldCommon
- protoTypeName string // Proto type name, empty if primitive, e.g. ".google.protobuf.Duration"
- protoType descriptor.FieldDescriptorProto_Type // Actual type enum value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64
- deprecated string // Deprecation comment, if any, e.g. "// Deprecated: Do not use."
- getterDef string // Default for getters, e.g. "nil", `""` or "Default_MessageType_FieldName"
- protoDef string // Default value as defined in the proto file, e.g "yoshi" or "5"
- comment string // The full comment for the field, e.g. "// Useful information"
-}
-
-// decl prints the declaration of the field in the struct (if any).
-func (f *simpleField) decl(g *Generator, mc *msgCtx) {
- g.P(f.comment, Annotate(mc.message.file, f.fullPath, f.goName), "\t", f.goType, "\t`", f.tags, "`", f.deprecated)
-}
-
-// getter prints the getter for the field.
-func (f *simpleField) getter(g *Generator, mc *msgCtx) {
- star := ""
- tname := f.goType
- if needsStar(f.protoType) && tname[0] == '*' {
- tname = tname[1:]
- star = "*"
- }
- if f.deprecated != "" {
- g.P(f.deprecated)
- }
- g.P("func (m *", mc.goName, ") ", Annotate(mc.message.file, f.fullPath, f.getterName), "() "+tname+" {")
- if f.getterDef == "nil" { // Simpler getter
- g.P("if m != nil {")
- g.P("return m." + f.goName)
- g.P("}")
- g.P("return nil")
- g.P("}")
- g.P()
- return
- }
- if mc.message.proto3() {
- g.P("if m != nil {")
- } else {
- g.P("if m != nil && m." + f.goName + " != nil {")
- }
- g.P("return " + star + "m." + f.goName)
- g.P("}")
- g.P("return ", f.getterDef)
- g.P("}")
- g.P()
-}
-
-// setter prints the setter method of the field.
-func (f *simpleField) setter(g *Generator, mc *msgCtx) {
- // No setter for regular fields yet
-}
-
-// getProtoDef returns the default value explicitly stated in the proto file, e.g "yoshi" or "5".
-func (f *simpleField) getProtoDef() string {
- return f.protoDef
-}
-
-// getProtoTypeName returns the protobuf type name for the field as returned by field.GetTypeName(), e.g. ".google.protobuf.Duration".
-func (f *simpleField) getProtoTypeName() string {
- return f.protoTypeName
-}
-
-// getProtoType returns the *field.Type value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64.
-func (f *simpleField) getProtoType() descriptor.FieldDescriptorProto_Type {
- return f.protoType
-}
-
-// oneofSubFields are kept slize held by each oneofField. They do not appear in the top level slize of fields for the message.
-type oneofSubField struct {
- fieldCommon
- protoTypeName string // Proto type name, empty if primitive, e.g. ".google.protobuf.Duration"
- protoType descriptor.FieldDescriptorProto_Type // Actual type enum value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64
- oneofTypeName string // Type name of the enclosing struct, e.g. "MessageName_FieldName"
- fieldNumber int // Actual field number, as defined in proto, e.g. 12
- getterDef string // Default for getters, e.g. "nil", `""` or "Default_MessageType_FieldName"
- protoDef string // Default value as defined in the proto file, e.g "yoshi" or "5"
- deprecated string // Deprecation comment, if any.
-}
-
-// typedNil prints a nil casted to the pointer to this field.
-// - for XXX_OneofWrappers
-func (f *oneofSubField) typedNil(g *Generator) {
- g.P("(*", f.oneofTypeName, ")(nil),")
-}
-
-// getProtoDef returns the default value explicitly stated in the proto file, e.g "yoshi" or "5".
-func (f *oneofSubField) getProtoDef() string {
- return f.protoDef
-}
-
-// getProtoTypeName returns the protobuf type name for the field as returned by field.GetTypeName(), e.g. ".google.protobuf.Duration".
-func (f *oneofSubField) getProtoTypeName() string {
- return f.protoTypeName
-}
-
-// getProtoType returns the *field.Type value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64.
-func (f *oneofSubField) getProtoType() descriptor.FieldDescriptorProto_Type {
- return f.protoType
-}
-
-// oneofField represents the oneof on top level.
-// The alternative fields within the oneof are represented by oneofSubField.
-type oneofField struct {
- fieldCommon
- subFields []*oneofSubField // All the possible oneof fields
- comment string // The full comment for the field, e.g. "// Types that are valid to be assigned to MyOneof:\n\\"
-}
-
-// decl prints the declaration of the field in the struct (if any).
-func (f *oneofField) decl(g *Generator, mc *msgCtx) {
- comment := f.comment
- for _, sf := range f.subFields {
- comment += "//\t*" + sf.oneofTypeName + "\n"
- }
- g.P(comment, Annotate(mc.message.file, f.fullPath, f.goName), " ", f.goType, " `", f.tags, "`")
-}
-
-// getter for a oneof field will print additional discriminators and interfaces for the oneof,
-// also it prints all the getters for the sub fields.
-func (f *oneofField) getter(g *Generator, mc *msgCtx) {
- // The discriminator type
- g.P("type ", f.goType, " interface {")
- g.P(f.goType, "()")
- g.P("}")
- g.P()
- // The subField types, fulfilling the discriminator type contract
- for _, sf := range f.subFields {
- g.P("type ", Annotate(mc.message.file, sf.fullPath, sf.oneofTypeName), " struct {")
- g.P(Annotate(mc.message.file, sf.fullPath, sf.goName), " ", sf.goType, " `", sf.tags, "`")
- g.P("}")
- g.P()
- }
- for _, sf := range f.subFields {
- g.P("func (*", sf.oneofTypeName, ") ", f.goType, "() {}")
- g.P()
- }
- // Getter for the oneof field
- g.P("func (m *", mc.goName, ") ", Annotate(mc.message.file, f.fullPath, f.getterName), "() ", f.goType, " {")
- g.P("if m != nil { return m.", f.goName, " }")
- g.P("return nil")
- g.P("}")
- g.P()
- // Getters for each oneof
- for _, sf := range f.subFields {
- if sf.deprecated != "" {
- g.P(sf.deprecated)
- }
- g.P("func (m *", mc.goName, ") ", Annotate(mc.message.file, sf.fullPath, sf.getterName), "() "+sf.goType+" {")
- g.P("if x, ok := m.", f.getterName, "().(*", sf.oneofTypeName, "); ok {")
- g.P("return x.", sf.goName)
- g.P("}")
- g.P("return ", sf.getterDef)
- g.P("}")
- g.P()
- }
-}
-
-// setter prints the setter method of the field.
-func (f *oneofField) setter(g *Generator, mc *msgCtx) {
- // No setters for oneof yet
-}
-
-// topLevelField interface implemented by all types of fields on the top level (not oneofSubField).
-type topLevelField interface {
- decl(g *Generator, mc *msgCtx) // print declaration within the struct
- getter(g *Generator, mc *msgCtx) // print getter
- setter(g *Generator, mc *msgCtx) // print setter if applicable
-}
-
-// defField interface implemented by all types of fields that can have defaults (not oneofField, but instead oneofSubField).
-type defField interface {
- getProtoDef() string // default value explicitly stated in the proto file, e.g "yoshi" or "5"
- getProtoName() string // proto name of a field, e.g. "field_name" or "descriptor"
- getGoType() string // go type of the field as a string, e.g. "*int32"
- getProtoTypeName() string // protobuf type name for the field, e.g. ".google.protobuf.Duration"
- getProtoType() descriptor.FieldDescriptorProto_Type // *field.Type value, e.g. descriptor.FieldDescriptorProto_TYPE_FIXED64
-}
-
-// generateDefaultConstants adds constants for default values if needed, which is only if the default value is.
-// explicit in the proto.
-func (g *Generator) generateDefaultConstants(mc *msgCtx, topLevelFields []topLevelField) {
- // Collect fields that can have defaults
- dFields := []defField{}
- for _, pf := range topLevelFields {
- if f, ok := pf.(*oneofField); ok {
- for _, osf := range f.subFields {
- dFields = append(dFields, osf)
- }
- continue
- }
- dFields = append(dFields, pf.(defField))
- }
- for _, df := range dFields {
- def := df.getProtoDef()
- if def == "" {
- continue
- }
- fieldname := g.defaultConstantName(mc.goName, df.getProtoName())
- typename := df.getGoType()
- if typename[0] == '*' {
- typename = typename[1:]
- }
- kind := "const "
- switch {
- case typename == "bool":
- case typename == "string":
- def = strconv.Quote(def)
- case typename == "[]byte":
- def = "[]byte(" + strconv.Quote(unescape(def)) + ")"
- kind = "var "
- case def == "inf", def == "-inf", def == "nan":
- // These names are known to, and defined by, the protocol language.
- switch def {
- case "inf":
- def = "math.Inf(1)"
- case "-inf":
- def = "math.Inf(-1)"
- case "nan":
- def = "math.NaN()"
- }
- if df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_FLOAT {
- def = "float32(" + def + ")"
- }
- kind = "var "
- case df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_FLOAT:
- if f, err := strconv.ParseFloat(def, 32); err == nil {
- def = fmt.Sprint(float32(f))
- }
- case df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_DOUBLE:
- if f, err := strconv.ParseFloat(def, 64); err == nil {
- def = fmt.Sprint(f)
- }
- case df.getProtoType() == descriptor.FieldDescriptorProto_TYPE_ENUM:
- // Must be an enum. Need to construct the prefixed name.
- obj := g.ObjectNamed(df.getProtoTypeName())
- var enum *EnumDescriptor
- if id, ok := obj.(*ImportedDescriptor); ok {
- // The enum type has been publicly imported.
- enum, _ = id.o.(*EnumDescriptor)
- } else {
- enum, _ = obj.(*EnumDescriptor)
- }
- if enum == nil {
- log.Printf("don't know how to generate constant for %s", fieldname)
- continue
- }
- def = g.DefaultPackageName(obj) + enum.prefix() + def
- }
- g.P(kind, fieldname, " ", typename, " = ", def)
- g.file.addExport(mc.message, constOrVarSymbol{fieldname, kind, ""})
- }
- g.P()
-}
-
-// generateInternalStructFields just adds the XXX_<something> fields to the message struct.
-func (g *Generator) generateInternalStructFields(mc *msgCtx, topLevelFields []topLevelField) {
- g.P("XXX_NoUnkeyedLiteral\tstruct{} `json:\"-\"`") // prevent unkeyed struct literals
- if len(mc.message.ExtensionRange) > 0 {
- messageset := ""
- if opts := mc.message.Options; opts != nil && opts.GetMessageSetWireFormat() {
- messageset = "protobuf_messageset:\"1\" "
- }
- g.P(g.Pkg["proto"], ".XXX_InternalExtensions `", messageset, "json:\"-\"`")
- }
- g.P("XXX_unrecognized\t[]byte `json:\"-\"`")
- g.P("XXX_sizecache\tint32 `json:\"-\"`")
-
-}
-
-// generateOneofFuncs adds all the utility functions for oneof, including marshalling, unmarshalling and sizer.
-func (g *Generator) generateOneofFuncs(mc *msgCtx, topLevelFields []topLevelField) {
- ofields := []*oneofField{}
- for _, f := range topLevelFields {
- if o, ok := f.(*oneofField); ok {
- ofields = append(ofields, o)
- }
- }
- if len(ofields) == 0 {
- return
- }
-
- // OneofFuncs
- g.P("// XXX_OneofWrappers is for the internal use of the proto package.")
- g.P("func (*", mc.goName, ") XXX_OneofWrappers() []interface{} {")
- g.P("return []interface{}{")
- for _, of := range ofields {
- for _, sf := range of.subFields {
- sf.typedNil(g)
- }
- }
- g.P("}")
- g.P("}")
- g.P()
-}
-
-// generateMessageStruct adds the actual struct with it's members (but not methods) to the output.
-func (g *Generator) generateMessageStruct(mc *msgCtx, topLevelFields []topLevelField) {
- comments := g.PrintComments(mc.message.path)
-
- // Guarantee deprecation comments appear after user-provided comments.
- if mc.message.GetOptions().GetDeprecated() {
- if comments {
- // Convention: Separate deprecation comments from original
- // comments with an empty line.
- g.P("//")
- }
- g.P(deprecationComment)
- }
-
- g.P("type ", Annotate(mc.message.file, mc.message.path, mc.goName), " struct {")
- for _, pf := range topLevelFields {
- pf.decl(g, mc)
- }
- g.generateInternalStructFields(mc, topLevelFields)
- g.P("}")
-}
-
-// generateGetters adds getters for all fields, including oneofs and weak fields when applicable.
-func (g *Generator) generateGetters(mc *msgCtx, topLevelFields []topLevelField) {
- for _, pf := range topLevelFields {
- pf.getter(g, mc)
- }
-}
-
-// generateSetters add setters for all fields, including oneofs and weak fields when applicable.
-func (g *Generator) generateSetters(mc *msgCtx, topLevelFields []topLevelField) {
- for _, pf := range topLevelFields {
- pf.setter(g, mc)
- }
-}
-
-// generateCommonMethods adds methods to the message that are not on a per field basis.
-func (g *Generator) generateCommonMethods(mc *msgCtx) {
- // Reset, String and ProtoMessage methods.
- g.P("func (m *", mc.goName, ") Reset() { *m = ", mc.goName, "{} }")
- g.P("func (m *", mc.goName, ") String() string { return ", g.Pkg["proto"], ".CompactTextString(m) }")
- g.P("func (*", mc.goName, ") ProtoMessage() {}")
- var indexes []string
- for m := mc.message; m != nil; m = m.parent {
- indexes = append([]string{strconv.Itoa(m.index)}, indexes...)
- }
- g.P("func (*", mc.goName, ") Descriptor() ([]byte, []int) {")
- g.P("return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "}")
- g.P("}")
- g.P()
- // TODO: Revisit the decision to use a XXX_WellKnownType method
- // if we change proto.MessageName to work with multiple equivalents.
- if mc.message.file.GetPackage() == "google.protobuf" && wellKnownTypes[mc.message.GetName()] {
- g.P("func (*", mc.goName, `) XXX_WellKnownType() string { return "`, mc.message.GetName(), `" }`)
- g.P()
- }
-
- // Extension support methods
- if len(mc.message.ExtensionRange) > 0 {
- g.P()
- g.P("var extRange_", mc.goName, " = []", g.Pkg["proto"], ".ExtensionRange{")
- for _, r := range mc.message.ExtensionRange {
- end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends
- g.P("{Start: ", r.Start, ", End: ", end, "},")
- }
- g.P("}")
- g.P("func (*", mc.goName, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange {")
- g.P("return extRange_", mc.goName)
- g.P("}")
- g.P()
- }
-
- // TODO: It does not scale to keep adding another method for every
- // operation on protos that we want to switch over to using the
- // table-driven approach. Instead, we should only add a single method
- // that allows getting access to the *InternalMessageInfo struct and then
- // calling Unmarshal, Marshal, Merge, Size, and Discard directly on that.
-
- // Wrapper for table-driven marshaling and unmarshaling.
- g.P("func (m *", mc.goName, ") XXX_Unmarshal(b []byte) error {")
- g.P("return xxx_messageInfo_", mc.goName, ".Unmarshal(m, b)")
- g.P("}")
-
- g.P("func (m *", mc.goName, ") XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {")
- g.P("return xxx_messageInfo_", mc.goName, ".Marshal(b, m, deterministic)")
- g.P("}")
-
- g.P("func (m *", mc.goName, ") XXX_Merge(src ", g.Pkg["proto"], ".Message) {")
- g.P("xxx_messageInfo_", mc.goName, ".Merge(m, src)")
- g.P("}")
-
- g.P("func (m *", mc.goName, ") XXX_Size() int {") // avoid name clash with "Size" field in some message
- g.P("return xxx_messageInfo_", mc.goName, ".Size(m)")
- g.P("}")
-
- g.P("func (m *", mc.goName, ") XXX_DiscardUnknown() {")
- g.P("xxx_messageInfo_", mc.goName, ".DiscardUnknown(m)")
- g.P("}")
-
- g.P("var xxx_messageInfo_", mc.goName, " ", g.Pkg["proto"], ".InternalMessageInfo")
- g.P()
-}
-
-// Generate the type, methods and default constant definitions for this Descriptor.
-func (g *Generator) generateMessage(message *Descriptor) {
- topLevelFields := []topLevelField{}
- oFields := make(map[int32]*oneofField)
- // The full type name
- typeName := message.TypeName()
- // The full type name, CamelCased.
- goTypeName := CamelCaseSlice(typeName)
-
- usedNames := make(map[string]bool)
- for _, n := range methodNames {
- usedNames[n] = true
- }
-
- // allocNames finds a conflict-free variation of the given strings,
- // consistently mutating their suffixes.
- // It returns the same number of strings.
- allocNames := func(ns ...string) []string {
- Loop:
- for {
- for _, n := range ns {
- if usedNames[n] {
- for i := range ns {
- ns[i] += "_"
- }
- continue Loop
- }
- }
- for _, n := range ns {
- usedNames[n] = true
- }
- return ns
- }
- }
-
- mapFieldTypes := make(map[*descriptor.FieldDescriptorProto]string) // keep track of the map fields to be added later
-
- // Build a structure more suitable for generating the text in one pass
- for i, field := range message.Field {
- // Allocate the getter and the field at the same time so name
- // collisions create field/method consistent names.
- // TODO: This allocation occurs based on the order of the fields
- // in the proto file, meaning that a change in the field
- // ordering can change generated Method/Field names.
- base := CamelCase(*field.Name)
- ns := allocNames(base, "Get"+base)
- fieldName, fieldGetterName := ns[0], ns[1]
- typename, wiretype := g.GoType(message, field)
- jsonName := *field.Name
- tag := fmt.Sprintf("protobuf:%s json:%q", g.goTag(message, field, wiretype), jsonName+",omitempty")
-
- oneof := field.OneofIndex != nil
- if oneof && oFields[*field.OneofIndex] == nil {
- odp := message.OneofDecl[int(*field.OneofIndex)]
- base := CamelCase(odp.GetName())
- fname := allocNames(base)[0]
-
- // This is the first field of a oneof we haven't seen before.
- // Generate the union field.
- oneofFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageOneofPath, *field.OneofIndex)
- c, ok := g.makeComments(oneofFullPath)
- if ok {
- c += "\n//\n"
- }
- c += "// Types that are valid to be assigned to " + fname + ":\n"
- // Generate the rest of this comment later,
- // when we've computed any disambiguation.
-
- dname := "is" + goTypeName + "_" + fname
- tag := `protobuf_oneof:"` + odp.GetName() + `"`
- of := oneofField{
- fieldCommon: fieldCommon{
- goName: fname,
- getterName: "Get"+fname,
- goType: dname,
- tags: tag,
- protoName: odp.GetName(),
- fullPath: oneofFullPath,
- },
- comment: c,
- }
- topLevelFields = append(topLevelFields, &of)
- oFields[*field.OneofIndex] = &of
- }
-
- if *field.Type == descriptor.FieldDescriptorProto_TYPE_MESSAGE {
- desc := g.ObjectNamed(field.GetTypeName())
- if d, ok := desc.(*Descriptor); ok && d.GetOptions().GetMapEntry() {
- // Figure out the Go types and tags for the key and value types.
- keyField, valField := d.Field[0], d.Field[1]
- keyType, keyWire := g.GoType(d, keyField)
- valType, valWire := g.GoType(d, valField)
- keyTag, valTag := g.goTag(d, keyField, keyWire), g.goTag(d, valField, valWire)
-
- // We don't use stars, except for message-typed values.
- // Message and enum types are the only two possibly foreign types used in maps,
- // so record their use. They are not permitted as map keys.
- keyType = strings.TrimPrefix(keyType, "*")
- switch *valField.Type {
- case descriptor.FieldDescriptorProto_TYPE_ENUM:
- valType = strings.TrimPrefix(valType, "*")
- g.RecordTypeUse(valField.GetTypeName())
- case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
- g.RecordTypeUse(valField.GetTypeName())
- default:
- valType = strings.TrimPrefix(valType, "*")
- }
-
- typename = fmt.Sprintf("map[%s]%s", keyType, valType)
- mapFieldTypes[field] = typename // record for the getter generation
-
- tag += fmt.Sprintf(" protobuf_key:%s protobuf_val:%s", keyTag, valTag)
- }
- }
-
- fieldDeprecated := ""
- if field.GetOptions().GetDeprecated() {
- fieldDeprecated = deprecationComment
- }
-
- dvalue := g.getterDefault(field, goTypeName)
- if oneof {
- tname := goTypeName + "_" + fieldName
- // It is possible for this to collide with a message or enum
- // nested in this message. Check for collisions.
- for {
- ok := true
- for _, desc := range message.nested {
- if CamelCaseSlice(desc.TypeName()) == tname {
- ok = false
- break
- }
- }
- for _, enum := range message.enums {
- if CamelCaseSlice(enum.TypeName()) == tname {
- ok = false
- break
- }
- }
- if !ok {
- tname += "_"
- continue
- }
- break
- }
-
- oneofField := oFields[*field.OneofIndex]
- tag := "protobuf:" + g.goTag(message, field, wiretype)
- sf := oneofSubField{
- fieldCommon: fieldCommon{
- goName: fieldName,
- getterName: fieldGetterName,
- goType: typename,
- tags: tag,
- protoName: field.GetName(),
- fullPath: fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i),
- },
- protoTypeName: field.GetTypeName(),
- fieldNumber: int(*field.Number),
- protoType: *field.Type,
- getterDef: dvalue,
- protoDef: field.GetDefaultValue(),
- oneofTypeName: tname,
- deprecated: fieldDeprecated,
- }
- oneofField.subFields = append(oneofField.subFields, &sf)
- g.RecordTypeUse(field.GetTypeName())
- continue
- }
-
- fieldFullPath := fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i)
- c, ok := g.makeComments(fieldFullPath)
- if ok {
- c += "\n"
- }
- rf := simpleField{
- fieldCommon: fieldCommon{
- goName: fieldName,
- getterName: fieldGetterName,
- goType: typename,
- tags: tag,
- protoName: field.GetName(),
- fullPath: fieldFullPath,
- },
- protoTypeName: field.GetTypeName(),
- protoType: *field.Type,
- deprecated: fieldDeprecated,
- getterDef: dvalue,
- protoDef: field.GetDefaultValue(),
- comment: c,
- }
- var pf topLevelField = &rf
-
- topLevelFields = append(topLevelFields, pf)
- g.RecordTypeUse(field.GetTypeName())
- }
-
- mc := &msgCtx{
- goName: goTypeName,
- message: message,
- }
-
- g.generateMessageStruct(mc, topLevelFields)
- g.P()
- g.generateCommonMethods(mc)
- g.P()
- g.generateDefaultConstants(mc, topLevelFields)
- g.P()
- g.generateGetters(mc, topLevelFields)
- g.P()
- g.generateSetters(mc, topLevelFields)
- g.P()
- g.generateOneofFuncs(mc, topLevelFields)
- g.P()
-
- var oneofTypes []string
- for _, f := range topLevelFields {
- if of, ok := f.(*oneofField); ok {
- for _, osf := range of.subFields {
- oneofTypes = append(oneofTypes, osf.oneofTypeName)
- }
- }
- }
-
- opts := message.Options
- ms := &messageSymbol{
- sym: goTypeName,
- hasExtensions: len(message.ExtensionRange) > 0,
- isMessageSet: opts != nil && opts.GetMessageSetWireFormat(),
- oneofTypes: oneofTypes,
- }
- g.file.addExport(message, ms)
-
- for _, ext := range message.ext {
- g.generateExtension(ext)
- }
-
- fullName := strings.Join(message.TypeName(), ".")
- if g.file.Package != nil {
- fullName = *g.file.Package + "." + fullName
- }
-
- g.addInitf("%s.RegisterType((*%s)(nil), %q)", g.Pkg["proto"], goTypeName, fullName)
- // Register types for native map types.
- for _, k := range mapFieldKeys(mapFieldTypes) {
- fullName := strings.TrimPrefix(*k.TypeName, ".")
- g.addInitf("%s.RegisterMapType((%s)(nil), %q)", g.Pkg["proto"], mapFieldTypes[k], fullName)
- }
-
-}
-
-type byTypeName []*descriptor.FieldDescriptorProto
-
-func (a byTypeName) Len() int { return len(a) }
-func (a byTypeName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
-func (a byTypeName) Less(i, j int) bool { return *a[i].TypeName < *a[j].TypeName }
-
-// mapFieldKeys returns the keys of m in a consistent order.
-func mapFieldKeys(m map[*descriptor.FieldDescriptorProto]string) []*descriptor.FieldDescriptorProto {
- keys := make([]*descriptor.FieldDescriptorProto, 0, len(m))
- for k := range m {
- keys = append(keys, k)
- }
- sort.Sort(byTypeName(keys))
- return keys
-}
-
-var escapeChars = [256]byte{
- 'a': '\a', 'b': '\b', 'f': '\f', 'n': '\n', 'r': '\r', 't': '\t', 'v': '\v', '\\': '\\', '"': '"', '\'': '\'', '?': '?',
-}
-
-// unescape reverses the "C" escaping that protoc does for default values of bytes fields.
-// It is best effort in that it effectively ignores malformed input. Seemingly invalid escape
-// sequences are conveyed, unmodified, into the decoded result.
-func unescape(s string) string {
- // NB: Sadly, we can't use strconv.Unquote because protoc will escape both
- // single and double quotes, but strconv.Unquote only allows one or the
- // other (based on actual surrounding quotes of its input argument).
-
- var out []byte
- for len(s) > 0 {
- // regular character, or too short to be valid escape
- if s[0] != '\\' || len(s) < 2 {
- out = append(out, s[0])
- s = s[1:]
- } else if c := escapeChars[s[1]]; c != 0 {
- // escape sequence
- out = append(out, c)
- s = s[2:]
- } else if s[1] == 'x' || s[1] == 'X' {
- // hex escape, e.g. "\x80
- if len(s) < 4 {
- // too short to be valid
- out = append(out, s[:2]...)
- s = s[2:]
- continue
- }
- v, err := strconv.ParseUint(s[2:4], 16, 8)
- if err != nil {
- out = append(out, s[:4]...)
- } else {
- out = append(out, byte(v))
- }
- s = s[4:]
- } else if '0' <= s[1] && s[1] <= '7' {
- // octal escape, can vary from 1 to 3 octal digits; e.g., "\0" "\40" or "\164"
- // so consume up to 2 more bytes or up to end-of-string
- n := len(s[1:]) - len(strings.TrimLeft(s[1:], "01234567"))
- if n > 3 {
- n = 3
- }
- v, err := strconv.ParseUint(s[1:1+n], 8, 8)
- if err != nil {
- out = append(out, s[:1+n]...)
- } else {
- out = append(out, byte(v))
- }
- s = s[1+n:]
- } else {
- // bad escape, just propagate the slash as-is
- out = append(out, s[0])
- s = s[1:]
- }
- }
-
- return string(out)
-}
-
-func (g *Generator) generateExtension(ext *ExtensionDescriptor) {
- ccTypeName := ext.DescName()
-
- extObj := g.ObjectNamed(*ext.Extendee)
- var extDesc *Descriptor
- if id, ok := extObj.(*ImportedDescriptor); ok {
- // This is extending a publicly imported message.
- // We need the underlying type for goTag.
- extDesc = id.o.(*Descriptor)
- } else {
- extDesc = extObj.(*Descriptor)
- }
- extendedType := "*" + g.TypeName(extObj) // always use the original
- field := ext.FieldDescriptorProto
- fieldType, wireType := g.GoType(ext.parent, field)
- tag := g.goTag(extDesc, field, wireType)
- g.RecordTypeUse(*ext.Extendee)
- if n := ext.FieldDescriptorProto.TypeName; n != nil {
- // foreign extension type
- g.RecordTypeUse(*n)
- }
-
- typeName := ext.TypeName()
-
- // Special case for proto2 message sets: If this extension is extending
- // proto2.bridge.MessageSet, and its final name component is "message_set_extension",
- // then drop that last component.
- //
- // TODO: This should be implemented in the text formatter rather than the generator.
- // In addition, the situation for when to apply this special case is implemented
- // differently in other languages:
- // https://github.com/google/protobuf/blob/aff10976/src/google/protobuf/text_format.cc#L1560
- if extDesc.GetOptions().GetMessageSetWireFormat() && typeName[len(typeName)-1] == "message_set_extension" {
- typeName = typeName[:len(typeName)-1]
- }
-
- // For text formatting, the package must be exactly what the .proto file declares,
- // ignoring overrides such as the go_package option, and with no dot/underscore mapping.
- extName := strings.Join(typeName, ".")
- if g.file.Package != nil {
- extName = *g.file.Package + "." + extName
- }
-
- g.P("var ", ccTypeName, " = &", g.Pkg["proto"], ".ExtensionDesc{")
- g.P("ExtendedType: (", extendedType, ")(nil),")
- g.P("ExtensionType: (", fieldType, ")(nil),")
- g.P("Field: ", field.Number, ",")
- g.P(`Name: "`, extName, `",`)
- g.P("Tag: ", tag, ",")
- g.P(`Filename: "`, g.file.GetName(), `",`)
-
- g.P("}")
- g.P()
-
- g.addInitf("%s.RegisterExtension(%s)", g.Pkg["proto"], ext.DescName())
-
- g.file.addExport(ext, constOrVarSymbol{ccTypeName, "var", ""})
-}
-
-func (g *Generator) generateInitFunction() {
- if len(g.init) == 0 {
- return
- }
- g.P("func init() {")
- for _, l := range g.init {
- g.P(l)
- }
- g.P("}")
- g.init = nil
-}
-
-func (g *Generator) generateFileDescriptor(file *FileDescriptor) {
- // Make a copy and trim source_code_info data.
- // TODO: Trim this more when we know exactly what we need.
- pb := proto.Clone(file.FileDescriptorProto).(*descriptor.FileDescriptorProto)
- pb.SourceCodeInfo = nil
-
- b, err := proto.Marshal(pb)
- if err != nil {
- g.Fail(err.Error())
- }
-
- var buf bytes.Buffer
- w, _ := gzip.NewWriterLevel(&buf, gzip.BestCompression)
- w.Write(b)
- w.Close()
- b = buf.Bytes()
-
- v := file.VarName()
- g.P()
- g.P("func init() { ", g.Pkg["proto"], ".RegisterFile(", strconv.Quote(*file.Name), ", ", v, ") }")
- g.P("var ", v, " = []byte{")
- g.P("// ", len(b), " bytes of a gzipped FileDescriptorProto")
- for len(b) > 0 {
- n := 16
- if n > len(b) {
- n = len(b)
- }
-
- s := ""
- for _, c := range b[:n] {
- s += fmt.Sprintf("0x%02x,", c)
- }
- g.P(s)
-
- b = b[n:]
- }
- g.P("}")
-}
-
-func (g *Generator) generateEnumRegistration(enum *EnumDescriptor) {
- // // We always print the full (proto-world) package name here.
- pkg := enum.File().GetPackage()
- if pkg != "" {
- pkg += "."
- }
- // The full type name
- typeName := enum.TypeName()
- // The full type name, CamelCased.
- ccTypeName := CamelCaseSlice(typeName)
- g.addInitf("%s.RegisterEnum(%q, %[3]s_name, %[3]s_value)", g.Pkg["proto"], pkg+ccTypeName, ccTypeName)
-}
-
-// And now lots of helper functions.
-
-// Is c an ASCII lower-case letter?
-func isASCIILower(c byte) bool {
- return 'a' <= c && c <= 'z'
-}
-
-// Is c an ASCII digit?
-func isASCIIDigit(c byte) bool {
- return '0' <= c && c <= '9'
-}
-
-// CamelCase returns the CamelCased name.
-// If there is an interior underscore followed by a lower case letter,
-// drop the underscore and convert the letter to upper case.
-// There is a remote possibility of this rewrite causing a name collision,
-// but it's so remote we're prepared to pretend it's nonexistent - since the
-// C++ generator lowercases names, it's extremely unlikely to have two fields
-// with different capitalizations.
-// In short, _my_field_name_2 becomes XMyFieldName_2.
-func CamelCase(s string) string {
- if s == "" {
- return ""
- }
- t := make([]byte, 0, 32)
- i := 0
- if s[0] == '_' {
- // Need a capital letter; drop the '_'.
- t = append(t, 'X')
- i++
- }
- // Invariant: if the next letter is lower case, it must be converted
- // to upper case.
- // That is, we process a word at a time, where words are marked by _ or
- // upper case letter. Digits are treated as words.
- for ; i < len(s); i++ {
- c := s[i]
- if c == '_' && i+1 < len(s) && isASCIILower(s[i+1]) {
- continue // Skip the underscore in s.
- }
- if isASCIIDigit(c) {
- t = append(t, c)
- continue
- }
- // Assume we have a letter now - if not, it's a bogus identifier.
- // The next word is a sequence of characters that must start upper case.
- if isASCIILower(c) {
- c ^= ' ' // Make it a capital letter.
- }
- t = append(t, c) // Guaranteed not lower case.
- // Accept lower case sequence that follows.
- for i+1 < len(s) && isASCIILower(s[i+1]) {
- i++
- t = append(t, s[i])
- }
- }
- return string(t)
-}
-
-// CamelCaseSlice is like CamelCase, but the argument is a slice of strings to
-// be joined with "_".
-func CamelCaseSlice(elem []string) string { return CamelCase(strings.Join(elem, "_")) }
-
-// dottedSlice turns a sliced name into a dotted name.
-func dottedSlice(elem []string) string { return strings.Join(elem, ".") }
-
-// Is this field optional?
-func isOptional(field *descriptor.FieldDescriptorProto) bool {
- return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_OPTIONAL
-}
-
-// Is this field required?
-func isRequired(field *descriptor.FieldDescriptorProto) bool {
- return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REQUIRED
-}
-
-// Is this field repeated?
-func isRepeated(field *descriptor.FieldDescriptorProto) bool {
- return field.Label != nil && *field.Label == descriptor.FieldDescriptorProto_LABEL_REPEATED
-}
-
-// Is this field a scalar numeric type?
-func isScalar(field *descriptor.FieldDescriptorProto) bool {
- if field.Type == nil {
- return false
- }
- switch *field.Type {
- case descriptor.FieldDescriptorProto_TYPE_DOUBLE,
- descriptor.FieldDescriptorProto_TYPE_FLOAT,
- descriptor.FieldDescriptorProto_TYPE_INT64,
- descriptor.FieldDescriptorProto_TYPE_UINT64,
- descriptor.FieldDescriptorProto_TYPE_INT32,
- descriptor.FieldDescriptorProto_TYPE_FIXED64,
- descriptor.FieldDescriptorProto_TYPE_FIXED32,
- descriptor.FieldDescriptorProto_TYPE_BOOL,
- descriptor.FieldDescriptorProto_TYPE_UINT32,
- descriptor.FieldDescriptorProto_TYPE_ENUM,
- descriptor.FieldDescriptorProto_TYPE_SFIXED32,
- descriptor.FieldDescriptorProto_TYPE_SFIXED64,
- descriptor.FieldDescriptorProto_TYPE_SINT32,
- descriptor.FieldDescriptorProto_TYPE_SINT64:
- return true
- default:
- return false
- }
-}
-
-// badToUnderscore is the mapping function used to generate Go names from package names,
-// which can be dotted in the input .proto file. It replaces non-identifier characters such as
-// dot or dash with underscore.
-func badToUnderscore(r rune) rune {
- if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' {
- return r
- }
- return '_'
-}
-
-// baseName returns the last path element of the name, with the last dotted suffix removed.
-func baseName(name string) string {
- // First, find the last element
- if i := strings.LastIndex(name, "/"); i >= 0 {
- name = name[i+1:]
- }
- // Now drop the suffix
- if i := strings.LastIndex(name, "."); i >= 0 {
- name = name[0:i]
- }
- return name
-}
-
-// The SourceCodeInfo message describes the location of elements of a parsed
-// .proto file by way of a "path", which is a sequence of integers that
-// describe the route from a FileDescriptorProto to the relevant submessage.
-// The path alternates between a field number of a repeated field, and an index
-// into that repeated field. The constants below define the field numbers that
-// are used.
-//
-// See descriptor.proto for more information about this.
-const (
- // tag numbers in FileDescriptorProto
- packagePath = 2 // package
- messagePath = 4 // message_type
- enumPath = 5 // enum_type
- // tag numbers in DescriptorProto
- messageFieldPath = 2 // field
- messageMessagePath = 3 // nested_type
- messageEnumPath = 4 // enum_type
- messageOneofPath = 8 // oneof_decl
- // tag numbers in EnumDescriptorProto
- enumValuePath = 2 // value
-)
-
-var supportTypeAliases bool
-
-func init() {
- for _, tag := range build.Default.ReleaseTags {
- if tag == "go1.9" {
- supportTypeAliases = true
- return
- }
- }
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap.go b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap.go
deleted file mode 100644
index a9b6103..0000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/generator/internal/remap/remap.go
+++ /dev/null
@@ -1,117 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2017 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-/*
-Package remap handles tracking the locations of Go tokens in a source text
-across a rewrite by the Go formatter.
-*/
-package remap
-
-import (
- "fmt"
- "go/scanner"
- "go/token"
-)
-
-// A Location represents a span of byte offsets in the source text.
-type Location struct {
- Pos, End int // End is exclusive
-}
-
-// A Map represents a mapping between token locations in an input source text
-// and locations in the correspnding output text.
-type Map map[Location]Location
-
-// Find reports whether the specified span is recorded by m, and if so returns
-// the new location it was mapped to. If the input span was not found, the
-// returned location is the same as the input.
-func (m Map) Find(pos, end int) (Location, bool) {
- key := Location{
- Pos: pos,
- End: end,
- }
- if loc, ok := m[key]; ok {
- return loc, true
- }
- return key, false
-}
-
-func (m Map) add(opos, oend, npos, nend int) {
- m[Location{Pos: opos, End: oend}] = Location{Pos: npos, End: nend}
-}
-
-// Compute constructs a location mapping from input to output. An error is
-// reported if any of the tokens of output cannot be mapped.
-func Compute(input, output []byte) (Map, error) {
- itok := tokenize(input)
- otok := tokenize(output)
- if len(itok) != len(otok) {
- return nil, fmt.Errorf("wrong number of tokens, %d ≠ %d", len(itok), len(otok))
- }
- m := make(Map)
- for i, ti := range itok {
- to := otok[i]
- if ti.Token != to.Token {
- return nil, fmt.Errorf("token %d type mismatch: %s ≠ %s", i+1, ti, to)
- }
- m.add(ti.pos, ti.end, to.pos, to.end)
- }
- return m, nil
-}
-
-// tokinfo records the span and type of a source token.
-type tokinfo struct {
- pos, end int
- token.Token
-}
-
-func tokenize(src []byte) []tokinfo {
- fs := token.NewFileSet()
- var s scanner.Scanner
- s.Init(fs.AddFile("src", fs.Base(), len(src)), src, nil, scanner.ScanComments)
- var info []tokinfo
- for {
- pos, next, lit := s.Scan()
- switch next {
- case token.SEMICOLON:
- continue
- }
- info = append(info, tokinfo{
- pos: int(pos - 1),
- end: int(pos + token.Pos(len(lit)) - 1),
- Token: next,
- })
- if next == token.EOF {
- break
- }
- }
- return info
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go b/vendor/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go
deleted file mode 100644
index 5d1e3f0..0000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go
+++ /dev/null
@@ -1,537 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2015 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Package grpc outputs gRPC service descriptions in Go code.
-// It runs as a plugin for the Go protocol buffer compiler plugin.
-// It is linked in to protoc-gen-go.
-package grpc
-
-import (
- "fmt"
- "strconv"
- "strings"
-
- pb "github.com/golang/protobuf/protoc-gen-go/descriptor"
- "github.com/golang/protobuf/protoc-gen-go/generator"
-)
-
-// generatedCodeVersion indicates a version of the generated code.
-// It is incremented whenever an incompatibility between the generated code and
-// the grpc package is introduced; the generated code references
-// a constant, grpc.SupportPackageIsVersionN (where N is generatedCodeVersion).
-const generatedCodeVersion = 4
-
-// Paths for packages used by code generated in this file,
-// relative to the import_prefix of the generator.Generator.
-const (
- contextPkgPath = "context"
- grpcPkgPath = "google.golang.org/grpc"
- codePkgPath = "google.golang.org/grpc/codes"
- statusPkgPath = "google.golang.org/grpc/status"
-)
-
-func init() {
- generator.RegisterPlugin(new(grpc))
-}
-
-// grpc is an implementation of the Go protocol buffer compiler's
-// plugin architecture. It generates bindings for gRPC support.
-type grpc struct {
- gen *generator.Generator
-}
-
-// Name returns the name of this plugin, "grpc".
-func (g *grpc) Name() string {
- return "grpc"
-}
-
-// The names for packages imported in the generated code.
-// They may vary from the final path component of the import path
-// if the name is used by other packages.
-var (
- contextPkg string
- grpcPkg string
-)
-
-// Init initializes the plugin.
-func (g *grpc) Init(gen *generator.Generator) {
- g.gen = gen
-}
-
-// Given a type name defined in a .proto, return its object.
-// Also record that we're using it, to guarantee the associated import.
-func (g *grpc) objectNamed(name string) generator.Object {
- g.gen.RecordTypeUse(name)
- return g.gen.ObjectNamed(name)
-}
-
-// Given a type name defined in a .proto, return its name as we will print it.
-func (g *grpc) typeName(str string) string {
- return g.gen.TypeName(g.objectNamed(str))
-}
-
-// P forwards to g.gen.P.
-func (g *grpc) P(args ...interface{}) { g.gen.P(args...) }
-
-// Generate generates code for the services in the given file.
-func (g *grpc) Generate(file *generator.FileDescriptor) {
- if len(file.FileDescriptorProto.Service) == 0 {
- return
- }
-
- contextPkg = string(g.gen.AddImport(contextPkgPath))
- grpcPkg = string(g.gen.AddImport(grpcPkgPath))
-
- g.P("// Reference imports to suppress errors if they are not otherwise used.")
- g.P("var _ ", contextPkg, ".Context")
- g.P("var _ ", grpcPkg, ".ClientConn")
- g.P()
-
- // Assert version compatibility.
- g.P("// This is a compile-time assertion to ensure that this generated file")
- g.P("// is compatible with the grpc package it is being compiled against.")
- g.P("const _ = ", grpcPkg, ".SupportPackageIsVersion", generatedCodeVersion)
- g.P()
-
- for i, service := range file.FileDescriptorProto.Service {
- g.generateService(file, service, i)
- }
-}
-
-// GenerateImports generates the import declaration for this file.
-func (g *grpc) GenerateImports(file *generator.FileDescriptor) {
-}
-
-// reservedClientName records whether a client name is reserved on the client side.
-var reservedClientName = map[string]bool{
- // TODO: do we need any in gRPC?
-}
-
-func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] }
-
-// deprecationComment is the standard comment added to deprecated
-// messages, fields, enums, and enum values.
-var deprecationComment = "// Deprecated: Do not use."
-
-// generateService generates all the code for the named service.
-func (g *grpc) generateService(file *generator.FileDescriptor, service *pb.ServiceDescriptorProto, index int) {
- path := fmt.Sprintf("6,%d", index) // 6 means service.
-
- origServName := service.GetName()
- fullServName := origServName
- if pkg := file.GetPackage(); pkg != "" {
- fullServName = pkg + "." + fullServName
- }
- servName := generator.CamelCase(origServName)
- deprecated := service.GetOptions().GetDeprecated()
-
- g.P()
- g.P(fmt.Sprintf(`// %sClient is the client API for %s service.
-//
-// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.`, servName, servName))
-
- // Client interface.
- if deprecated {
- g.P("//")
- g.P(deprecationComment)
- }
- g.P("type ", servName, "Client interface {")
- for i, method := range service.Method {
- g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
- g.P(g.generateClientSignature(servName, method))
- }
- g.P("}")
- g.P()
-
- // Client structure.
- g.P("type ", unexport(servName), "Client struct {")
- g.P("cc *", grpcPkg, ".ClientConn")
- g.P("}")
- g.P()
-
- // NewClient factory.
- if deprecated {
- g.P(deprecationComment)
- }
- g.P("func New", servName, "Client (cc *", grpcPkg, ".ClientConn) ", servName, "Client {")
- g.P("return &", unexport(servName), "Client{cc}")
- g.P("}")
- g.P()
-
- var methodIndex, streamIndex int
- serviceDescVar := "_" + servName + "_serviceDesc"
- // Client method implementations.
- for _, method := range service.Method {
- var descExpr string
- if !method.GetServerStreaming() && !method.GetClientStreaming() {
- // Unary RPC method
- descExpr = fmt.Sprintf("&%s.Methods[%d]", serviceDescVar, methodIndex)
- methodIndex++
- } else {
- // Streaming RPC method
- descExpr = fmt.Sprintf("&%s.Streams[%d]", serviceDescVar, streamIndex)
- streamIndex++
- }
- g.generateClientMethod(servName, fullServName, serviceDescVar, method, descExpr)
- }
-
- // Server interface.
- serverType := servName + "Server"
- g.P("// ", serverType, " is the server API for ", servName, " service.")
- if deprecated {
- g.P("//")
- g.P(deprecationComment)
- }
- g.P("type ", serverType, " interface {")
- for i, method := range service.Method {
- g.gen.PrintComments(fmt.Sprintf("%s,2,%d", path, i)) // 2 means method in a service.
- g.P(g.generateServerSignature(servName, method))
- }
- g.P("}")
- g.P()
-
- // Server Unimplemented struct for forward compatability.
- if deprecated {
- g.P(deprecationComment)
- }
- g.generateUnimplementedServer(servName, service)
-
- // Server registration.
- if deprecated {
- g.P(deprecationComment)
- }
- g.P("func Register", servName, "Server(s *", grpcPkg, ".Server, srv ", serverType, ") {")
- g.P("s.RegisterService(&", serviceDescVar, `, srv)`)
- g.P("}")
- g.P()
-
- // Server handler implementations.
- var handlerNames []string
- for _, method := range service.Method {
- hname := g.generateServerMethod(servName, fullServName, method)
- handlerNames = append(handlerNames, hname)
- }
-
- // Service descriptor.
- g.P("var ", serviceDescVar, " = ", grpcPkg, ".ServiceDesc {")
- g.P("ServiceName: ", strconv.Quote(fullServName), ",")
- g.P("HandlerType: (*", serverType, ")(nil),")
- g.P("Methods: []", grpcPkg, ".MethodDesc{")
- for i, method := range service.Method {
- if method.GetServerStreaming() || method.GetClientStreaming() {
- continue
- }
- g.P("{")
- g.P("MethodName: ", strconv.Quote(method.GetName()), ",")
- g.P("Handler: ", handlerNames[i], ",")
- g.P("},")
- }
- g.P("},")
- g.P("Streams: []", grpcPkg, ".StreamDesc{")
- for i, method := range service.Method {
- if !method.GetServerStreaming() && !method.GetClientStreaming() {
- continue
- }
- g.P("{")
- g.P("StreamName: ", strconv.Quote(method.GetName()), ",")
- g.P("Handler: ", handlerNames[i], ",")
- if method.GetServerStreaming() {
- g.P("ServerStreams: true,")
- }
- if method.GetClientStreaming() {
- g.P("ClientStreams: true,")
- }
- g.P("},")
- }
- g.P("},")
- g.P("Metadata: \"", file.GetName(), "\",")
- g.P("}")
- g.P()
-}
-
-// generateUnimplementedServer creates the unimplemented server struct
-func (g *grpc) generateUnimplementedServer(servName string, service *pb.ServiceDescriptorProto) {
- serverType := servName + "Server"
- g.P("// Unimplemented", serverType, " can be embedded to have forward compatible implementations.")
- g.P("type Unimplemented", serverType, " struct {")
- g.P("}")
- g.P()
- // Unimplemented<service_name>Server's concrete methods
- for _, method := range service.Method {
- g.generateServerMethodConcrete(servName, method)
- }
- g.P()
-}
-
-// generateServerMethodConcrete returns unimplemented methods which ensure forward compatibility
-func (g *grpc) generateServerMethodConcrete(servName string, method *pb.MethodDescriptorProto) {
- header := g.generateServerSignatureWithParamNames(servName, method)
- g.P("func (*Unimplemented", servName, "Server) ", header, " {")
- var nilArg string
- if !method.GetServerStreaming() && !method.GetClientStreaming() {
- nilArg = "nil, "
- }
- methName := generator.CamelCase(method.GetName())
- statusPkg := string(g.gen.AddImport(statusPkgPath))
- codePkg := string(g.gen.AddImport(codePkgPath))
- g.P("return ", nilArg, statusPkg, `.Errorf(`, codePkg, `.Unimplemented, "method `, methName, ` not implemented")`)
- g.P("}")
-}
-
-// generateClientSignature returns the client-side signature for a method.
-func (g *grpc) generateClientSignature(servName string, method *pb.MethodDescriptorProto) string {
- origMethName := method.GetName()
- methName := generator.CamelCase(origMethName)
- if reservedClientName[methName] {
- methName += "_"
- }
- reqArg := ", in *" + g.typeName(method.GetInputType())
- if method.GetClientStreaming() {
- reqArg = ""
- }
- respName := "*" + g.typeName(method.GetOutputType())
- if method.GetServerStreaming() || method.GetClientStreaming() {
- respName = servName + "_" + generator.CamelCase(origMethName) + "Client"
- }
- return fmt.Sprintf("%s(ctx %s.Context%s, opts ...%s.CallOption) (%s, error)", methName, contextPkg, reqArg, grpcPkg, respName)
-}
-
-func (g *grpc) generateClientMethod(servName, fullServName, serviceDescVar string, method *pb.MethodDescriptorProto, descExpr string) {
- sname := fmt.Sprintf("/%s/%s", fullServName, method.GetName())
- methName := generator.CamelCase(method.GetName())
- inType := g.typeName(method.GetInputType())
- outType := g.typeName(method.GetOutputType())
-
- if method.GetOptions().GetDeprecated() {
- g.P(deprecationComment)
- }
- g.P("func (c *", unexport(servName), "Client) ", g.generateClientSignature(servName, method), "{")
- if !method.GetServerStreaming() && !method.GetClientStreaming() {
- g.P("out := new(", outType, ")")
- // TODO: Pass descExpr to Invoke.
- g.P(`err := c.cc.Invoke(ctx, "`, sname, `", in, out, opts...)`)
- g.P("if err != nil { return nil, err }")
- g.P("return out, nil")
- g.P("}")
- g.P()
- return
- }
- streamType := unexport(servName) + methName + "Client"
- g.P("stream, err := c.cc.NewStream(ctx, ", descExpr, `, "`, sname, `", opts...)`)
- g.P("if err != nil { return nil, err }")
- g.P("x := &", streamType, "{stream}")
- if !method.GetClientStreaming() {
- g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }")
- g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
- }
- g.P("return x, nil")
- g.P("}")
- g.P()
-
- genSend := method.GetClientStreaming()
- genRecv := method.GetServerStreaming()
- genCloseAndRecv := !method.GetServerStreaming()
-
- // Stream auxiliary types and methods.
- g.P("type ", servName, "_", methName, "Client interface {")
- if genSend {
- g.P("Send(*", inType, ") error")
- }
- if genRecv {
- g.P("Recv() (*", outType, ", error)")
- }
- if genCloseAndRecv {
- g.P("CloseAndRecv() (*", outType, ", error)")
- }
- g.P(grpcPkg, ".ClientStream")
- g.P("}")
- g.P()
-
- g.P("type ", streamType, " struct {")
- g.P(grpcPkg, ".ClientStream")
- g.P("}")
- g.P()
-
- if genSend {
- g.P("func (x *", streamType, ") Send(m *", inType, ") error {")
- g.P("return x.ClientStream.SendMsg(m)")
- g.P("}")
- g.P()
- }
- if genRecv {
- g.P("func (x *", streamType, ") Recv() (*", outType, ", error) {")
- g.P("m := new(", outType, ")")
- g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
- g.P("return m, nil")
- g.P("}")
- g.P()
- }
- if genCloseAndRecv {
- g.P("func (x *", streamType, ") CloseAndRecv() (*", outType, ", error) {")
- g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }")
- g.P("m := new(", outType, ")")
- g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }")
- g.P("return m, nil")
- g.P("}")
- g.P()
- }
-}
-
-// generateServerSignatureWithParamNames returns the server-side signature for a method with parameter names.
-func (g *grpc) generateServerSignatureWithParamNames(servName string, method *pb.MethodDescriptorProto) string {
- origMethName := method.GetName()
- methName := generator.CamelCase(origMethName)
- if reservedClientName[methName] {
- methName += "_"
- }
-
- var reqArgs []string
- ret := "error"
- if !method.GetServerStreaming() && !method.GetClientStreaming() {
- reqArgs = append(reqArgs, "ctx "+contextPkg+".Context")
- ret = "(*" + g.typeName(method.GetOutputType()) + ", error)"
- }
- if !method.GetClientStreaming() {
- reqArgs = append(reqArgs, "req *"+g.typeName(method.GetInputType()))
- }
- if method.GetServerStreaming() || method.GetClientStreaming() {
- reqArgs = append(reqArgs, "srv "+servName+"_"+generator.CamelCase(origMethName)+"Server")
- }
-
- return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret
-}
-
-// generateServerSignature returns the server-side signature for a method.
-func (g *grpc) generateServerSignature(servName string, method *pb.MethodDescriptorProto) string {
- origMethName := method.GetName()
- methName := generator.CamelCase(origMethName)
- if reservedClientName[methName] {
- methName += "_"
- }
-
- var reqArgs []string
- ret := "error"
- if !method.GetServerStreaming() && !method.GetClientStreaming() {
- reqArgs = append(reqArgs, contextPkg+".Context")
- ret = "(*" + g.typeName(method.GetOutputType()) + ", error)"
- }
- if !method.GetClientStreaming() {
- reqArgs = append(reqArgs, "*"+g.typeName(method.GetInputType()))
- }
- if method.GetServerStreaming() || method.GetClientStreaming() {
- reqArgs = append(reqArgs, servName+"_"+generator.CamelCase(origMethName)+"Server")
- }
-
- return methName + "(" + strings.Join(reqArgs, ", ") + ") " + ret
-}
-
-func (g *grpc) generateServerMethod(servName, fullServName string, method *pb.MethodDescriptorProto) string {
- methName := generator.CamelCase(method.GetName())
- hname := fmt.Sprintf("_%s_%s_Handler", servName, methName)
- inType := g.typeName(method.GetInputType())
- outType := g.typeName(method.GetOutputType())
-
- if !method.GetServerStreaming() && !method.GetClientStreaming() {
- g.P("func ", hname, "(srv interface{}, ctx ", contextPkg, ".Context, dec func(interface{}) error, interceptor ", grpcPkg, ".UnaryServerInterceptor) (interface{}, error) {")
- g.P("in := new(", inType, ")")
- g.P("if err := dec(in); err != nil { return nil, err }")
- g.P("if interceptor == nil { return srv.(", servName, "Server).", methName, "(ctx, in) }")
- g.P("info := &", grpcPkg, ".UnaryServerInfo{")
- g.P("Server: srv,")
- g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", fullServName, methName)), ",")
- g.P("}")
- g.P("handler := func(ctx ", contextPkg, ".Context, req interface{}) (interface{}, error) {")
- g.P("return srv.(", servName, "Server).", methName, "(ctx, req.(*", inType, "))")
- g.P("}")
- g.P("return interceptor(ctx, in, info, handler)")
- g.P("}")
- g.P()
- return hname
- }
- streamType := unexport(servName) + methName + "Server"
- g.P("func ", hname, "(srv interface{}, stream ", grpcPkg, ".ServerStream) error {")
- if !method.GetClientStreaming() {
- g.P("m := new(", inType, ")")
- g.P("if err := stream.RecvMsg(m); err != nil { return err }")
- g.P("return srv.(", servName, "Server).", methName, "(m, &", streamType, "{stream})")
- } else {
- g.P("return srv.(", servName, "Server).", methName, "(&", streamType, "{stream})")
- }
- g.P("}")
- g.P()
-
- genSend := method.GetServerStreaming()
- genSendAndClose := !method.GetServerStreaming()
- genRecv := method.GetClientStreaming()
-
- // Stream auxiliary types and methods.
- g.P("type ", servName, "_", methName, "Server interface {")
- if genSend {
- g.P("Send(*", outType, ") error")
- }
- if genSendAndClose {
- g.P("SendAndClose(*", outType, ") error")
- }
- if genRecv {
- g.P("Recv() (*", inType, ", error)")
- }
- g.P(grpcPkg, ".ServerStream")
- g.P("}")
- g.P()
-
- g.P("type ", streamType, " struct {")
- g.P(grpcPkg, ".ServerStream")
- g.P("}")
- g.P()
-
- if genSend {
- g.P("func (x *", streamType, ") Send(m *", outType, ") error {")
- g.P("return x.ServerStream.SendMsg(m)")
- g.P("}")
- g.P()
- }
- if genSendAndClose {
- g.P("func (x *", streamType, ") SendAndClose(m *", outType, ") error {")
- g.P("return x.ServerStream.SendMsg(m)")
- g.P("}")
- g.P()
- }
- if genRecv {
- g.P("func (x *", streamType, ") Recv() (*", inType, ", error) {")
- g.P("m := new(", inType, ")")
- g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }")
- g.P("return m, nil")
- g.P("}")
- g.P()
- }
-
- return hname
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/link_grpc.go b/vendor/github.com/golang/protobuf/protoc-gen-go/link_grpc.go
deleted file mode 100644
index 532a550..0000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/link_grpc.go
+++ /dev/null
@@ -1,34 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2015 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package main
-
-import _ "github.com/golang/protobuf/protoc-gen-go/grpc"
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/main.go b/vendor/github.com/golang/protobuf/protoc-gen-go/main.go
deleted file mode 100644
index 8e2486d..0000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/main.go
+++ /dev/null
@@ -1,98 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2010 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// protoc-gen-go is a plugin for the Google protocol buffer compiler to generate
-// Go code. Run it by building this program and putting it in your path with
-// the name
-// protoc-gen-go
-// That word 'go' at the end becomes part of the option string set for the
-// protocol compiler, so once the protocol compiler (protoc) is installed
-// you can run
-// protoc --go_out=output_directory input_directory/file.proto
-// to generate Go bindings for the protocol defined by file.proto.
-// With that input, the output will be written to
-// output_directory/file.pb.go
-//
-// The generated code is documented in the package comment for
-// the library.
-//
-// See the README and documentation for protocol buffers to learn more:
-// https://developers.google.com/protocol-buffers/
-package main
-
-import (
- "io/ioutil"
- "os"
-
- "github.com/golang/protobuf/proto"
- "github.com/golang/protobuf/protoc-gen-go/generator"
-)
-
-func main() {
- // Begin by allocating a generator. The request and response structures are stored there
- // so we can do error handling easily - the response structure contains the field to
- // report failure.
- g := generator.New()
-
- data, err := ioutil.ReadAll(os.Stdin)
- if err != nil {
- g.Error(err, "reading input")
- }
-
- if err := proto.Unmarshal(data, g.Request); err != nil {
- g.Error(err, "parsing input proto")
- }
-
- if len(g.Request.FileToGenerate) == 0 {
- g.Fail("no files to generate")
- }
-
- g.CommandLineParameters(g.Request.GetParameter())
-
- // Create a wrapped version of the Descriptors and EnumDescriptors that
- // point to the file that defines them.
- g.WrapTypes()
-
- g.SetPackageNames()
- g.BuildTypeNameMap()
-
- g.GenerateAllFiles()
-
- // Send back the results.
- data, err = proto.Marshal(g.Response)
- if err != nil {
- g.Error(err, "failed to marshal output proto")
- }
- _, err = os.Stdout.Write(data)
- if err != nil {
- g.Error(err, "failed to write output proto")
- }
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go
deleted file mode 100644
index 61bfc10..0000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go
+++ /dev/null
@@ -1,369 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/compiler/plugin.proto
-
-/*
-Package plugin_go is a generated protocol buffer package.
-
-It is generated from these files:
- google/protobuf/compiler/plugin.proto
-
-It has these top-level messages:
- Version
- CodeGeneratorRequest
- CodeGeneratorResponse
-*/
-package plugin_go
-
-import proto "github.com/golang/protobuf/proto"
-import fmt "fmt"
-import math "math"
-import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
-
-// 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.ProtoPackageIsVersion2 // please upgrade the proto package
-
-// The version number of protocol compiler.
-type Version struct {
- Major *int32 `protobuf:"varint,1,opt,name=major" json:"major,omitempty"`
- Minor *int32 `protobuf:"varint,2,opt,name=minor" json:"minor,omitempty"`
- Patch *int32 `protobuf:"varint,3,opt,name=patch" json:"patch,omitempty"`
- // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
- // be empty for mainline stable releases.
- Suffix *string `protobuf:"bytes,4,opt,name=suffix" json:"suffix,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *Version) Reset() { *m = Version{} }
-func (m *Version) String() string { return proto.CompactTextString(m) }
-func (*Version) ProtoMessage() {}
-func (*Version) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
-func (m *Version) Unmarshal(b []byte) error {
- return xxx_messageInfo_Version.Unmarshal(m, b)
-}
-func (m *Version) Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_Version.Marshal(b, m, deterministic)
-}
-func (dst *Version) XXX_Merge(src proto.Message) {
- xxx_messageInfo_Version.Merge(dst, src)
-}
-func (m *Version) XXX_Size() int {
- return xxx_messageInfo_Version.Size(m)
-}
-func (m *Version) XXX_DiscardUnknown() {
- xxx_messageInfo_Version.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_Version proto.InternalMessageInfo
-
-func (m *Version) GetMajor() int32 {
- if m != nil && m.Major != nil {
- return *m.Major
- }
- return 0
-}
-
-func (m *Version) GetMinor() int32 {
- if m != nil && m.Minor != nil {
- return *m.Minor
- }
- return 0
-}
-
-func (m *Version) GetPatch() int32 {
- if m != nil && m.Patch != nil {
- return *m.Patch
- }
- return 0
-}
-
-func (m *Version) GetSuffix() string {
- if m != nil && m.Suffix != nil {
- return *m.Suffix
- }
- return ""
-}
-
-// An encoded CodeGeneratorRequest is written to the plugin's stdin.
-type CodeGeneratorRequest struct {
- // The .proto files that were explicitly listed on the command-line. The
- // code generator should generate code only for these files. Each file's
- // descriptor will be included in proto_file, below.
- FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate,json=fileToGenerate" json:"file_to_generate,omitempty"`
- // The generator parameter passed on the command-line.
- Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"`
- // FileDescriptorProtos for all files in files_to_generate and everything
- // they import. The files will appear in topological order, so each file
- // appears before any file that imports it.
- //
- // protoc guarantees that all proto_files will be written after
- // the fields above, even though this is not technically guaranteed by the
- // protobuf wire format. This theoretically could allow a plugin to stream
- // in the FileDescriptorProtos and handle them one by one rather than read
- // the entire set into memory at once. However, as of this writing, this
- // is not similarly optimized on protoc's end -- it will store all fields in
- // memory at once before sending them to the plugin.
- //
- // Type names of fields and extensions in the FileDescriptorProto are always
- // fully qualified.
- ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file,json=protoFile" json:"proto_file,omitempty"`
- // The version number of protocol compiler.
- CompilerVersion *Version `protobuf:"bytes,3,opt,name=compiler_version,json=compilerVersion" json:"compiler_version,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *CodeGeneratorRequest) Reset() { *m = CodeGeneratorRequest{} }
-func (m *CodeGeneratorRequest) String() string { return proto.CompactTextString(m) }
-func (*CodeGeneratorRequest) ProtoMessage() {}
-func (*CodeGeneratorRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
-func (m *CodeGeneratorRequest) Unmarshal(b []byte) error {
- return xxx_messageInfo_CodeGeneratorRequest.Unmarshal(m, b)
-}
-func (m *CodeGeneratorRequest) Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_CodeGeneratorRequest.Marshal(b, m, deterministic)
-}
-func (dst *CodeGeneratorRequest) XXX_Merge(src proto.Message) {
- xxx_messageInfo_CodeGeneratorRequest.Merge(dst, src)
-}
-func (m *CodeGeneratorRequest) XXX_Size() int {
- return xxx_messageInfo_CodeGeneratorRequest.Size(m)
-}
-func (m *CodeGeneratorRequest) XXX_DiscardUnknown() {
- xxx_messageInfo_CodeGeneratorRequest.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_CodeGeneratorRequest proto.InternalMessageInfo
-
-func (m *CodeGeneratorRequest) GetFileToGenerate() []string {
- if m != nil {
- return m.FileToGenerate
- }
- return nil
-}
-
-func (m *CodeGeneratorRequest) GetParameter() string {
- if m != nil && m.Parameter != nil {
- return *m.Parameter
- }
- return ""
-}
-
-func (m *CodeGeneratorRequest) GetProtoFile() []*google_protobuf.FileDescriptorProto {
- if m != nil {
- return m.ProtoFile
- }
- return nil
-}
-
-func (m *CodeGeneratorRequest) GetCompilerVersion() *Version {
- if m != nil {
- return m.CompilerVersion
- }
- return nil
-}
-
-// The plugin writes an encoded CodeGeneratorResponse to stdout.
-type CodeGeneratorResponse struct {
- // Error message. If non-empty, code generation failed. The plugin process
- // should exit with status code zero even if it reports an error in this way.
- //
- // This should be used to indicate errors in .proto files which prevent the
- // code generator from generating correct code. Errors which indicate a
- // problem in protoc itself -- such as the input CodeGeneratorRequest being
- // unparseable -- should be reported by writing a message to stderr and
- // exiting with a non-zero status code.
- Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"`
- File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *CodeGeneratorResponse) Reset() { *m = CodeGeneratorResponse{} }
-func (m *CodeGeneratorResponse) String() string { return proto.CompactTextString(m) }
-func (*CodeGeneratorResponse) ProtoMessage() {}
-func (*CodeGeneratorResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
-func (m *CodeGeneratorResponse) Unmarshal(b []byte) error {
- return xxx_messageInfo_CodeGeneratorResponse.Unmarshal(m, b)
-}
-func (m *CodeGeneratorResponse) Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_CodeGeneratorResponse.Marshal(b, m, deterministic)
-}
-func (dst *CodeGeneratorResponse) XXX_Merge(src proto.Message) {
- xxx_messageInfo_CodeGeneratorResponse.Merge(dst, src)
-}
-func (m *CodeGeneratorResponse) XXX_Size() int {
- return xxx_messageInfo_CodeGeneratorResponse.Size(m)
-}
-func (m *CodeGeneratorResponse) XXX_DiscardUnknown() {
- xxx_messageInfo_CodeGeneratorResponse.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_CodeGeneratorResponse proto.InternalMessageInfo
-
-func (m *CodeGeneratorResponse) GetError() string {
- if m != nil && m.Error != nil {
- return *m.Error
- }
- return ""
-}
-
-func (m *CodeGeneratorResponse) GetFile() []*CodeGeneratorResponse_File {
- if m != nil {
- return m.File
- }
- return nil
-}
-
-// Represents a single generated file.
-type CodeGeneratorResponse_File struct {
- // The file name, relative to the output directory. The name must not
- // contain "." or ".." components and must be relative, not be absolute (so,
- // the file cannot lie outside the output directory). "/" must be used as
- // the path separator, not "\".
- //
- // If the name is omitted, the content will be appended to the previous
- // file. This allows the generator to break large files into small chunks,
- // and allows the generated text to be streamed back to protoc so that large
- // files need not reside completely in memory at one time. Note that as of
- // this writing protoc does not optimize for this -- it will read the entire
- // CodeGeneratorResponse before writing files to disk.
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- // If non-empty, indicates that the named file should already exist, and the
- // content here is to be inserted into that file at a defined insertion
- // point. This feature allows a code generator to extend the output
- // produced by another code generator. The original generator may provide
- // insertion points by placing special annotations in the file that look
- // like:
- // @@protoc_insertion_point(NAME)
- // The annotation can have arbitrary text before and after it on the line,
- // which allows it to be placed in a comment. NAME should be replaced with
- // an identifier naming the point -- this is what other generators will use
- // as the insertion_point. Code inserted at this point will be placed
- // immediately above the line containing the insertion point (thus multiple
- // insertions to the same point will come out in the order they were added).
- // The double-@ is intended to make it unlikely that the generated code
- // could contain things that look like insertion points by accident.
- //
- // For example, the C++ code generator places the following line in the
- // .pb.h files that it generates:
- // // @@protoc_insertion_point(namespace_scope)
- // This line appears within the scope of the file's package namespace, but
- // outside of any particular class. Another plugin can then specify the
- // insertion_point "namespace_scope" to generate additional classes or
- // other declarations that should be placed in this scope.
- //
- // Note that if the line containing the insertion point begins with
- // whitespace, the same whitespace will be added to every line of the
- // inserted text. This is useful for languages like Python, where
- // indentation matters. In these languages, the insertion point comment
- // should be indented the same amount as any inserted code will need to be
- // in order to work correctly in that context.
- //
- // The code generator that generates the initial file and the one which
- // inserts into it must both run as part of a single invocation of protoc.
- // Code generators are executed in the order in which they appear on the
- // command line.
- //
- // If |insertion_point| is present, |name| must also be present.
- InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point,json=insertionPoint" json:"insertion_point,omitempty"`
- // The file contents.
- Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *CodeGeneratorResponse_File) Reset() { *m = CodeGeneratorResponse_File{} }
-func (m *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(m) }
-func (*CodeGeneratorResponse_File) ProtoMessage() {}
-func (*CodeGeneratorResponse_File) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} }
-func (m *CodeGeneratorResponse_File) Unmarshal(b []byte) error {
- return xxx_messageInfo_CodeGeneratorResponse_File.Unmarshal(m, b)
-}
-func (m *CodeGeneratorResponse_File) Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_CodeGeneratorResponse_File.Marshal(b, m, deterministic)
-}
-func (dst *CodeGeneratorResponse_File) XXX_Merge(src proto.Message) {
- xxx_messageInfo_CodeGeneratorResponse_File.Merge(dst, src)
-}
-func (m *CodeGeneratorResponse_File) XXX_Size() int {
- return xxx_messageInfo_CodeGeneratorResponse_File.Size(m)
-}
-func (m *CodeGeneratorResponse_File) XXX_DiscardUnknown() {
- xxx_messageInfo_CodeGeneratorResponse_File.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_CodeGeneratorResponse_File proto.InternalMessageInfo
-
-func (m *CodeGeneratorResponse_File) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *CodeGeneratorResponse_File) GetInsertionPoint() string {
- if m != nil && m.InsertionPoint != nil {
- return *m.InsertionPoint
- }
- return ""
-}
-
-func (m *CodeGeneratorResponse_File) GetContent() string {
- if m != nil && m.Content != nil {
- return *m.Content
- }
- return ""
-}
-
-func init() {
- proto.RegisterType((*Version)(nil), "google.protobuf.compiler.Version")
- proto.RegisterType((*CodeGeneratorRequest)(nil), "google.protobuf.compiler.CodeGeneratorRequest")
- proto.RegisterType((*CodeGeneratorResponse)(nil), "google.protobuf.compiler.CodeGeneratorResponse")
- proto.RegisterType((*CodeGeneratorResponse_File)(nil), "google.protobuf.compiler.CodeGeneratorResponse.File")
-}
-
-func init() { proto.RegisterFile("google/protobuf/compiler/plugin.proto", fileDescriptor0) }
-
-var fileDescriptor0 = []byte{
- // 417 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0xcf, 0x6a, 0x14, 0x41,
- 0x10, 0xc6, 0x19, 0x77, 0x63, 0x98, 0x8a, 0x64, 0x43, 0x13, 0xa5, 0x09, 0x39, 0x8c, 0x8b, 0xe2,
- 0x5c, 0x32, 0x0b, 0xc1, 0x8b, 0x78, 0x4b, 0x44, 0x3d, 0x78, 0x58, 0x1a, 0xf1, 0x20, 0xc8, 0x30,
- 0x99, 0xd4, 0x74, 0x5a, 0x66, 0xba, 0xc6, 0xee, 0x1e, 0xf1, 0x49, 0x7d, 0x0f, 0xdf, 0x40, 0xfa,
- 0xcf, 0x24, 0xb2, 0xb8, 0xa7, 0xee, 0xef, 0x57, 0xd5, 0xd5, 0x55, 0x1f, 0x05, 0x2f, 0x25, 0x91,
- 0xec, 0x71, 0x33, 0x1a, 0x72, 0x74, 0x33, 0x75, 0x9b, 0x96, 0x86, 0x51, 0xf5, 0x68, 0x36, 0x63,
- 0x3f, 0x49, 0xa5, 0xab, 0x10, 0x60, 0x3c, 0xa6, 0x55, 0x73, 0x5a, 0x35, 0xa7, 0x9d, 0x15, 0xbb,
- 0x05, 0x6e, 0xd1, 0xb6, 0x46, 0x8d, 0x8e, 0x4c, 0xcc, 0x5e, 0xb7, 0x70, 0xf8, 0x05, 0x8d, 0x55,
- 0xa4, 0xd9, 0x29, 0x1c, 0x0c, 0xcd, 0x77, 0x32, 0x3c, 0x2b, 0xb2, 0xf2, 0x40, 0x44, 0x11, 0xa8,
- 0xd2, 0x64, 0xf8, 0xa3, 0x44, 0xbd, 0xf0, 0x74, 0x6c, 0x5c, 0x7b, 0xc7, 0x17, 0x91, 0x06, 0xc1,
- 0x9e, 0xc1, 0x63, 0x3b, 0x75, 0x9d, 0xfa, 0xc5, 0x97, 0x45, 0x56, 0xe6, 0x22, 0xa9, 0xf5, 0x9f,
- 0x0c, 0x4e, 0xaf, 0xe9, 0x16, 0x3f, 0xa0, 0x46, 0xd3, 0x38, 0x32, 0x02, 0x7f, 0x4c, 0x68, 0x1d,
- 0x2b, 0xe1, 0xa4, 0x53, 0x3d, 0xd6, 0x8e, 0x6a, 0x19, 0x63, 0xc8, 0xb3, 0x62, 0x51, 0xe6, 0xe2,
- 0xd8, 0xf3, 0xcf, 0x94, 0x5e, 0x20, 0x3b, 0x87, 0x7c, 0x6c, 0x4c, 0x33, 0xa0, 0xc3, 0xd8, 0x4a,
- 0x2e, 0x1e, 0x00, 0xbb, 0x06, 0x08, 0xe3, 0xd4, 0xfe, 0x15, 0x5f, 0x15, 0x8b, 0xf2, 0xe8, 0xf2,
- 0x45, 0xb5, 0x6b, 0xcb, 0x7b, 0xd5, 0xe3, 0xbb, 0x7b, 0x03, 0xb6, 0x1e, 0x8b, 0x3c, 0x44, 0x7d,
- 0x84, 0x7d, 0x82, 0x93, 0xd9, 0xb8, 0xfa, 0x67, 0xf4, 0x24, 0x8c, 0x77, 0x74, 0xf9, 0xbc, 0xda,
- 0xe7, 0x70, 0x95, 0xcc, 0x13, 0xab, 0x99, 0x24, 0xb0, 0xfe, 0x9d, 0xc1, 0xd3, 0x9d, 0x99, 0xed,
- 0x48, 0xda, 0xa2, 0xf7, 0x0e, 0x8d, 0x49, 0x3e, 0xe7, 0x22, 0x0a, 0xf6, 0x11, 0x96, 0xff, 0x34,
- 0xff, 0x7a, 0xff, 0x8f, 0xff, 0x2d, 0x1a, 0x66, 0x13, 0xa1, 0xc2, 0xd9, 0x37, 0x58, 0x86, 0x79,
- 0x18, 0x2c, 0x75, 0x33, 0x60, 0xfa, 0x26, 0xdc, 0xd9, 0x2b, 0x58, 0x29, 0x6d, 0xd1, 0x38, 0x45,
- 0xba, 0x1e, 0x49, 0x69, 0x97, 0xcc, 0x3c, 0xbe, 0xc7, 0x5b, 0x4f, 0x19, 0x87, 0xc3, 0x96, 0xb4,
- 0x43, 0xed, 0xf8, 0x2a, 0x24, 0xcc, 0xf2, 0x4a, 0xc2, 0x79, 0x4b, 0xc3, 0xde, 0xfe, 0xae, 0x9e,
- 0x6c, 0xc3, 0x6e, 0x06, 0x7b, 0xed, 0xd7, 0x37, 0x52, 0xb9, 0xbb, 0xe9, 0xc6, 0x87, 0x37, 0x92,
- 0xfa, 0x46, 0xcb, 0x87, 0x65, 0x0c, 0x97, 0xf6, 0x42, 0xa2, 0xbe, 0x90, 0x94, 0x56, 0xfa, 0x6d,
- 0x3c, 0x6a, 0x49, 0x7f, 0x03, 0x00, 0x00, 0xff, 0xff, 0xf7, 0x15, 0x40, 0xc5, 0xfe, 0x02, 0x00,
- 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden b/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden
deleted file mode 100644
index 8953d0f..0000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden
+++ /dev/null
@@ -1,83 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: google/protobuf/compiler/plugin.proto
-// DO NOT EDIT!
-
-package google_protobuf_compiler
-
-import proto "github.com/golang/protobuf/proto"
-import "math"
-import google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
-
-// Reference proto and math imports to suppress error if they are not otherwise used.
-var _ = proto.GetString
-var _ = math.Inf
-
-type CodeGeneratorRequest struct {
- FileToGenerate []string `protobuf:"bytes,1,rep,name=file_to_generate" json:"file_to_generate,omitempty"`
- Parameter *string `protobuf:"bytes,2,opt,name=parameter" json:"parameter,omitempty"`
- ProtoFile []*google_protobuf.FileDescriptorProto `protobuf:"bytes,15,rep,name=proto_file" json:"proto_file,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (this *CodeGeneratorRequest) Reset() { *this = CodeGeneratorRequest{} }
-func (this *CodeGeneratorRequest) String() string { return proto.CompactTextString(this) }
-func (*CodeGeneratorRequest) ProtoMessage() {}
-
-func (this *CodeGeneratorRequest) GetParameter() string {
- if this != nil && this.Parameter != nil {
- return *this.Parameter
- }
- return ""
-}
-
-type CodeGeneratorResponse struct {
- Error *string `protobuf:"bytes,1,opt,name=error" json:"error,omitempty"`
- File []*CodeGeneratorResponse_File `protobuf:"bytes,15,rep,name=file" json:"file,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (this *CodeGeneratorResponse) Reset() { *this = CodeGeneratorResponse{} }
-func (this *CodeGeneratorResponse) String() string { return proto.CompactTextString(this) }
-func (*CodeGeneratorResponse) ProtoMessage() {}
-
-func (this *CodeGeneratorResponse) GetError() string {
- if this != nil && this.Error != nil {
- return *this.Error
- }
- return ""
-}
-
-type CodeGeneratorResponse_File struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- InsertionPoint *string `protobuf:"bytes,2,opt,name=insertion_point" json:"insertion_point,omitempty"`
- Content *string `protobuf:"bytes,15,opt,name=content" json:"content,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (this *CodeGeneratorResponse_File) Reset() { *this = CodeGeneratorResponse_File{} }
-func (this *CodeGeneratorResponse_File) String() string { return proto.CompactTextString(this) }
-func (*CodeGeneratorResponse_File) ProtoMessage() {}
-
-func (this *CodeGeneratorResponse_File) GetName() string {
- if this != nil && this.Name != nil {
- return *this.Name
- }
- return ""
-}
-
-func (this *CodeGeneratorResponse_File) GetInsertionPoint() string {
- if this != nil && this.InsertionPoint != nil {
- return *this.InsertionPoint
- }
- return ""
-}
-
-func (this *CodeGeneratorResponse_File) GetContent() string {
- if this != nil && this.Content != nil {
- return *this.Content
- }
- return ""
-}
-
-func init() {
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto
deleted file mode 100644
index 5b55745..0000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto
+++ /dev/null
@@ -1,167 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-// Author: kenton@google.com (Kenton Varda)
-//
-// WARNING: The plugin interface is currently EXPERIMENTAL and is subject to
-// change.
-//
-// protoc (aka the Protocol Compiler) can be extended via plugins. A plugin is
-// just a program that reads a CodeGeneratorRequest from stdin and writes a
-// CodeGeneratorResponse to stdout.
-//
-// Plugins written using C++ can use google/protobuf/compiler/plugin.h instead
-// of dealing with the raw protocol defined here.
-//
-// A plugin executable needs only to be placed somewhere in the path. The
-// plugin should be named "protoc-gen-$NAME", and will then be used when the
-// flag "--${NAME}_out" is passed to protoc.
-
-syntax = "proto2";
-package google.protobuf.compiler;
-option java_package = "com.google.protobuf.compiler";
-option java_outer_classname = "PluginProtos";
-
-option go_package = "github.com/golang/protobuf/protoc-gen-go/plugin;plugin_go";
-
-import "google/protobuf/descriptor.proto";
-
-// The version number of protocol compiler.
-message Version {
- optional int32 major = 1;
- optional int32 minor = 2;
- optional int32 patch = 3;
- // A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should
- // be empty for mainline stable releases.
- optional string suffix = 4;
-}
-
-// An encoded CodeGeneratorRequest is written to the plugin's stdin.
-message CodeGeneratorRequest {
- // The .proto files that were explicitly listed on the command-line. The
- // code generator should generate code only for these files. Each file's
- // descriptor will be included in proto_file, below.
- repeated string file_to_generate = 1;
-
- // The generator parameter passed on the command-line.
- optional string parameter = 2;
-
- // FileDescriptorProtos for all files in files_to_generate and everything
- // they import. The files will appear in topological order, so each file
- // appears before any file that imports it.
- //
- // protoc guarantees that all proto_files will be written after
- // the fields above, even though this is not technically guaranteed by the
- // protobuf wire format. This theoretically could allow a plugin to stream
- // in the FileDescriptorProtos and handle them one by one rather than read
- // the entire set into memory at once. However, as of this writing, this
- // is not similarly optimized on protoc's end -- it will store all fields in
- // memory at once before sending them to the plugin.
- //
- // Type names of fields and extensions in the FileDescriptorProto are always
- // fully qualified.
- repeated FileDescriptorProto proto_file = 15;
-
- // The version number of protocol compiler.
- optional Version compiler_version = 3;
-
-}
-
-// The plugin writes an encoded CodeGeneratorResponse to stdout.
-message CodeGeneratorResponse {
- // Error message. If non-empty, code generation failed. The plugin process
- // should exit with status code zero even if it reports an error in this way.
- //
- // This should be used to indicate errors in .proto files which prevent the
- // code generator from generating correct code. Errors which indicate a
- // problem in protoc itself -- such as the input CodeGeneratorRequest being
- // unparseable -- should be reported by writing a message to stderr and
- // exiting with a non-zero status code.
- optional string error = 1;
-
- // Represents a single generated file.
- message File {
- // The file name, relative to the output directory. The name must not
- // contain "." or ".." components and must be relative, not be absolute (so,
- // the file cannot lie outside the output directory). "/" must be used as
- // the path separator, not "\".
- //
- // If the name is omitted, the content will be appended to the previous
- // file. This allows the generator to break large files into small chunks,
- // and allows the generated text to be streamed back to protoc so that large
- // files need not reside completely in memory at one time. Note that as of
- // this writing protoc does not optimize for this -- it will read the entire
- // CodeGeneratorResponse before writing files to disk.
- optional string name = 1;
-
- // If non-empty, indicates that the named file should already exist, and the
- // content here is to be inserted into that file at a defined insertion
- // point. This feature allows a code generator to extend the output
- // produced by another code generator. The original generator may provide
- // insertion points by placing special annotations in the file that look
- // like:
- // @@protoc_insertion_point(NAME)
- // The annotation can have arbitrary text before and after it on the line,
- // which allows it to be placed in a comment. NAME should be replaced with
- // an identifier naming the point -- this is what other generators will use
- // as the insertion_point. Code inserted at this point will be placed
- // immediately above the line containing the insertion point (thus multiple
- // insertions to the same point will come out in the order they were added).
- // The double-@ is intended to make it unlikely that the generated code
- // could contain things that look like insertion points by accident.
- //
- // For example, the C++ code generator places the following line in the
- // .pb.h files that it generates:
- // // @@protoc_insertion_point(namespace_scope)
- // This line appears within the scope of the file's package namespace, but
- // outside of any particular class. Another plugin can then specify the
- // insertion_point "namespace_scope" to generate additional classes or
- // other declarations that should be placed in this scope.
- //
- // Note that if the line containing the insertion point begins with
- // whitespace, the same whitespace will be added to every line of the
- // inserted text. This is useful for languages like Python, where
- // indentation matters. In these languages, the insertion point comment
- // should be indented the same amount as any inserted code will need to be
- // in order to work correctly in that context.
- //
- // The code generator that generates the initial file and the one which
- // inserts into it must both run as part of a single invocation of protoc.
- // Code generators are executed in the order in which they appear on the
- // command line.
- //
- // If |insertion_point| is present, |name| must also be present.
- optional string insertion_point = 2;
-
- // The file contents.
- optional string content = 15;
- }
- repeated File file = 15;
-}
diff --git a/vendor/github.com/google/gopacket/layers/gen.go b/vendor/github.com/google/gopacket/layers/gen.go
deleted file mode 100644
index ab7a0c0..0000000
--- a/vendor/github.com/google/gopacket/layers/gen.go
+++ /dev/null
@@ -1,109 +0,0 @@
-// Copyright 2012 Google, Inc. All rights reserved.
-//
-// Use of this source code is governed by a BSD-style license
-// that can be found in the LICENSE file in the root of the source
-// tree.
-
-// +build ignore
-
-// This binary pulls known ports from IANA, and uses them to populate
-// iana_ports.go's TCPPortNames and UDPPortNames maps.
-//
-// go run gen.go | gofmt > iana_ports.go
-package main
-
-import (
- "bytes"
- "encoding/xml"
- "flag"
- "fmt"
- "io/ioutil"
- "net/http"
- "os"
- "strconv"
- "time"
-)
-
-const fmtString = `// Copyright 2012 Google, Inc. All rights reserved.
-
-package layers
-
-// Created by gen.go, don't edit manually
-// Generated at %s
-// Fetched from %q
-
-// TCPPortNames contains the port names for all TCP ports.
-var TCPPortNames = tcpPortNames
-
-// UDPPortNames contains the port names for all UDP ports.
-var UDPPortNames = udpPortNames
-
-// SCTPPortNames contains the port names for all SCTP ports.
-var SCTPPortNames = sctpPortNames
-
-var tcpPortNames = map[TCPPort]string{
-%s}
-var udpPortNames = map[UDPPort]string{
-%s}
-var sctpPortNames = map[SCTPPort]string{
-%s}
-`
-
-var url = flag.String("url", "http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml", "URL to grab port numbers from")
-
-func main() {
- fmt.Fprintf(os.Stderr, "Fetching ports from %q\n", *url)
- resp, err := http.Get(*url)
- if err != nil {
- panic(err)
- }
- defer resp.Body.Close()
- body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- panic(err)
- }
- fmt.Fprintln(os.Stderr, "Parsing XML")
- var registry struct {
- Records []struct {
- Protocol string `xml:"protocol"`
- Number string `xml:"number"`
- Name string `xml:"name"`
- } `xml:"record"`
- }
- xml.Unmarshal(body, ®istry)
- var tcpPorts bytes.Buffer
- var udpPorts bytes.Buffer
- var sctpPorts bytes.Buffer
- done := map[string]map[int]bool{
- "tcp": map[int]bool{},
- "udp": map[int]bool{},
- "sctp": map[int]bool{},
- }
- for _, r := range registry.Records {
- port, err := strconv.Atoi(r.Number)
- if err != nil {
- continue
- }
- if r.Name == "" {
- continue
- }
- var b *bytes.Buffer
- switch r.Protocol {
- case "tcp":
- b = &tcpPorts
- case "udp":
- b = &udpPorts
- case "sctp":
- b = &sctpPorts
- default:
- continue
- }
- if done[r.Protocol][port] {
- continue
- }
- done[r.Protocol][port] = true
- fmt.Fprintf(b, "\t%d: %q,\n", port, r.Name)
- }
- fmt.Fprintln(os.Stderr, "Writing results to stdout")
- fmt.Printf(fmtString, time.Now(), *url, tcpPorts.String(), udpPorts.String(), sctpPorts.String())
-}
diff --git a/vendor/github.com/google/gopacket/layers/gen2.go b/vendor/github.com/google/gopacket/layers/gen2.go
deleted file mode 100644
index 150cad7..0000000
--- a/vendor/github.com/google/gopacket/layers/gen2.go
+++ /dev/null
@@ -1,104 +0,0 @@
-// Copyright 2012 Google, Inc. All rights reserved.
-//
-// Use of this source code is governed by a BSD-style license
-// that can be found in the LICENSE file in the root of the source
-// tree.
-
-// +build ignore
-
-// This binary handles creating string constants and function templates for enums.
-//
-// go run gen.go | gofmt > enums_generated.go
-package main
-
-import (
- "fmt"
- "log"
- "os"
- "text/template"
- "time"
-)
-
-const fmtString = `// Copyright 2012 Google, Inc. All rights reserved.
-
-package layers
-
-// Created by gen2.go, don't edit manually
-// Generated at %s
-
-import (
- "fmt"
-
- "github.com/google/gopacket"
-)
-
-`
-
-var funcsTmpl = template.Must(template.New("foo").Parse(`
-// Decoder calls {{.Name}}Metadata.DecodeWith's decoder.
-func (a {{.Name}}) Decode(data []byte, p gopacket.PacketBuilder) error {
- return {{.Name}}Metadata[a].DecodeWith.Decode(data, p)
-}
-// String returns {{.Name}}Metadata.Name.
-func (a {{.Name}}) String() string {
- return {{.Name}}Metadata[a].Name
-}
-// LayerType returns {{.Name}}Metadata.LayerType.
-func (a {{.Name}}) LayerType() gopacket.LayerType {
- return {{.Name}}Metadata[a].LayerType
-}
-
-type errorDecoderFor{{.Name}} int
-func (a *errorDecoderFor{{.Name}}) Decode(data []byte, p gopacket.PacketBuilder) error {
- return a
-}
-func (a *errorDecoderFor{{.Name}}) Error() string {
- return fmt.Sprintf("Unable to decode {{.Name}} %d", int(*a))
-}
-
-var errorDecodersFor{{.Name}} [{{.Num}}]errorDecoderFor{{.Name}}
-var {{.Name}}Metadata [{{.Num}}]EnumMetadata
-
-func initUnknownTypesFor{{.Name}}() {
- for i := 0; i < {{.Num}}; i++ {
- errorDecodersFor{{.Name}}[i] = errorDecoderFor{{.Name}}(i)
- {{.Name}}Metadata[i] = EnumMetadata{
- DecodeWith: &errorDecodersFor{{.Name}}[i],
- Name: "Unknown{{.Name}}",
- }
- }
-}
-`))
-
-func main() {
- fmt.Fprintf(os.Stderr, "Writing results to stdout\n")
- fmt.Printf(fmtString, time.Now())
- types := []struct {
- Name string
- Num int
- }{
- {"LinkType", 256},
- {"EthernetType", 65536},
- {"PPPType", 65536},
- {"IPProtocol", 256},
- {"SCTPChunkType", 256},
- {"PPPoECode", 256},
- {"FDDIFrameControl", 256},
- {"EAPOLType", 256},
- {"ProtocolFamily", 256},
- {"Dot11Type", 256},
- {"USBTransportType", 256},
- }
-
- fmt.Println("func init() {")
- for _, t := range types {
- fmt.Printf("initUnknownTypesFor%s()\n", t.Name)
- }
- fmt.Println("initActualTypeData()")
- fmt.Println("}")
- for _, t := range types {
- if err := funcsTmpl.Execute(os.Stdout, t); err != nil {
- log.Fatalf("Failed to execute template %s: %v", t.Name, err)
- }
- }
-}
diff --git a/vendor/github.com/google/gopacket/pcap/generate_defs.go b/vendor/github.com/google/gopacket/pcap/generate_defs.go
deleted file mode 100644
index bcbf161..0000000
--- a/vendor/github.com/google/gopacket/pcap/generate_defs.go
+++ /dev/null
@@ -1,157 +0,0 @@
-// Copyright 2019 The GoPacket Authors. All rights reserved.
-//
-// Use of this source code is governed by a BSD-style license
-// that can be found in the LICENSE file in the root of the source
-// tree.
-
-// +build ignore
-
-package main
-
-// This file generates the godefs needed for the windows version.
-// Rebuild is only necessary if additional libpcap functionality is implemented, or a new arch is implemented in golang.
-// Call with go run generate_windows.go [-I includepath]
-// Needs npcap sdk, go tool cgo, and gofmt to work. Location of npcap includes can be specified with -I
-
-import (
- "bytes"
- "flag"
- "fmt"
- "io/ioutil"
- "log"
- "os"
- "os/exec"
- "path/filepath"
- "strings"
-)
-
-const header = `// Copyright 2019 The GoPacket Authors. All rights reserved.
-//
-// Use of this source code is governed by a BSD-style license
-// that can be found in the LICENSE file in the root of the source
-// tree.
-
-// This file contains necessary structs/constants generated from libpcap headers with cgo -godefs
-// generated with: %s
-// DO NOT MODIFY
-
-`
-
-const source = `
-package pcap
-
-//#include <pcap.h>
-import "C"
-
-import "syscall" // needed for RawSockaddr
-
-const errorBufferSize = C.PCAP_ERRBUF_SIZE
-
-const (
- pcapErrorNotActivated = C.PCAP_ERROR_NOT_ACTIVATED
- pcapErrorActivated = C.PCAP_ERROR_ACTIVATED
- pcapWarningPromisc = C.PCAP_WARNING_PROMISC_NOTSUP
- pcapErrorNoSuchDevice = C.PCAP_ERROR_NO_SUCH_DEVICE
- pcapErrorDenied = C.PCAP_ERROR_PERM_DENIED
- pcapErrorNotUp = C.PCAP_ERROR_IFACE_NOT_UP
- pcapError = C.PCAP_ERROR
- pcapWarning = C.PCAP_WARNING
- pcapDIN = C.PCAP_D_IN
- pcapDOUT = C.PCAP_D_OUT
- pcapDINOUT = C.PCAP_D_INOUT
- pcapNetmaskUnknown = C.PCAP_NETMASK_UNKNOWN
- pcapTstampPrecisionMicro = C.PCAP_TSTAMP_PRECISION_MICRO
- pcapTstampPrecisionNano = C.PCAP_TSTAMP_PRECISION_NANO
-)
-
-type timeval C.struct_timeval
-type pcapPkthdr C.struct_pcap_pkthdr
-type pcapTPtr uintptr
-type pcapBpfInstruction C.struct_bpf_insn
-type pcapBpfProgram C.struct_bpf_program
-type pcapStats C.struct_pcap_stat
-type pcapCint C.int
-type pcapIf C.struct_pcap_if
-// +godefs map struct_sockaddr syscall.RawSockaddr
-type pcapAddr C.struct_pcap_addr
-`
-
-var includes = flag.String("I", "C:\\npcap-sdk-1.01\\Include", "Include path containing libpcap headers")
-
-func main() {
- flag.Parse()
-
- infile, err := ioutil.TempFile(".", "defs.*.go")
- if err != nil {
- log.Fatal("Couldn't create temporary source file: ", err)
- }
- defer infile.Close()
- defer os.Remove(infile.Name())
-
- _, err = infile.WriteString(source)
- if err != nil {
- log.Fatalf("Couldn't write definitions to temporary file %s: %s", infile.Name(), err)
- }
- err = infile.Close()
- if err != nil {
- log.Fatalf("Couldn't close temporary source file %s: %s", infile.Name(), err)
- }
-
- archs := []string{"386", "amd64"}
- for _, arch := range archs {
- env := append(os.Environ(), "GOARCH="+arch)
- cmd := exec.Command("go", "tool", "cgo", "-godefs", "--", "-I", *includes, infile.Name())
- cmd.Env = env
- cmd.Stderr = os.Stderr
- var generated bytes.Buffer
- cmd.Stdout = &generated
- err := cmd.Run()
- if err != nil {
- log.Fatalf("Couldn't generated defs for %s: %s\n", arch, err)
- }
-
- cmd = exec.Command("gofmt")
- cmd.Env = env
- cmd.Stderr = os.Stderr
- outName := fmt.Sprintf("defs_windows_%s.go", arch)
- out, err := os.Create(outName)
- if err != nil {
- log.Fatalf("Couldn't open file %s: %s", outName, err)
- }
- cmd.Stdout = out
- in, err := cmd.StdinPipe()
- if err != nil {
- log.Fatal("Couldn't create input pipe for gofmt: ", err)
- }
- err = cmd.Start()
- if err != nil {
- log.Fatal("Couldn't start gofmt: ", err)
- }
-
- _, err = fmt.Fprintf(in, header, strings.Join(append([]string{filepath.Base(os.Args[0])}, os.Args[1:]...), " "))
- if err != nil {
- log.Fatal("Couldn't write header to gofmt: ", err)
- }
-
- for {
- line, err := generated.ReadBytes('\n')
- if err != nil {
- break
- }
- // remove godefs comments
- if bytes.HasPrefix(line, []byte("//")) {
- continue
- }
- _, err = in.Write(line)
- if err != nil {
- log.Fatal("Couldn't write line to gofmt: ", err)
- }
- }
- in.Close()
- err = cmd.Wait()
- if err != nil {
- log.Fatal("gofmt failed: ", err)
- }
- out.Close()
- }
-}
diff --git a/vendor/github.com/google/gopacket/pcap/pcap_tester.go b/vendor/github.com/google/gopacket/pcap/pcap_tester.go
deleted file mode 100644
index 7873a96..0000000
--- a/vendor/github.com/google/gopacket/pcap/pcap_tester.go
+++ /dev/null
@@ -1,108 +0,0 @@
-// Copyright 2012 Google, Inc. All rights reserved.
-//
-// Use of this source code is governed by a BSD-style license
-// that can be found in the LICENSE file in the root of the source
-// tree.
-
-// +build ignore
-
-// This binary tests that PCAP packet capture is working correctly by issuing
-// HTTP requests, then making sure we actually capture data off the wire.
-package main
-
-import (
- "errors"
- "flag"
- "fmt"
- "log"
- "net/http"
- "os"
- "time"
-
- "github.com/google/gopacket/pcap"
-)
-
-var mode = flag.String("mode", "basic", "One of: basic,filtered,timestamp")
-
-func generatePackets() {
- if resp, err := http.Get("http://code.google.com"); err != nil {
- log.Printf("Could not get HTTP: %v", err)
- } else {
- resp.Body.Close()
- }
-}
-
-func main() {
- flag.Parse()
- ifaces, err := pcap.FindAllDevs()
- if err != nil {
- log.Fatal(err)
- }
- for _, iface := range ifaces {
- log.Printf("Trying capture on %q", iface.Name)
- if err := tryCapture(iface); err != nil {
- log.Printf("Error capturing on %q: %v", iface.Name, err)
- } else {
- log.Printf("Successfully captured on %q", iface.Name)
- return
- }
- }
- os.Exit(1)
-}
-
-func tryCapture(iface pcap.Interface) error {
- if iface.Name[:2] == "lo" {
- return errors.New("skipping loopback")
- }
- var h *pcap.Handle
- var err error
- switch *mode {
- case "basic":
- h, err = pcap.OpenLive(iface.Name, 65536, false, time.Second*3)
- if err != nil {
- return fmt.Errorf("openlive: %v", err)
- }
- defer h.Close()
- case "filtered":
- h, err = pcap.OpenLive(iface.Name, 65536, false, time.Second*3)
- if err != nil {
- return fmt.Errorf("openlive: %v", err)
- }
- defer h.Close()
- if err := h.SetBPFFilter("port 80 or port 443"); err != nil {
- return fmt.Errorf("setbpf: %v", err)
- }
- case "timestamp":
- u, err := pcap.NewInactiveHandle(iface.Name)
- if err != nil {
- return err
- }
- defer u.CleanUp()
- if err = u.SetSnapLen(65536); err != nil {
- return err
- } else if err = u.SetPromisc(false); err != nil {
- return err
- } else if err = u.SetTimeout(time.Second * 3); err != nil {
- return err
- }
- sources := u.SupportedTimestamps()
- if len(sources) == 0 {
- return errors.New("no supported timestamp sources")
- } else if err := u.SetTimestampSource(sources[0]); err != nil {
- return fmt.Errorf("settimestampsource(%v): %v", sources[0], err)
- } else if h, err = u.Activate(); err != nil {
- return fmt.Errorf("could not activate: %v", err)
- }
- defer h.Close()
- default:
- panic("Invalid --mode: " + *mode)
- }
- go generatePackets()
- h.ReadPacketData() // Do one dummy read to clear any timeouts.
- data, ci, err := h.ReadPacketData()
- if err != nil {
- return fmt.Errorf("readpacketdata: %v", err)
- }
- log.Printf("Read packet, %v bytes, CI: %+v", len(data), ci)
- return nil
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/codegenerator/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/codegenerator/BUILD.bazel
deleted file mode 100644
index 651177f..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/codegenerator/BUILD.bazel
+++ /dev/null
@@ -1,26 +0,0 @@
-load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
-
-package(default_visibility = ["//:generators"])
-
-go_library(
- name = "go_default_library",
- srcs = [
- "doc.go",
- "parse_req.go",
- ],
- importpath = "github.com/grpc-ecosystem/grpc-gateway/codegenerator",
- deps = [
- "@com_github_golang_protobuf//proto:go_default_library",
- "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto",
- ],
-)
-
-go_test(
- name = "go_default_test",
- srcs = ["parse_req_test.go"],
- embed = [":go_default_library"],
- deps = [
- "@com_github_golang_protobuf//proto:go_default_library",
- "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto",
- ],
-)
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/codegenerator/doc.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/codegenerator/doc.go
deleted file mode 100644
index 3645317..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/codegenerator/doc.go
+++ /dev/null
@@ -1,4 +0,0 @@
-/*
-Package codegenerator contains reusable functions used by the code generators.
-*/
-package codegenerator
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/codegenerator/parse_req.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/codegenerator/parse_req.go
deleted file mode 100644
index e74575b..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/codegenerator/parse_req.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package codegenerator
-
-import (
- "fmt"
- "io"
- "io/ioutil"
-
- "github.com/golang/protobuf/proto"
- plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
-)
-
-// ParseRequest parses a code generator request from a proto Message.
-func ParseRequest(r io.Reader) (*plugin.CodeGeneratorRequest, error) {
- input, err := ioutil.ReadAll(r)
- if err != nil {
- return nil, fmt.Errorf("failed to read code generator request: %v", err)
- }
- req := new(plugin.CodeGeneratorRequest)
- if err = proto.Unmarshal(input, req); err != nil {
- return nil, fmt.Errorf("failed to unmarshal code generator request: %v", err)
- }
- return req, nil
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/BUILD.bazel
deleted file mode 100644
index cb772ef..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/BUILD.bazel
+++ /dev/null
@@ -1,45 +0,0 @@
-load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
-load("@io_bazel_rules_go//proto:compiler.bzl", "go_proto_compiler")
-
-package(default_visibility = ["//visibility:private"])
-
-go_library(
- name = "go_default_library",
- srcs = ["main.go"],
- importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway",
- deps = [
- "//codegenerator:go_default_library",
- "//protoc-gen-grpc-gateway/descriptor:go_default_library",
- "//protoc-gen-grpc-gateway/gengateway:go_default_library",
- "@com_github_golang_glog//:go_default_library",
- "@com_github_golang_protobuf//proto:go_default_library",
- "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto",
- ],
-)
-
-go_binary(
- name = "protoc-gen-grpc-gateway",
- embed = [":go_default_library"],
- visibility = ["//visibility:public"],
-)
-
-go_proto_compiler(
- name = "go_gen_grpc_gateway",
- options = [
- "logtostderr=true",
- "allow_repeated_fields_in_body=true",
- ],
- plugin = ":protoc-gen-grpc-gateway",
- suffix = ".pb.gw.go",
- visibility = ["//visibility:public"],
- deps = [
- "//runtime:go_default_library",
- "//utilities:go_default_library",
- "@com_github_golang_protobuf//proto:go_default_library",
- "@org_golang_google_grpc//:go_default_library",
- "@org_golang_google_grpc//codes:go_default_library",
- "@org_golang_google_grpc//grpclog:go_default_library",
- "@org_golang_google_grpc//status:go_default_library",
- "@org_golang_x_net//context:go_default_library",
- ],
-)
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/BUILD.bazel
deleted file mode 100644
index cfbdc27..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/BUILD.bazel
+++ /dev/null
@@ -1,44 +0,0 @@
-load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
-
-package(default_visibility = ["//:generators"])
-
-go_library(
- name = "go_default_library",
- srcs = [
- "grpc_api_configuration.go",
- "grpc_api_service.go",
- "registry.go",
- "services.go",
- "types.go",
- ],
- importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor",
- deps = [
- "//protoc-gen-grpc-gateway/httprule:go_default_library",
- "@com_github_ghodss_yaml//:go_default_library",
- "@com_github_golang_glog//:go_default_library",
- "@com_github_golang_protobuf//jsonpb:go_default_library_gen",
- "@com_github_golang_protobuf//proto:go_default_library",
- "@com_github_golang_protobuf//protoc-gen-go/generator:go_default_library_gen",
- "@go_googleapis//google/api:annotations_go_proto",
- "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto",
- "@io_bazel_rules_go//proto/wkt:descriptor_go_proto",
- ],
-)
-
-go_test(
- name = "go_default_test",
- size = "small",
- srcs = [
- "grpc_api_configuration_test.go",
- "registry_test.go",
- "services_test.go",
- "types_test.go",
- ],
- embed = [":go_default_library"],
- deps = [
- "//protoc-gen-grpc-gateway/httprule:go_default_library",
- "@com_github_golang_protobuf//proto:go_default_library",
- "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto",
- "@io_bazel_rules_go//proto/wkt:descriptor_go_proto",
- ],
-)
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_configuration.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_configuration.go
deleted file mode 100644
index ca68ed7..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_configuration.go
+++ /dev/null
@@ -1,71 +0,0 @@
-package descriptor
-
-import (
- "bytes"
- "fmt"
- "io/ioutil"
- "strings"
-
- "github.com/ghodss/yaml"
- "github.com/golang/protobuf/jsonpb"
-)
-
-func loadGrpcAPIServiceFromYAML(yamlFileContents []byte, yamlSourceLogName string) (*GrpcAPIService, error) {
- jsonContents, err := yaml.YAMLToJSON(yamlFileContents)
- if err != nil {
- return nil, fmt.Errorf("Failed to convert gRPC API Configuration from YAML in '%v' to JSON: %v", yamlSourceLogName, err)
- }
-
- // As our GrpcAPIService is incomplete accept unkown fields.
- unmarshaler := jsonpb.Unmarshaler{
- AllowUnknownFields: true,
- }
-
- serviceConfiguration := GrpcAPIService{}
- if err := unmarshaler.Unmarshal(bytes.NewReader(jsonContents), &serviceConfiguration); err != nil {
- return nil, fmt.Errorf("Failed to parse gRPC API Configuration from YAML in '%v': %v", yamlSourceLogName, err)
- }
-
- return &serviceConfiguration, nil
-}
-
-func registerHTTPRulesFromGrpcAPIService(registry *Registry, service *GrpcAPIService, sourceLogName string) error {
- if service.HTTP == nil {
- // Nothing to do
- return nil
- }
-
- for _, rule := range service.HTTP.GetRules() {
- selector := "." + strings.Trim(rule.GetSelector(), " ")
- if strings.ContainsAny(selector, "*, ") {
- return fmt.Errorf("Selector '%v' in %v must specify a single service method without wildcards", rule.GetSelector(), sourceLogName)
- }
-
- registry.AddExternalHTTPRule(selector, rule)
- }
-
- return nil
-}
-
-// LoadGrpcAPIServiceFromYAML loads a gRPC API Configuration from the given YAML file
-// and registers the HttpRule descriptions contained in it as externalHTTPRules in
-// the given registry. This must be done before loading the proto file.
-//
-// You can learn more about gRPC API Service descriptions from google's documentation
-// at https://cloud.google.com/endpoints/docs/grpc/grpc-service-config
-//
-// Note that for the purposes of the gateway generator we only consider a subset of all
-// available features google supports in their service descriptions.
-func (r *Registry) LoadGrpcAPIServiceFromYAML(yamlFile string) error {
- yamlFileContents, err := ioutil.ReadFile(yamlFile)
- if err != nil {
- return fmt.Errorf("Failed to read gRPC API Configuration description from '%v': %v", yamlFile, err)
- }
-
- service, err := loadGrpcAPIServiceFromYAML(yamlFileContents, yamlFile)
- if err != nil {
- return err
- }
-
- return registerHTTPRulesFromGrpcAPIService(r, service, yamlFile)
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_service.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_service.go
deleted file mode 100644
index 75b8240..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/grpc_api_service.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package descriptor
-
-import (
- "github.com/golang/protobuf/proto"
- "google.golang.org/genproto/googleapis/api/annotations"
-)
-
-// GrpcAPIService represents a stripped down version of google.api.Service .
-// Compare to https://github.com/googleapis/googleapis/blob/master/google/api/service.proto
-// The original imports 23 other protobuf files we are not interested in. If a significant
-// subset (>50%) of these start being reproduced in this file we should swap to using the
-// full generated version instead.
-//
-// For the purposes of the gateway generator we only consider a small subset of all
-// available features google supports in their service descriptions. Thanks to backwards
-// compatibility guarantees by protobuf it is safe for us to remove the other fields.
-// We also only implement the absolute minimum of protobuf generator boilerplate to use
-// our simplified version. These should be pretty stable too.
-type GrpcAPIService struct {
- // Http Rule. Named Http in the actual proto. Changed to suppress linter warning.
- HTTP *annotations.Http `protobuf:"bytes,9,opt,name=http" json:"http,omitempty"`
-}
-
-// ProtoMessage returns an empty GrpcAPIService element
-func (*GrpcAPIService) ProtoMessage() {}
-
-// Reset resets the GrpcAPIService
-func (m *GrpcAPIService) Reset() { *m = GrpcAPIService{} }
-
-// String returns the string representation of the GrpcAPIService
-func (m *GrpcAPIService) String() string { return proto.CompactTextString(m) }
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/registry.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/registry.go
deleted file mode 100644
index b73c123..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/registry.go
+++ /dev/null
@@ -1,512 +0,0 @@
-package descriptor
-
-import (
- "fmt"
- "path"
- "path/filepath"
- "strings"
-
- "github.com/golang/glog"
- descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
- plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
- "google.golang.org/genproto/googleapis/api/annotations"
-)
-
-// Registry is a registry of information extracted from plugin.CodeGeneratorRequest.
-type Registry struct {
- // msgs is a mapping from fully-qualified message name to descriptor
- msgs map[string]*Message
-
- // enums is a mapping from fully-qualified enum name to descriptor
- enums map[string]*Enum
-
- // files is a mapping from file path to descriptor
- files map[string]*File
-
- // prefix is a prefix to be inserted to golang package paths generated from proto package names.
- prefix string
-
- // importPath is used as the package if no input files declare go_package. If it contains slashes, everything up to the rightmost slash is ignored.
- importPath string
-
- // pkgMap is a user-specified mapping from file path to proto package.
- pkgMap map[string]string
-
- // pkgAliases is a mapping from package aliases to package paths in go which are already taken.
- pkgAliases map[string]string
-
- // allowDeleteBody permits http delete methods to have a body
- allowDeleteBody bool
-
- // externalHttpRules is a mapping from fully qualified service method names to additional HttpRules applicable besides the ones found in annotations.
- externalHTTPRules map[string][]*annotations.HttpRule
-
- // allowMerge generation one swagger file out of multiple protos
- allowMerge bool
-
- // mergeFileName target swagger file name after merge
- mergeFileName string
-
- // allowRepeatedFieldsInBody permits repeated field in body field path of `google.api.http` annotation option
- allowRepeatedFieldsInBody bool
-
- // includePackageInTags controls whether the package name defined in the `package` directive
- // in the proto file can be prepended to the gRPC service name in the `Tags` field of every operation.
- includePackageInTags bool
-
- // repeatedPathParamSeparator specifies how path parameter repeated fields are separated
- repeatedPathParamSeparator repeatedFieldSeparator
-
- // useJSONNamesForFields if true json tag name is used for generating fields in swagger definitions,
- // otherwise the original proto name is used. It's helpful for synchronizing the swagger definition
- // with grpc-gateway response, if it uses json tags for marshaling.
- useJSONNamesForFields bool
-
- // useFQNForSwaggerName if true swagger names will use the full qualified name (FQN) from proto definition,
- // and generate a dot-separated swagger name concatenating all elements from the proto FQN.
- // If false, the default behavior is to concat the last 2 elements of the FQN if they are unique, otherwise concat
- // all the elements of the FQN without any separator
- useFQNForSwaggerName bool
-
- // allowColonFinalSegments determines whether colons are permitted
- // in the final segment of a path.
- allowColonFinalSegments bool
-
- // useGoTemplate determines whether you want to use GO templates
- // in your protofile comments
- useGoTemplate bool
-}
-
-type repeatedFieldSeparator struct {
- name string
- sep rune
-}
-
-// NewRegistry returns a new Registry.
-func NewRegistry() *Registry {
- return &Registry{
- msgs: make(map[string]*Message),
- enums: make(map[string]*Enum),
- files: make(map[string]*File),
- pkgMap: make(map[string]string),
- pkgAliases: make(map[string]string),
- externalHTTPRules: make(map[string][]*annotations.HttpRule),
- repeatedPathParamSeparator: repeatedFieldSeparator{
- name: "csv",
- sep: ',',
- },
- }
-}
-
-// Load loads definitions of services, methods, messages, enumerations and fields from "req".
-func (r *Registry) Load(req *plugin.CodeGeneratorRequest) error {
- for _, file := range req.GetProtoFile() {
- r.loadFile(file)
- }
-
- var targetPkg string
- for _, name := range req.FileToGenerate {
- target := r.files[name]
- if target == nil {
- return fmt.Errorf("no such file: %s", name)
- }
- name := r.packageIdentityName(target.FileDescriptorProto)
- if targetPkg == "" {
- targetPkg = name
- } else {
- if targetPkg != name {
- return fmt.Errorf("inconsistent package names: %s %s", targetPkg, name)
- }
- }
-
- if err := r.loadServices(target); err != nil {
- return err
- }
- }
- return nil
-}
-
-// loadFile loads messages, enumerations and fields from "file".
-// It does not loads services and methods in "file". You need to call
-// loadServices after loadFiles is called for all files to load services and methods.
-func (r *Registry) loadFile(file *descriptor.FileDescriptorProto) {
- pkg := GoPackage{
- Path: r.goPackagePath(file),
- Name: r.defaultGoPackageName(file),
- }
- if err := r.ReserveGoPackageAlias(pkg.Name, pkg.Path); err != nil {
- for i := 0; ; i++ {
- alias := fmt.Sprintf("%s_%d", pkg.Name, i)
- if err := r.ReserveGoPackageAlias(alias, pkg.Path); err == nil {
- pkg.Alias = alias
- break
- }
- }
- }
- f := &File{
- FileDescriptorProto: file,
- GoPkg: pkg,
- }
-
- r.files[file.GetName()] = f
- r.registerMsg(f, nil, file.GetMessageType())
- r.registerEnum(f, nil, file.GetEnumType())
-}
-
-func (r *Registry) registerMsg(file *File, outerPath []string, msgs []*descriptor.DescriptorProto) {
- for i, md := range msgs {
- m := &Message{
- File: file,
- Outers: outerPath,
- DescriptorProto: md,
- Index: i,
- }
- for _, fd := range md.GetField() {
- m.Fields = append(m.Fields, &Field{
- Message: m,
- FieldDescriptorProto: fd,
- })
- }
- file.Messages = append(file.Messages, m)
- r.msgs[m.FQMN()] = m
- glog.V(1).Infof("register name: %s", m.FQMN())
-
- var outers []string
- outers = append(outers, outerPath...)
- outers = append(outers, m.GetName())
- r.registerMsg(file, outers, m.GetNestedType())
- r.registerEnum(file, outers, m.GetEnumType())
- }
-}
-
-func (r *Registry) registerEnum(file *File, outerPath []string, enums []*descriptor.EnumDescriptorProto) {
- for i, ed := range enums {
- e := &Enum{
- File: file,
- Outers: outerPath,
- EnumDescriptorProto: ed,
- Index: i,
- }
- file.Enums = append(file.Enums, e)
- r.enums[e.FQEN()] = e
- glog.V(1).Infof("register enum name: %s", e.FQEN())
- }
-}
-
-// LookupMsg looks up a message type by "name".
-// It tries to resolve "name" from "location" if "name" is a relative message name.
-func (r *Registry) LookupMsg(location, name string) (*Message, error) {
- glog.V(1).Infof("lookup %s from %s", name, location)
- if strings.HasPrefix(name, ".") {
- m, ok := r.msgs[name]
- if !ok {
- return nil, fmt.Errorf("no message found: %s", name)
- }
- return m, nil
- }
-
- if !strings.HasPrefix(location, ".") {
- location = fmt.Sprintf(".%s", location)
- }
- components := strings.Split(location, ".")
- for len(components) > 0 {
- fqmn := strings.Join(append(components, name), ".")
- if m, ok := r.msgs[fqmn]; ok {
- return m, nil
- }
- components = components[:len(components)-1]
- }
- return nil, fmt.Errorf("no message found: %s", name)
-}
-
-// LookupEnum looks up a enum type by "name".
-// It tries to resolve "name" from "location" if "name" is a relative enum name.
-func (r *Registry) LookupEnum(location, name string) (*Enum, error) {
- glog.V(1).Infof("lookup enum %s from %s", name, location)
- if strings.HasPrefix(name, ".") {
- e, ok := r.enums[name]
- if !ok {
- return nil, fmt.Errorf("no enum found: %s", name)
- }
- return e, nil
- }
-
- if !strings.HasPrefix(location, ".") {
- location = fmt.Sprintf(".%s", location)
- }
- components := strings.Split(location, ".")
- for len(components) > 0 {
- fqen := strings.Join(append(components, name), ".")
- if e, ok := r.enums[fqen]; ok {
- return e, nil
- }
- components = components[:len(components)-1]
- }
- return nil, fmt.Errorf("no enum found: %s", name)
-}
-
-// LookupFile looks up a file by name.
-func (r *Registry) LookupFile(name string) (*File, error) {
- f, ok := r.files[name]
- if !ok {
- return nil, fmt.Errorf("no such file given: %s", name)
- }
- return f, nil
-}
-
-// LookupExternalHTTPRules looks up external http rules by fully qualified service method name
-func (r *Registry) LookupExternalHTTPRules(qualifiedMethodName string) []*annotations.HttpRule {
- return r.externalHTTPRules[qualifiedMethodName]
-}
-
-// AddExternalHTTPRule adds an external http rule for the given fully qualified service method name
-func (r *Registry) AddExternalHTTPRule(qualifiedMethodName string, rule *annotations.HttpRule) {
- r.externalHTTPRules[qualifiedMethodName] = append(r.externalHTTPRules[qualifiedMethodName], rule)
-}
-
-// AddPkgMap adds a mapping from a .proto file to proto package name.
-func (r *Registry) AddPkgMap(file, protoPkg string) {
- r.pkgMap[file] = protoPkg
-}
-
-// SetPrefix registers the prefix to be added to go package paths generated from proto package names.
-func (r *Registry) SetPrefix(prefix string) {
- r.prefix = prefix
-}
-
-// SetImportPath registers the importPath which is used as the package if no
-// input files declare go_package. If it contains slashes, everything up to the
-// rightmost slash is ignored.
-func (r *Registry) SetImportPath(importPath string) {
- r.importPath = importPath
-}
-
-// ReserveGoPackageAlias reserves the unique alias of go package.
-// If succeeded, the alias will be never used for other packages in generated go files.
-// If failed, the alias is already taken by another package, so you need to use another
-// alias for the package in your go files.
-func (r *Registry) ReserveGoPackageAlias(alias, pkgpath string) error {
- if taken, ok := r.pkgAliases[alias]; ok {
- if taken == pkgpath {
- return nil
- }
- return fmt.Errorf("package name %s is already taken. Use another alias", alias)
- }
- r.pkgAliases[alias] = pkgpath
- return nil
-}
-
-// goPackagePath returns the go package path which go files generated from "f" should have.
-// It respects the mapping registered by AddPkgMap if exists. Or use go_package as import path
-// if it includes a slash, Otherwide, it generates a path from the file name of "f".
-func (r *Registry) goPackagePath(f *descriptor.FileDescriptorProto) string {
- name := f.GetName()
- if pkg, ok := r.pkgMap[name]; ok {
- return path.Join(r.prefix, pkg)
- }
-
- gopkg := f.Options.GetGoPackage()
- idx := strings.LastIndex(gopkg, "/")
- if idx >= 0 {
- if sc := strings.LastIndex(gopkg, ";"); sc > 0 {
- gopkg = gopkg[:sc+1-1]
- }
- return gopkg
- }
-
- return path.Join(r.prefix, path.Dir(name))
-}
-
-// GetAllFQMNs returns a list of all FQMNs
-func (r *Registry) GetAllFQMNs() []string {
- var keys []string
- for k := range r.msgs {
- keys = append(keys, k)
- }
- return keys
-}
-
-// GetAllFQENs returns a list of all FQENs
-func (r *Registry) GetAllFQENs() []string {
- var keys []string
- for k := range r.enums {
- keys = append(keys, k)
- }
- return keys
-}
-
-// SetAllowDeleteBody controls whether http delete methods may have a
-// body or fail loading if encountered.
-func (r *Registry) SetAllowDeleteBody(allow bool) {
- r.allowDeleteBody = allow
-}
-
-// SetAllowMerge controls whether generation one swagger file out of multiple protos
-func (r *Registry) SetAllowMerge(allow bool) {
- r.allowMerge = allow
-}
-
-// IsAllowMerge whether generation one swagger file out of multiple protos
-func (r *Registry) IsAllowMerge() bool {
- return r.allowMerge
-}
-
-// SetMergeFileName controls the target swagger file name out of multiple protos
-func (r *Registry) SetMergeFileName(mergeFileName string) {
- r.mergeFileName = mergeFileName
-}
-
-// SetAllowRepeatedFieldsInBody controls whether repeated field can be used
-// in `body` and `response_body` (`google.api.http` annotation option) field path or not
-func (r *Registry) SetAllowRepeatedFieldsInBody(allow bool) {
- r.allowRepeatedFieldsInBody = allow
-}
-
-// IsAllowRepeatedFieldsInBody checks if repeated field can be used
-// in `body` and `response_body` (`google.api.http` annotation option) field path or not
-func (r *Registry) IsAllowRepeatedFieldsInBody() bool {
- return r.allowRepeatedFieldsInBody
-}
-
-// SetIncludePackageInTags controls whether the package name defined in the `package` directive
-// in the proto file can be prepended to the gRPC service name in the `Tags` field of every operation.
-func (r *Registry) SetIncludePackageInTags(allow bool) {
- r.includePackageInTags = allow
-}
-
-// IsIncludePackageInTags checks whether the package name defined in the `package` directive
-// in the proto file can be prepended to the gRPC service name in the `Tags` field of every operation.
-func (r *Registry) IsIncludePackageInTags() bool {
- return r.includePackageInTags
-}
-
-// GetRepeatedPathParamSeparator returns a rune spcifying how
-// path parameter repeated fields are separated.
-func (r *Registry) GetRepeatedPathParamSeparator() rune {
- return r.repeatedPathParamSeparator.sep
-}
-
-// GetRepeatedPathParamSeparatorName returns the name path parameter repeated
-// fields repeatedFieldSeparator. I.e. 'csv', 'pipe', 'ssv' or 'tsv'
-func (r *Registry) GetRepeatedPathParamSeparatorName() string {
- return r.repeatedPathParamSeparator.name
-}
-
-// SetRepeatedPathParamSeparator sets how path parameter repeated fields are
-// separated. Allowed names are 'csv', 'pipe', 'ssv' and 'tsv'.
-func (r *Registry) SetRepeatedPathParamSeparator(name string) error {
- var sep rune
- switch name {
- case "csv":
- sep = ','
- case "pipes":
- sep = '|'
- case "ssv":
- sep = ' '
- case "tsv":
- sep = '\t'
- default:
- return fmt.Errorf("unknown repeated path parameter separator: %s", name)
- }
- r.repeatedPathParamSeparator = repeatedFieldSeparator{
- name: name,
- sep: sep,
- }
- return nil
-}
-
-// SetUseJSONNamesForFields sets useJSONNamesForFields
-func (r *Registry) SetUseJSONNamesForFields(use bool) {
- r.useJSONNamesForFields = use
-}
-
-// GetUseJSONNamesForFields returns useJSONNamesForFields
-func (r *Registry) GetUseJSONNamesForFields() bool {
- return r.useJSONNamesForFields
-}
-
-// SetUseFQNForSwaggerName sets useFQNForSwaggerName
-func (r *Registry) SetUseFQNForSwaggerName(use bool) {
- r.useFQNForSwaggerName = use
-}
-
-// GetAllowColonFinalSegments returns allowColonFinalSegments
-func (r *Registry) GetAllowColonFinalSegments() bool {
- return r.allowColonFinalSegments
-}
-
-// SetAllowColonFinalSegments sets allowColonFinalSegments
-func (r *Registry) SetAllowColonFinalSegments(use bool) {
- r.allowColonFinalSegments = use
-}
-
-// GetUseFQNForSwaggerName returns useFQNForSwaggerName
-func (r *Registry) GetUseFQNForSwaggerName() bool {
- return r.useFQNForSwaggerName
-}
-
-// GetMergeFileName return the target merge swagger file name
-func (r *Registry) GetMergeFileName() string {
- return r.mergeFileName
-}
-
-// SetUseGoTemplate sets useGoTemplate
-func (r *Registry) SetUseGoTemplate(use bool) {
- r.useGoTemplate = use
-}
-
-// GetUseGoTemplate returns useGoTemplate
-func (r *Registry) GetUseGoTemplate() bool {
- return r.useGoTemplate
-}
-
-// sanitizePackageName replaces unallowed character in package name
-// with allowed character.
-func sanitizePackageName(pkgName string) string {
- pkgName = strings.Replace(pkgName, ".", "_", -1)
- pkgName = strings.Replace(pkgName, "-", "_", -1)
- return pkgName
-}
-
-// defaultGoPackageName returns the default go package name to be used for go files generated from "f".
-// You might need to use an unique alias for the package when you import it. Use ReserveGoPackageAlias to get a unique alias.
-func (r *Registry) defaultGoPackageName(f *descriptor.FileDescriptorProto) string {
- name := r.packageIdentityName(f)
- return sanitizePackageName(name)
-}
-
-// packageIdentityName returns the identity of packages.
-// protoc-gen-grpc-gateway rejects CodeGenerationRequests which contains more than one packages
-// as protoc-gen-go does.
-func (r *Registry) packageIdentityName(f *descriptor.FileDescriptorProto) string {
- if f.Options != nil && f.Options.GoPackage != nil {
- gopkg := f.Options.GetGoPackage()
- idx := strings.LastIndex(gopkg, "/")
- if idx < 0 {
- gopkg = gopkg[idx+1:]
- }
-
- gopkg = gopkg[idx+1:]
- // package name is overrided with the string after the
- // ';' character
- sc := strings.IndexByte(gopkg, ';')
- if sc < 0 {
- return sanitizePackageName(gopkg)
-
- }
- return sanitizePackageName(gopkg[sc+1:])
- }
- if p := r.importPath; len(p) != 0 {
- if i := strings.LastIndex(p, "/"); i >= 0 {
- p = p[i+1:]
- }
- return p
- }
-
- if f.Package == nil {
- base := filepath.Base(f.GetName())
- ext := filepath.Ext(base)
- return strings.TrimSuffix(base, ext)
- }
- return f.GetPackage()
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/services.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/services.go
deleted file mode 100644
index 8916d31..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/services.go
+++ /dev/null
@@ -1,304 +0,0 @@
-package descriptor
-
-import (
- "fmt"
- "strings"
-
- "github.com/golang/glog"
- "github.com/golang/protobuf/proto"
- descriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
- "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule"
- options "google.golang.org/genproto/googleapis/api/annotations"
-)
-
-// loadServices registers services and their methods from "targetFile" to "r".
-// It must be called after loadFile is called for all files so that loadServices
-// can resolve names of message types and their fields.
-func (r *Registry) loadServices(file *File) error {
- glog.V(1).Infof("Loading services from %s", file.GetName())
- var svcs []*Service
- for _, sd := range file.GetService() {
- glog.V(2).Infof("Registering %s", sd.GetName())
- svc := &Service{
- File: file,
- ServiceDescriptorProto: sd,
- }
- for _, md := range sd.GetMethod() {
- glog.V(2).Infof("Processing %s.%s", sd.GetName(), md.GetName())
- opts, err := extractAPIOptions(md)
- if err != nil {
- glog.Errorf("Failed to extract HttpRule from %s.%s: %v", svc.GetName(), md.GetName(), err)
- return err
- }
- optsList := r.LookupExternalHTTPRules((&Method{Service: svc, MethodDescriptorProto: md}).FQMN())
- if opts != nil {
- optsList = append(optsList, opts)
- }
- if len(optsList) == 0 {
- glog.V(1).Infof("Found non-target method: %s.%s", svc.GetName(), md.GetName())
- }
- meth, err := r.newMethod(svc, md, optsList)
- if err != nil {
- return err
- }
- svc.Methods = append(svc.Methods, meth)
- }
- if len(svc.Methods) == 0 {
- continue
- }
- glog.V(2).Infof("Registered %s with %d method(s)", svc.GetName(), len(svc.Methods))
- svcs = append(svcs, svc)
- }
- file.Services = svcs
- return nil
-}
-
-func (r *Registry) newMethod(svc *Service, md *descriptor.MethodDescriptorProto, optsList []*options.HttpRule) (*Method, error) {
- requestType, err := r.LookupMsg(svc.File.GetPackage(), md.GetInputType())
- if err != nil {
- return nil, err
- }
- responseType, err := r.LookupMsg(svc.File.GetPackage(), md.GetOutputType())
- if err != nil {
- return nil, err
- }
- meth := &Method{
- Service: svc,
- MethodDescriptorProto: md,
- RequestType: requestType,
- ResponseType: responseType,
- }
-
- newBinding := func(opts *options.HttpRule, idx int) (*Binding, error) {
- var (
- httpMethod string
- pathTemplate string
- )
- switch {
- case opts.GetGet() != "":
- httpMethod = "GET"
- pathTemplate = opts.GetGet()
- if opts.Body != "" {
- return nil, fmt.Errorf("must not set request body when http method is GET: %s", md.GetName())
- }
-
- case opts.GetPut() != "":
- httpMethod = "PUT"
- pathTemplate = opts.GetPut()
-
- case opts.GetPost() != "":
- httpMethod = "POST"
- pathTemplate = opts.GetPost()
-
- case opts.GetDelete() != "":
- httpMethod = "DELETE"
- pathTemplate = opts.GetDelete()
- if opts.Body != "" && !r.allowDeleteBody {
- return nil, fmt.Errorf("must not set request body when http method is DELETE except allow_delete_body option is true: %s", md.GetName())
- }
-
- case opts.GetPatch() != "":
- httpMethod = "PATCH"
- pathTemplate = opts.GetPatch()
-
- case opts.GetCustom() != nil:
- custom := opts.GetCustom()
- httpMethod = custom.Kind
- pathTemplate = custom.Path
-
- default:
- glog.V(1).Infof("No pattern specified in google.api.HttpRule: %s", md.GetName())
- return nil, nil
- }
-
- parsed, err := httprule.Parse(pathTemplate)
- if err != nil {
- return nil, err
- }
- tmpl := parsed.Compile()
-
- if md.GetClientStreaming() && len(tmpl.Fields) > 0 {
- return nil, fmt.Errorf("cannot use path parameter in client streaming")
- }
-
- b := &Binding{
- Method: meth,
- Index: idx,
- PathTmpl: tmpl,
- HTTPMethod: httpMethod,
- }
-
- for _, f := range tmpl.Fields {
- param, err := r.newParam(meth, f)
- if err != nil {
- return nil, err
- }
- b.PathParams = append(b.PathParams, param)
- }
-
- // TODO(yugui) Handle query params
-
- b.Body, err = r.newBody(meth, opts.Body)
- if err != nil {
- return nil, err
- }
-
- b.ResponseBody, err = r.newResponse(meth, opts.ResponseBody)
- if err != nil {
- return nil, err
- }
-
- return b, nil
- }
-
- applyOpts := func(opts *options.HttpRule) error {
- b, err := newBinding(opts, len(meth.Bindings))
- if err != nil {
- return err
- }
-
- if b != nil {
- meth.Bindings = append(meth.Bindings, b)
- }
- for _, additional := range opts.GetAdditionalBindings() {
- if len(additional.AdditionalBindings) > 0 {
- return fmt.Errorf("additional_binding in additional_binding not allowed: %s.%s", svc.GetName(), meth.GetName())
- }
- b, err := newBinding(additional, len(meth.Bindings))
- if err != nil {
- return err
- }
- meth.Bindings = append(meth.Bindings, b)
- }
-
- return nil
- }
-
- for _, opts := range optsList {
- if err := applyOpts(opts); err != nil {
- return nil, err
- }
- }
-
- return meth, nil
-}
-
-func extractAPIOptions(meth *descriptor.MethodDescriptorProto) (*options.HttpRule, error) {
- if meth.Options == nil {
- return nil, nil
- }
- if !proto.HasExtension(meth.Options, options.E_Http) {
- return nil, nil
- }
- ext, err := proto.GetExtension(meth.Options, options.E_Http)
- if err != nil {
- return nil, err
- }
- opts, ok := ext.(*options.HttpRule)
- if !ok {
- return nil, fmt.Errorf("extension is %T; want an HttpRule", ext)
- }
- return opts, nil
-}
-
-func (r *Registry) newParam(meth *Method, path string) (Parameter, error) {
- msg := meth.RequestType
- fields, err := r.resolveFieldPath(msg, path, true)
- if err != nil {
- return Parameter{}, err
- }
- l := len(fields)
- if l == 0 {
- return Parameter{}, fmt.Errorf("invalid field access list for %s", path)
- }
- target := fields[l-1].Target
- switch target.GetType() {
- case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_GROUP:
- glog.V(2).Infoln("found aggregate type:", target, target.TypeName)
- if IsWellKnownType(*target.TypeName) {
- glog.V(2).Infoln("found well known aggregate type:", target)
- } else {
- return Parameter{}, fmt.Errorf("aggregate type %s in parameter of %s.%s: %s", target.Type, meth.Service.GetName(), meth.GetName(), path)
- }
- }
- return Parameter{
- FieldPath: FieldPath(fields),
- Method: meth,
- Target: fields[l-1].Target,
- }, nil
-}
-
-func (r *Registry) newBody(meth *Method, path string) (*Body, error) {
- msg := meth.RequestType
- switch path {
- case "":
- return nil, nil
- case "*":
- return &Body{FieldPath: nil}, nil
- }
- fields, err := r.resolveFieldPath(msg, path, false)
- if err != nil {
- return nil, err
- }
- return &Body{FieldPath: FieldPath(fields)}, nil
-}
-
-func (r *Registry) newResponse(meth *Method, path string) (*Body, error) {
- msg := meth.ResponseType
- switch path {
- case "", "*":
- return nil, nil
- }
- fields, err := r.resolveFieldPath(msg, path, false)
- if err != nil {
- return nil, err
- }
- return &Body{FieldPath: FieldPath(fields)}, nil
-}
-
-// lookupField looks up a field named "name" within "msg".
-// It returns nil if no such field found.
-func lookupField(msg *Message, name string) *Field {
- for _, f := range msg.Fields {
- if f.GetName() == name {
- return f
- }
- }
- return nil
-}
-
-// resolveFieldPath resolves "path" into a list of fieldDescriptor, starting from "msg".
-func (r *Registry) resolveFieldPath(msg *Message, path string, isPathParam bool) ([]FieldPathComponent, error) {
- if path == "" {
- return nil, nil
- }
-
- root := msg
- var result []FieldPathComponent
- for i, c := range strings.Split(path, ".") {
- if i > 0 {
- f := result[i-1].Target
- switch f.GetType() {
- case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_GROUP:
- var err error
- msg, err = r.LookupMsg(msg.FQMN(), f.GetTypeName())
- if err != nil {
- return nil, err
- }
- default:
- return nil, fmt.Errorf("not an aggregate type: %s in %s", f.GetName(), path)
- }
- }
-
- glog.V(2).Infof("Lookup %s in %s", c, msg.FQMN())
- f := lookupField(msg, c)
- if f == nil {
- return nil, fmt.Errorf("no field %q found in %s", path, root.GetName())
- }
- if !(isPathParam || r.allowRepeatedFieldsInBody) && f.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED {
- return nil, fmt.Errorf("repeated field not allowed in field path: %s in %s", f.GetName(), path)
- }
- result = append(result, FieldPathComponent{Name: c, Target: f})
- }
- return result, nil
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/types.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/types.go
deleted file mode 100644
index 4aa75f8..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor/types.go
+++ /dev/null
@@ -1,466 +0,0 @@
-package descriptor
-
-import (
- "fmt"
- "strings"
-
- "github.com/golang/protobuf/protoc-gen-go/descriptor"
- gogen "github.com/golang/protobuf/protoc-gen-go/generator"
- "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule"
-)
-
-// IsWellKnownType returns true if the provided fully qualified type name is considered 'well-known'.
-func IsWellKnownType(typeName string) bool {
- _, ok := wellKnownTypeConv[typeName]
- return ok
-}
-
-// GoPackage represents a golang package
-type GoPackage struct {
- // Path is the package path to the package.
- Path string
- // Name is the package name of the package
- Name string
- // Alias is an alias of the package unique within the current invokation of grpc-gateway generator.
- Alias string
-}
-
-// Standard returns whether the import is a golang standard package.
-func (p GoPackage) Standard() bool {
- return !strings.Contains(p.Path, ".")
-}
-
-// String returns a string representation of this package in the form of import line in golang.
-func (p GoPackage) String() string {
- if p.Alias == "" {
- return fmt.Sprintf("%q", p.Path)
- }
- return fmt.Sprintf("%s %q", p.Alias, p.Path)
-}
-
-// File wraps descriptor.FileDescriptorProto for richer features.
-type File struct {
- *descriptor.FileDescriptorProto
- // GoPkg is the go package of the go file generated from this file..
- GoPkg GoPackage
- // Messages is the list of messages defined in this file.
- Messages []*Message
- // Enums is the list of enums defined in this file.
- Enums []*Enum
- // Services is the list of services defined in this file.
- Services []*Service
-}
-
-// proto2 determines if the syntax of the file is proto2.
-func (f *File) proto2() bool {
- return f.Syntax == nil || f.GetSyntax() == "proto2"
-}
-
-// Message describes a protocol buffer message types
-type Message struct {
- // File is the file where the message is defined
- File *File
- // Outers is a list of outer messages if this message is a nested type.
- Outers []string
- *descriptor.DescriptorProto
- Fields []*Field
-
- // Index is proto path index of this message in File.
- Index int
-}
-
-// FQMN returns a fully qualified message name of this message.
-func (m *Message) FQMN() string {
- components := []string{""}
- if m.File.Package != nil {
- components = append(components, m.File.GetPackage())
- }
- components = append(components, m.Outers...)
- components = append(components, m.GetName())
- return strings.Join(components, ".")
-}
-
-// GoType returns a go type name for the message type.
-// It prefixes the type name with the package alias if
-// its belonging package is not "currentPackage".
-func (m *Message) GoType(currentPackage string) string {
- var components []string
- components = append(components, m.Outers...)
- components = append(components, m.GetName())
-
- name := strings.Join(components, "_")
- if m.File.GoPkg.Path == currentPackage {
- return name
- }
- pkg := m.File.GoPkg.Name
- if alias := m.File.GoPkg.Alias; alias != "" {
- pkg = alias
- }
- return fmt.Sprintf("%s.%s", pkg, name)
-}
-
-// Enum describes a protocol buffer enum types
-type Enum struct {
- // File is the file where the enum is defined
- File *File
- // Outers is a list of outer messages if this enum is a nested type.
- Outers []string
- *descriptor.EnumDescriptorProto
-
- Index int
-}
-
-// FQEN returns a fully qualified enum name of this enum.
-func (e *Enum) FQEN() string {
- components := []string{""}
- if e.File.Package != nil {
- components = append(components, e.File.GetPackage())
- }
- components = append(components, e.Outers...)
- components = append(components, e.GetName())
- return strings.Join(components, ".")
-}
-
-// GoType returns a go type name for the enum type.
-// It prefixes the type name with the package alias if
-// its belonging package is not "currentPackage".
-func (e *Enum) GoType(currentPackage string) string {
- var components []string
- components = append(components, e.Outers...)
- components = append(components, e.GetName())
-
- name := strings.Join(components, "_")
- if e.File.GoPkg.Path == currentPackage {
- return name
- }
- pkg := e.File.GoPkg.Name
- if alias := e.File.GoPkg.Alias; alias != "" {
- pkg = alias
- }
- return fmt.Sprintf("%s.%s", pkg, name)
-}
-
-// Service wraps descriptor.ServiceDescriptorProto for richer features.
-type Service struct {
- // File is the file where this service is defined.
- File *File
- *descriptor.ServiceDescriptorProto
- // Methods is the list of methods defined in this service.
- Methods []*Method
-}
-
-// FQSN returns the fully qualified service name of this service.
-func (s *Service) FQSN() string {
- components := []string{""}
- if s.File.Package != nil {
- components = append(components, s.File.GetPackage())
- }
- components = append(components, s.GetName())
- return strings.Join(components, ".")
-}
-
-// Method wraps descriptor.MethodDescriptorProto for richer features.
-type Method struct {
- // Service is the service which this method belongs to.
- Service *Service
- *descriptor.MethodDescriptorProto
-
- // RequestType is the message type of requests to this method.
- RequestType *Message
- // ResponseType is the message type of responses from this method.
- ResponseType *Message
- Bindings []*Binding
-}
-
-// FQMN returns a fully qualified rpc method name of this method.
-func (m *Method) FQMN() string {
- components := []string{}
- components = append(components, m.Service.FQSN())
- components = append(components, m.GetName())
- return strings.Join(components, ".")
-}
-
-// Binding describes how an HTTP endpoint is bound to a gRPC method.
-type Binding struct {
- // Method is the method which the endpoint is bound to.
- Method *Method
- // Index is a zero-origin index of the binding in the target method
- Index int
- // PathTmpl is path template where this method is mapped to.
- PathTmpl httprule.Template
- // HTTPMethod is the HTTP method which this method is mapped to.
- HTTPMethod string
- // PathParams is the list of parameters provided in HTTP request paths.
- PathParams []Parameter
- // Body describes parameters provided in HTTP request body.
- Body *Body
- // ResponseBody describes field in response struct to marshal in HTTP response body.
- ResponseBody *Body
-}
-
-// ExplicitParams returns a list of explicitly bound parameters of "b",
-// i.e. a union of field path for body and field paths for path parameters.
-func (b *Binding) ExplicitParams() []string {
- var result []string
- if b.Body != nil {
- result = append(result, b.Body.FieldPath.String())
- }
- for _, p := range b.PathParams {
- result = append(result, p.FieldPath.String())
- }
- return result
-}
-
-// Field wraps descriptor.FieldDescriptorProto for richer features.
-type Field struct {
- // Message is the message type which this field belongs to.
- Message *Message
- // FieldMessage is the message type of the field.
- FieldMessage *Message
- *descriptor.FieldDescriptorProto
-}
-
-// Parameter is a parameter provided in http requests
-type Parameter struct {
- // FieldPath is a path to a proto field which this parameter is mapped to.
- FieldPath
- // Target is the proto field which this parameter is mapped to.
- Target *Field
- // Method is the method which this parameter is used for.
- Method *Method
-}
-
-// ConvertFuncExpr returns a go expression of a converter function.
-// The converter function converts a string into a value for the parameter.
-func (p Parameter) ConvertFuncExpr() (string, error) {
- tbl := proto3ConvertFuncs
- if !p.IsProto2() && p.IsRepeated() {
- tbl = proto3RepeatedConvertFuncs
- } else if p.IsProto2() && !p.IsRepeated() {
- tbl = proto2ConvertFuncs
- } else if p.IsProto2() && p.IsRepeated() {
- tbl = proto2RepeatedConvertFuncs
- }
- typ := p.Target.GetType()
- conv, ok := tbl[typ]
- if !ok {
- conv, ok = wellKnownTypeConv[p.Target.GetTypeName()]
- }
- if !ok {
- return "", fmt.Errorf("unsupported field type %s of parameter %s in %s.%s", typ, p.FieldPath, p.Method.Service.GetName(), p.Method.GetName())
- }
- return conv, nil
-}
-
-// IsEnum returns true if the field is an enum type, otherwise false is returned.
-func (p Parameter) IsEnum() bool {
- return p.Target.GetType() == descriptor.FieldDescriptorProto_TYPE_ENUM
-}
-
-// IsRepeated returns true if the field is repeated, otherwise false is returned.
-func (p Parameter) IsRepeated() bool {
- return p.Target.GetLabel() == descriptor.FieldDescriptorProto_LABEL_REPEATED
-}
-
-// IsProto2 returns true if the field is proto2, otherwise false is returned.
-func (p Parameter) IsProto2() bool {
- return p.Target.Message.File.proto2()
-}
-
-// Body describes a http (request|response) body to be sent to the (method|client).
-// This is used in body and response_body options in google.api.HttpRule
-type Body struct {
- // FieldPath is a path to a proto field which the (request|response) body is mapped to.
- // The (request|response) body is mapped to the (request|response) type itself if FieldPath is empty.
- FieldPath FieldPath
-}
-
-// AssignableExpr returns an assignable expression in Go to be used to initialize method request object.
-// It starts with "msgExpr", which is the go expression of the method request object.
-func (b Body) AssignableExpr(msgExpr string) string {
- return b.FieldPath.AssignableExpr(msgExpr)
-}
-
-// FieldPath is a path to a field from a request message.
-type FieldPath []FieldPathComponent
-
-// String returns a string representation of the field path.
-func (p FieldPath) String() string {
- var components []string
- for _, c := range p {
- components = append(components, c.Name)
- }
- return strings.Join(components, ".")
-}
-
-// IsNestedProto3 indicates whether the FieldPath is a nested Proto3 path.
-func (p FieldPath) IsNestedProto3() bool {
- if len(p) > 1 && !p[0].Target.Message.File.proto2() {
- return true
- }
- return false
-}
-
-// AssignableExpr is an assignable expression in Go to be used to assign a value to the target field.
-// It starts with "msgExpr", which is the go expression of the method request object.
-func (p FieldPath) AssignableExpr(msgExpr string) string {
- l := len(p)
- if l == 0 {
- return msgExpr
- }
-
- var preparations []string
- components := msgExpr
- for i, c := range p {
- // Check if it is a oneOf field.
- if c.Target.OneofIndex != nil {
- index := c.Target.OneofIndex
- msg := c.Target.Message
- oneOfName := gogen.CamelCase(msg.GetOneofDecl()[*index].GetName())
- oneofFieldName := msg.GetName() + "_" + c.AssignableExpr()
-
- components = components + "." + oneOfName
- s := `if %s == nil {
- %s =&%s{}
- } else if _, ok := %s.(*%s); !ok {
- return nil, metadata, grpc.Errorf(codes.InvalidArgument, "expect type: *%s, but: %%t\n",%s)
- }`
-
- preparations = append(preparations, fmt.Sprintf(s, components, components, oneofFieldName, components, oneofFieldName, oneofFieldName, components))
- components = components + ".(*" + oneofFieldName + ")"
- }
-
- if i == l-1 {
- components = components + "." + c.AssignableExpr()
- continue
- }
- components = components + "." + c.ValueExpr()
- }
-
- preparations = append(preparations, components)
- return strings.Join(preparations, "\n")
-}
-
-// FieldPathComponent is a path component in FieldPath
-type FieldPathComponent struct {
- // Name is a name of the proto field which this component corresponds to.
- // TODO(yugui) is this necessary?
- Name string
- // Target is the proto field which this component corresponds to.
- Target *Field
-}
-
-// AssignableExpr returns an assignable expression in go for this field.
-func (c FieldPathComponent) AssignableExpr() string {
- return gogen.CamelCase(c.Name)
-}
-
-// ValueExpr returns an expression in go for this field.
-func (c FieldPathComponent) ValueExpr() string {
- if c.Target.Message.File.proto2() {
- return fmt.Sprintf("Get%s()", gogen.CamelCase(c.Name))
- }
- return gogen.CamelCase(c.Name)
-}
-
-var (
- proto3ConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{
- descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64",
- descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32",
- descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64",
- descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64",
- descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32",
- descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64",
- descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32",
- descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.Bool",
- descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.String",
- // FieldDescriptorProto_TYPE_GROUP
- // FieldDescriptorProto_TYPE_MESSAGE
- descriptor.FieldDescriptorProto_TYPE_BYTES: "runtime.Bytes",
- descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32",
- descriptor.FieldDescriptorProto_TYPE_ENUM: "runtime.Enum",
- descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32",
- descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64",
- descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32",
- descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64",
- }
-
- proto3RepeatedConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{
- descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64Slice",
- descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32Slice",
- descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64Slice",
- descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64Slice",
- descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32Slice",
- descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64Slice",
- descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32Slice",
- descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolSlice",
- descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.StringSlice",
- // FieldDescriptorProto_TYPE_GROUP
- // FieldDescriptorProto_TYPE_MESSAGE
- descriptor.FieldDescriptorProto_TYPE_BYTES: "runtime.BytesSlice",
- descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32Slice",
- descriptor.FieldDescriptorProto_TYPE_ENUM: "runtime.EnumSlice",
- descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32Slice",
- descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64Slice",
- descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32Slice",
- descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64Slice",
- }
-
- proto2ConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{
- descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64P",
- descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32P",
- descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64P",
- descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64P",
- descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32P",
- descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64P",
- descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32P",
- descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolP",
- descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.StringP",
- // FieldDescriptorProto_TYPE_GROUP
- // FieldDescriptorProto_TYPE_MESSAGE
- // FieldDescriptorProto_TYPE_BYTES
- // TODO(yugui) Handle bytes
- descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32P",
- descriptor.FieldDescriptorProto_TYPE_ENUM: "runtime.EnumP",
- descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32P",
- descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64P",
- descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32P",
- descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64P",
- }
-
- proto2RepeatedConvertFuncs = map[descriptor.FieldDescriptorProto_Type]string{
- descriptor.FieldDescriptorProto_TYPE_DOUBLE: "runtime.Float64Slice",
- descriptor.FieldDescriptorProto_TYPE_FLOAT: "runtime.Float32Slice",
- descriptor.FieldDescriptorProto_TYPE_INT64: "runtime.Int64Slice",
- descriptor.FieldDescriptorProto_TYPE_UINT64: "runtime.Uint64Slice",
- descriptor.FieldDescriptorProto_TYPE_INT32: "runtime.Int32Slice",
- descriptor.FieldDescriptorProto_TYPE_FIXED64: "runtime.Uint64Slice",
- descriptor.FieldDescriptorProto_TYPE_FIXED32: "runtime.Uint32Slice",
- descriptor.FieldDescriptorProto_TYPE_BOOL: "runtime.BoolSlice",
- descriptor.FieldDescriptorProto_TYPE_STRING: "runtime.StringSlice",
- // FieldDescriptorProto_TYPE_GROUP
- // FieldDescriptorProto_TYPE_MESSAGE
- // FieldDescriptorProto_TYPE_BYTES
- // TODO(maros7) Handle bytes
- descriptor.FieldDescriptorProto_TYPE_UINT32: "runtime.Uint32Slice",
- descriptor.FieldDescriptorProto_TYPE_ENUM: "runtime.EnumSlice",
- descriptor.FieldDescriptorProto_TYPE_SFIXED32: "runtime.Int32Slice",
- descriptor.FieldDescriptorProto_TYPE_SFIXED64: "runtime.Int64Slice",
- descriptor.FieldDescriptorProto_TYPE_SINT32: "runtime.Int32Slice",
- descriptor.FieldDescriptorProto_TYPE_SINT64: "runtime.Int64Slice",
- }
-
- wellKnownTypeConv = map[string]string{
- ".google.protobuf.Timestamp": "runtime.Timestamp",
- ".google.protobuf.Duration": "runtime.Duration",
- ".google.protobuf.StringValue": "runtime.StringValue",
- ".google.protobuf.FloatValue": "runtime.FloatValue",
- ".google.protobuf.DoubleValue": "runtime.DoubleValue",
- ".google.protobuf.BoolValue": "runtime.BoolValue",
- ".google.protobuf.BytesValue": "runtime.BytesValue",
- ".google.protobuf.Int32Value": "runtime.Int32Value",
- ".google.protobuf.UInt32Value": "runtime.UInt32Value",
- ".google.protobuf.Int64Value": "runtime.Int64Value",
- ".google.protobuf.UInt64Value": "runtime.UInt64Value",
- }
-)
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/BUILD.bazel
deleted file mode 100644
index 6cb2162..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/BUILD.bazel
+++ /dev/null
@@ -1,13 +0,0 @@
-load("@io_bazel_rules_go//go:def.bzl", "go_library")
-
-package(default_visibility = ["//:generators"])
-
-go_library(
- name = "go_default_library",
- srcs = ["generator.go"],
- importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator",
- deps = [
- "//protoc-gen-grpc-gateway/descriptor:go_default_library",
- "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto",
- ],
-)
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/generator.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/generator.go
deleted file mode 100644
index df55da4..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator/generator.go
+++ /dev/null
@@ -1,13 +0,0 @@
-// Package generator provides an abstract interface to code generators.
-package generator
-
-import (
- plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
- "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
-)
-
-// Generator is an abstraction of code generators.
-type Generator interface {
- // Generate generates output files from input .proto files.
- Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error)
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/BUILD.bazel
deleted file mode 100644
index 316010f..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/BUILD.bazel
+++ /dev/null
@@ -1,38 +0,0 @@
-load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
-
-package(default_visibility = ["//protoc-gen-grpc-gateway:__subpackages__"])
-
-go_library(
- name = "go_default_library",
- srcs = [
- "doc.go",
- "generator.go",
- "template.go",
- ],
- importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway",
- deps = [
- "//protoc-gen-grpc-gateway/descriptor:go_default_library",
- "//protoc-gen-grpc-gateway/generator:go_default_library",
- "//utilities:go_default_library",
- "@com_github_golang_glog//:go_default_library",
- "@com_github_golang_protobuf//proto:go_default_library",
- "@com_github_golang_protobuf//protoc-gen-go/generator:go_default_library_gen",
- "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto",
- ],
-)
-
-go_test(
- name = "go_default_test",
- size = "small",
- srcs = [
- "generator_test.go",
- "template_test.go",
- ],
- embed = [":go_default_library"],
- deps = [
- "//protoc-gen-grpc-gateway/descriptor:go_default_library",
- "//protoc-gen-grpc-gateway/httprule:go_default_library",
- "@com_github_golang_protobuf//proto:go_default_library",
- "@io_bazel_rules_go//proto/wkt:descriptor_go_proto",
- ],
-)
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/doc.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/doc.go
deleted file mode 100644
index 223d810..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/doc.go
+++ /dev/null
@@ -1,2 +0,0 @@
-// Package gengateway provides a code generator for grpc gateway files.
-package gengateway
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/generator.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/generator.go
deleted file mode 100644
index 0b6bfbd..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/generator.go
+++ /dev/null
@@ -1,171 +0,0 @@
-package gengateway
-
-import (
- "errors"
- "fmt"
- "go/format"
- "path"
- "path/filepath"
- "strings"
-
- "github.com/golang/glog"
- "github.com/golang/protobuf/proto"
- plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
- "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
- gen "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator"
-)
-
-var (
- errNoTargetService = errors.New("no target service defined in the file")
-)
-
-type pathType int
-
-const (
- pathTypeImport pathType = iota
- pathTypeSourceRelative
-)
-
-type generator struct {
- reg *descriptor.Registry
- baseImports []descriptor.GoPackage
- useRequestContext bool
- registerFuncSuffix string
- pathType pathType
- allowPatchFeature bool
-}
-
-// New returns a new generator which generates grpc gateway files.
-func New(reg *descriptor.Registry, useRequestContext bool, registerFuncSuffix, pathTypeString string, allowPatchFeature bool) gen.Generator {
- var imports []descriptor.GoPackage
- for _, pkgpath := range []string{
- "context",
- "io",
- "net/http",
- "github.com/grpc-ecosystem/grpc-gateway/runtime",
- "github.com/grpc-ecosystem/grpc-gateway/utilities",
- "github.com/golang/protobuf/descriptor",
- "github.com/golang/protobuf/proto",
- "google.golang.org/grpc",
- "google.golang.org/grpc/codes",
- "google.golang.org/grpc/grpclog",
- "google.golang.org/grpc/status",
- } {
- pkg := descriptor.GoPackage{
- Path: pkgpath,
- Name: path.Base(pkgpath),
- }
- if err := reg.ReserveGoPackageAlias(pkg.Name, pkg.Path); err != nil {
- for i := 0; ; i++ {
- alias := fmt.Sprintf("%s_%d", pkg.Name, i)
- if err := reg.ReserveGoPackageAlias(alias, pkg.Path); err != nil {
- continue
- }
- pkg.Alias = alias
- break
- }
- }
- imports = append(imports, pkg)
- }
-
- var pathType pathType
- switch pathTypeString {
- case "", "import":
- // paths=import is default
- case "source_relative":
- pathType = pathTypeSourceRelative
- default:
- glog.Fatalf(`Unknown path type %q: want "import" or "source_relative".`, pathTypeString)
- }
-
- return &generator{
- reg: reg,
- baseImports: imports,
- useRequestContext: useRequestContext,
- registerFuncSuffix: registerFuncSuffix,
- pathType: pathType,
- allowPatchFeature: allowPatchFeature,
- }
-}
-
-func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) {
- var files []*plugin.CodeGeneratorResponse_File
- for _, file := range targets {
- glog.V(1).Infof("Processing %s", file.GetName())
- code, err := g.generate(file)
- if err == errNoTargetService {
- glog.V(1).Infof("%s: %v", file.GetName(), err)
- continue
- }
- if err != nil {
- return nil, err
- }
- formatted, err := format.Source([]byte(code))
- if err != nil {
- glog.Errorf("%v: %s", err, code)
- return nil, err
- }
- name := file.GetName()
- if g.pathType == pathTypeImport && file.GoPkg.Path != "" {
- name = fmt.Sprintf("%s/%s", file.GoPkg.Path, filepath.Base(name))
- }
- ext := filepath.Ext(name)
- base := strings.TrimSuffix(name, ext)
- output := fmt.Sprintf("%s.pb.gw.go", base)
- files = append(files, &plugin.CodeGeneratorResponse_File{
- Name: proto.String(output),
- Content: proto.String(string(formatted)),
- })
- glog.V(1).Infof("Will emit %s", output)
- }
- return files, nil
-}
-
-func (g *generator) generate(file *descriptor.File) (string, error) {
- pkgSeen := make(map[string]bool)
- var imports []descriptor.GoPackage
- for _, pkg := range g.baseImports {
- pkgSeen[pkg.Path] = true
- imports = append(imports, pkg)
- }
- for _, svc := range file.Services {
- for _, m := range svc.Methods {
- imports = append(imports, g.addEnumPathParamImports(file, m, pkgSeen)...)
- pkg := m.RequestType.File.GoPkg
- if len(m.Bindings) == 0 ||
- pkg == file.GoPkg || pkgSeen[pkg.Path] {
- continue
- }
- pkgSeen[pkg.Path] = true
- imports = append(imports, pkg)
- }
- }
- params := param{
- File: file,
- Imports: imports,
- UseRequestContext: g.useRequestContext,
- RegisterFuncSuffix: g.registerFuncSuffix,
- AllowPatchFeature: g.allowPatchFeature,
- }
- return applyTemplate(params, g.reg)
-}
-
-// addEnumPathParamImports handles adding import of enum path parameter go packages
-func (g *generator) addEnumPathParamImports(file *descriptor.File, m *descriptor.Method, pkgSeen map[string]bool) []descriptor.GoPackage {
- var imports []descriptor.GoPackage
- for _, b := range m.Bindings {
- for _, p := range b.PathParams {
- e, err := g.reg.LookupEnum("", p.Target.GetTypeName())
- if err != nil {
- continue
- }
- pkg := e.File.GoPkg
- if pkg == file.GoPkg || pkgSeen[pkg.Path] {
- continue
- }
- pkgSeen[pkg.Path] = true
- imports = append(imports, pkg)
- }
- }
- return imports
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/template.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/template.go
deleted file mode 100644
index 1d3d3ca..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway/template.go
+++ /dev/null
@@ -1,715 +0,0 @@
-package gengateway
-
-import (
- "bytes"
- "errors"
- "fmt"
- "strings"
- "text/template"
-
- "github.com/golang/glog"
- generator2 "github.com/golang/protobuf/protoc-gen-go/generator"
- "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
- "github.com/grpc-ecosystem/grpc-gateway/utilities"
-)
-
-type param struct {
- *descriptor.File
- Imports []descriptor.GoPackage
- UseRequestContext bool
- RegisterFuncSuffix string
- AllowPatchFeature bool
-}
-
-type binding struct {
- *descriptor.Binding
- Registry *descriptor.Registry
- AllowPatchFeature bool
-}
-
-// GetBodyFieldPath returns the binding body's fieldpath.
-func (b binding) GetBodyFieldPath() string {
- if b.Body != nil && len(b.Body.FieldPath) != 0 {
- return b.Body.FieldPath.String()
- }
- return "*"
-}
-
-// GetBodyFieldPath returns the binding body's struct field name.
-func (b binding) GetBodyFieldStructName() (string, error) {
- if b.Body != nil && len(b.Body.FieldPath) != 0 {
- return generator2.CamelCase(b.Body.FieldPath.String()), nil
- }
- return "", errors.New("No body field found")
-}
-
-// HasQueryParam determines if the binding needs parameters in query string.
-//
-// It sometimes returns true even though actually the binding does not need.
-// But it is not serious because it just results in a small amount of extra codes generated.
-func (b binding) HasQueryParam() bool {
- if b.Body != nil && len(b.Body.FieldPath) == 0 {
- return false
- }
- fields := make(map[string]bool)
- for _, f := range b.Method.RequestType.Fields {
- fields[f.GetName()] = true
- }
- if b.Body != nil {
- delete(fields, b.Body.FieldPath.String())
- }
- for _, p := range b.PathParams {
- delete(fields, p.FieldPath.String())
- }
- return len(fields) > 0
-}
-
-func (b binding) QueryParamFilter() queryParamFilter {
- var seqs [][]string
- if b.Body != nil {
- seqs = append(seqs, strings.Split(b.Body.FieldPath.String(), "."))
- }
- for _, p := range b.PathParams {
- seqs = append(seqs, strings.Split(p.FieldPath.String(), "."))
- }
- return queryParamFilter{utilities.NewDoubleArray(seqs)}
-}
-
-// HasEnumPathParam returns true if the path parameter slice contains a parameter
-// that maps to an enum proto field that is not repeated, if not false is returned.
-func (b binding) HasEnumPathParam() bool {
- return b.hasEnumPathParam(false)
-}
-
-// HasRepeatedEnumPathParam returns true if the path parameter slice contains a parameter
-// that maps to a repeated enum proto field, if not false is returned.
-func (b binding) HasRepeatedEnumPathParam() bool {
- return b.hasEnumPathParam(true)
-}
-
-// hasEnumPathParam returns true if the path parameter slice contains a parameter
-// that maps to a enum proto field and that the enum proto field is or isn't repeated
-// based on the provided 'repeated' parameter.
-func (b binding) hasEnumPathParam(repeated bool) bool {
- for _, p := range b.PathParams {
- if p.IsEnum() && p.IsRepeated() == repeated {
- return true
- }
- }
- return false
-}
-
-// LookupEnum looks up a enum type by path parameter.
-func (b binding) LookupEnum(p descriptor.Parameter) *descriptor.Enum {
- e, err := b.Registry.LookupEnum("", p.Target.GetTypeName())
- if err != nil {
- return nil
- }
- return e
-}
-
-// FieldMaskField returns the golang-style name of the variable for a FieldMask, if there is exactly one of that type in
-// the message. Otherwise, it returns an empty string.
-func (b binding) FieldMaskField() string {
- var fieldMaskField *descriptor.Field
- for _, f := range b.Method.RequestType.Fields {
- if f.GetTypeName() == ".google.protobuf.FieldMask" {
- // if there is more than 1 FieldMask for this request, then return none
- if fieldMaskField != nil {
- return ""
- }
- fieldMaskField = f
- }
- }
- if fieldMaskField != nil {
- return generator2.CamelCase(fieldMaskField.GetName())
- }
- return ""
-}
-
-// queryParamFilter is a wrapper of utilities.DoubleArray which provides String() to output DoubleArray.Encoding in a stable and predictable format.
-type queryParamFilter struct {
- *utilities.DoubleArray
-}
-
-func (f queryParamFilter) String() string {
- encodings := make([]string, len(f.Encoding))
- for str, enc := range f.Encoding {
- encodings[enc] = fmt.Sprintf("%q: %d", str, enc)
- }
- e := strings.Join(encodings, ", ")
- return fmt.Sprintf("&utilities.DoubleArray{Encoding: map[string]int{%s}, Base: %#v, Check: %#v}", e, f.Base, f.Check)
-}
-
-type trailerParams struct {
- Services []*descriptor.Service
- UseRequestContext bool
- RegisterFuncSuffix string
- AssumeColonVerb bool
-}
-
-func applyTemplate(p param, reg *descriptor.Registry) (string, error) {
- w := bytes.NewBuffer(nil)
- if err := headerTemplate.Execute(w, p); err != nil {
- return "", err
- }
- var targetServices []*descriptor.Service
-
- for _, msg := range p.Messages {
- msgName := generator2.CamelCase(*msg.Name)
- msg.Name = &msgName
- }
- for _, svc := range p.Services {
- var methodWithBindingsSeen bool
- svcName := generator2.CamelCase(*svc.Name)
- svc.Name = &svcName
- for _, meth := range svc.Methods {
- glog.V(2).Infof("Processing %s.%s", svc.GetName(), meth.GetName())
- methName := generator2.CamelCase(*meth.Name)
- meth.Name = &methName
- for _, b := range meth.Bindings {
- methodWithBindingsSeen = true
- if err := handlerTemplate.Execute(w, binding{
- Binding: b,
- Registry: reg,
- AllowPatchFeature: p.AllowPatchFeature,
- }); err != nil {
- return "", err
- }
-
- // Local
- if err := localHandlerTemplate.Execute(w, binding{
- Binding: b,
- Registry: reg,
- AllowPatchFeature: p.AllowPatchFeature,
- }); err != nil {
- return "", err
- }
- }
- }
- if methodWithBindingsSeen {
- targetServices = append(targetServices, svc)
- }
- }
- if len(targetServices) == 0 {
- return "", errNoTargetService
- }
-
- assumeColonVerb := true
- if reg != nil {
- assumeColonVerb = !reg.GetAllowColonFinalSegments()
- }
- tp := trailerParams{
- Services: targetServices,
- UseRequestContext: p.UseRequestContext,
- RegisterFuncSuffix: p.RegisterFuncSuffix,
- AssumeColonVerb: assumeColonVerb,
- }
- // Local
- if err := localTrailerTemplate.Execute(w, tp); err != nil {
- return "", err
- }
-
- if err := trailerTemplate.Execute(w, tp); err != nil {
- return "", err
- }
- return w.String(), nil
-}
-
-var (
- headerTemplate = template.Must(template.New("header").Parse(`
-// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
-// source: {{.GetName}}
-
-/*
-Package {{.GoPkg.Name}} is a reverse proxy.
-
-It translates gRPC into RESTful JSON APIs.
-*/
-package {{.GoPkg.Name}}
-import (
- {{range $i := .Imports}}{{if $i.Standard}}{{$i | printf "%s\n"}}{{end}}{{end}}
-
- {{range $i := .Imports}}{{if not $i.Standard}}{{$i | printf "%s\n"}}{{end}}{{end}}
-)
-
-// Suppress "imported and not used" errors
-var _ codes.Code
-var _ io.Reader
-var _ status.Status
-var _ = runtime.String
-var _ = utilities.NewDoubleArray
-var _ = descriptor.ForMessage
-`))
-
- handlerTemplate = template.Must(template.New("handler").Parse(`
-{{if and .Method.GetClientStreaming .Method.GetServerStreaming}}
-{{template "bidi-streaming-request-func" .}}
-{{else if .Method.GetClientStreaming}}
-{{template "client-streaming-request-func" .}}
-{{else}}
-{{template "client-rpc-request-func" .}}
-{{end}}
-`))
-
- _ = template.Must(handlerTemplate.New("request-func-signature").Parse(strings.Replace(`
-{{if .Method.GetServerStreaming}}
-func request_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}(ctx context.Context, marshaler runtime.Marshaler, client {{.Method.Service.GetName}}Client, req *http.Request, pathParams map[string]string) ({{.Method.Service.GetName}}_{{.Method.GetName}}Client, runtime.ServerMetadata, error)
-{{else}}
-func request_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}(ctx context.Context, marshaler runtime.Marshaler, client {{.Method.Service.GetName}}Client, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error)
-{{end}}`, "\n", "", -1)))
-
- _ = template.Must(handlerTemplate.New("client-streaming-request-func").Parse(`
-{{template "request-func-signature" .}} {
- var metadata runtime.ServerMetadata
- stream, err := client.{{.Method.GetName}}(ctx)
- if err != nil {
- grpclog.Infof("Failed to start streaming: %v", err)
- return nil, metadata, err
- }
- dec := marshaler.NewDecoder(req.Body)
- for {
- var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}}
- err = dec.Decode(&protoReq)
- if err == io.EOF {
- break
- }
- if err != nil {
- grpclog.Infof("Failed to decode request: %v", err)
- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
- }
- if err = stream.Send(&protoReq); err != nil {
- if err == io.EOF {
- break
- }
- grpclog.Infof("Failed to send request: %v", err)
- return nil, metadata, err
- }
- }
-
- if err := stream.CloseSend(); err != nil {
- grpclog.Infof("Failed to terminate client stream: %v", err)
- return nil, metadata, err
- }
- header, err := stream.Header()
- if err != nil {
- grpclog.Infof("Failed to get header from client: %v", err)
- return nil, metadata, err
- }
- metadata.HeaderMD = header
-{{if .Method.GetServerStreaming}}
- return stream, metadata, nil
-{{else}}
- msg, err := stream.CloseAndRecv()
- metadata.TrailerMD = stream.Trailer()
- return msg, metadata, err
-{{end}}
-}
-`))
-
- _ = template.Must(handlerTemplate.New("client-rpc-request-func").Parse(`
-{{$AllowPatchFeature := .AllowPatchFeature}}
-{{if .HasQueryParam}}
-var (
- filter_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}} = {{.QueryParamFilter}}
-)
-{{end}}
-{{template "request-func-signature" .}} {
- var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}}
- var metadata runtime.ServerMetadata
-{{if .Body}}
- newReader, berr := utilities.IOReaderFactory(req.Body)
- if berr != nil {
- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
- }
- if err := marshaler.NewDecoder(newReader()).Decode(&{{.Body.AssignableExpr "protoReq"}}); err != nil && err != io.EOF {
- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
- }
- {{- if and $AllowPatchFeature (eq (.HTTPMethod) "PATCH") (.FieldMaskField) (not (eq "*" .GetBodyFieldPath)) }}
- if protoReq.{{.FieldMaskField}} == nil || len(protoReq.{{.FieldMaskField}}.GetPaths()) == 0 {
- _, md := descriptor.ForMessage(protoReq.{{.GetBodyFieldStructName}})
- if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader(), md); err != nil {
- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
- } else {
- protoReq.{{.FieldMaskField}} = fieldMask
- }
- }
- {{end}}
-{{end}}
-{{if .PathParams}}
- var (
- val string
-{{- if .HasEnumPathParam}}
- e int32
-{{- end}}
-{{- if .HasRepeatedEnumPathParam}}
- es []int32
-{{- end}}
- ok bool
- err error
- _ = err
- )
- {{$binding := .}}
- {{range $param := .PathParams}}
- {{$enum := $binding.LookupEnum $param}}
- val, ok = pathParams[{{$param | printf "%q"}}]
- if !ok {
- return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", {{$param | printf "%q"}})
- }
-{{if $param.IsNestedProto3}}
- err = runtime.PopulateFieldFromPath(&protoReq, {{$param | printf "%q"}}, val)
- {{if $enum}}
- e{{if $param.IsRepeated}}s{{end}}, err = {{$param.ConvertFuncExpr}}(val{{if $param.IsRepeated}}, {{$binding.Registry.GetRepeatedPathParamSeparator | printf "%c" | printf "%q"}}{{end}}, {{$enum.GoType $param.Target.Message.File.GoPkg.Path}}_value)
- {{end}}
-{{else if $enum}}
- e{{if $param.IsRepeated}}s{{end}}, err = {{$param.ConvertFuncExpr}}(val{{if $param.IsRepeated}}, {{$binding.Registry.GetRepeatedPathParamSeparator | printf "%c" | printf "%q"}}{{end}}, {{$enum.GoType $param.Target.Message.File.GoPkg.Path}}_value)
-{{else}}
- {{$param.AssignableExpr "protoReq"}}, err = {{$param.ConvertFuncExpr}}(val{{if $param.IsRepeated}}, {{$binding.Registry.GetRepeatedPathParamSeparator | printf "%c" | printf "%q"}}{{end}})
-{{end}}
- if err != nil {
- return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", {{$param | printf "%q"}}, err)
- }
-{{if and $enum $param.IsRepeated}}
- s := make([]{{$enum.GoType $param.Target.Message.File.GoPkg.Path}}, len(es))
- for i, v := range es {
- s[i] = {{$enum.GoType $param.Target.Message.File.GoPkg.Path}}(v)
- }
- {{$param.AssignableExpr "protoReq"}} = s
-{{else if $enum}}
- {{$param.AssignableExpr "protoReq"}} = {{$enum.GoType $param.Target.Message.File.GoPkg.Path}}(e)
-{{end}}
- {{end}}
-{{end}}
-{{if .HasQueryParam}}
- if err := req.ParseForm(); err != nil {
- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
- }
- if err := runtime.PopulateQueryParameters(&protoReq, req.Form, filter_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}); err != nil {
- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
- }
-{{end}}
-{{if .Method.GetServerStreaming}}
- stream, err := client.{{.Method.GetName}}(ctx, &protoReq)
- if err != nil {
- return nil, metadata, err
- }
- header, err := stream.Header()
- if err != nil {
- return nil, metadata, err
- }
- metadata.HeaderMD = header
- return stream, metadata, nil
-{{else}}
- msg, err := client.{{.Method.GetName}}(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
- return msg, metadata, err
-{{end}}
-}`))
-
- _ = template.Must(handlerTemplate.New("bidi-streaming-request-func").Parse(`
-{{template "request-func-signature" .}} {
- var metadata runtime.ServerMetadata
- stream, err := client.{{.Method.GetName}}(ctx)
- if err != nil {
- grpclog.Infof("Failed to start streaming: %v", err)
- return nil, metadata, err
- }
- dec := marshaler.NewDecoder(req.Body)
- handleSend := func() error {
- var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}}
- err := dec.Decode(&protoReq)
- if err == io.EOF {
- return err
- }
- if err != nil {
- grpclog.Infof("Failed to decode request: %v", err)
- return err
- }
- if err := stream.Send(&protoReq); err != nil {
- grpclog.Infof("Failed to send request: %v", err)
- return err
- }
- return nil
- }
- if err := handleSend(); err != nil {
- if cerr := stream.CloseSend(); cerr != nil {
- grpclog.Infof("Failed to terminate client stream: %v", cerr)
- }
- if err == io.EOF {
- return stream, metadata, nil
- }
- return nil, metadata, err
- }
- go func() {
- for {
- if err := handleSend(); err != nil {
- break
- }
- }
- if err := stream.CloseSend(); err != nil {
- grpclog.Infof("Failed to terminate client stream: %v", err)
- }
- }()
- header, err := stream.Header()
- if err != nil {
- grpclog.Infof("Failed to get header from client: %v", err)
- return nil, metadata, err
- }
- metadata.HeaderMD = header
- return stream, metadata, nil
-}
-`))
-
- localHandlerTemplate = template.Must(template.New("local-handler").Parse(`
-{{if and .Method.GetClientStreaming .Method.GetServerStreaming}}
-{{else if .Method.GetClientStreaming}}
-{{else if .Method.GetServerStreaming}}
-{{else}}
-{{template "local-client-rpc-request-func" .}}
-{{end}}
-`))
-
- _ = template.Must(localHandlerTemplate.New("local-request-func-signature").Parse(strings.Replace(`
-{{if .Method.GetServerStreaming}}
-{{else}}
-func local_request_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}(ctx context.Context, marshaler runtime.Marshaler, server {{.Method.Service.GetName}}Server, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error)
-{{end}}`, "\n", "", -1)))
-
- _ = template.Must(localHandlerTemplate.New("local-client-rpc-request-func").Parse(`
-{{$AllowPatchFeature := .AllowPatchFeature}}
-{{template "local-request-func-signature" .}} {
- var protoReq {{.Method.RequestType.GoType .Method.Service.File.GoPkg.Path}}
- var metadata runtime.ServerMetadata
-{{if .Body}}
- newReader, berr := utilities.IOReaderFactory(req.Body)
- if berr != nil {
- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
- }
- if err := marshaler.NewDecoder(newReader()).Decode(&{{.Body.AssignableExpr "protoReq"}}); err != nil && err != io.EOF {
- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
- }
- {{- if and $AllowPatchFeature (eq (.HTTPMethod) "PATCH") (.FieldMaskField) (not (eq "*" .GetBodyFieldPath)) }}
- if protoReq.{{.FieldMaskField}} == nil || len(protoReq.{{.FieldMaskField}}.GetPaths()) == 0 {
- _, md := descriptor.ForMessage(protoReq.{{.GetBodyFieldStructName}})
- if fieldMask, err := runtime.FieldMaskFromRequestBody(newReader(), md); err != nil {
- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
- } else {
- protoReq.{{.FieldMaskField}} = fieldMask
- }
- }
- {{end}}
-{{end}}
-{{if .PathParams}}
- var (
- val string
-{{- if .HasEnumPathParam}}
- e int32
-{{- end}}
-{{- if .HasRepeatedEnumPathParam}}
- es []int32
-{{- end}}
- ok bool
- err error
- _ = err
- )
- {{$binding := .}}
- {{range $param := .PathParams}}
- {{$enum := $binding.LookupEnum $param}}
- val, ok = pathParams[{{$param | printf "%q"}}]
- if !ok {
- return nil, metadata, status.Errorf(codes.InvalidArgument, "missing parameter %s", {{$param | printf "%q"}})
- }
-{{if $param.IsNestedProto3}}
- err = runtime.PopulateFieldFromPath(&protoReq, {{$param | printf "%q"}}, val)
- {{if $enum}}
- e{{if $param.IsRepeated}}s{{end}}, err = {{$param.ConvertFuncExpr}}(val{{if $param.IsRepeated}}, {{$binding.Registry.GetRepeatedPathParamSeparator | printf "%c" | printf "%q"}}{{end}}, {{$enum.GoType $param.Target.Message.File.GoPkg.Path}}_value)
- {{end}}
-{{else if $enum}}
- e{{if $param.IsRepeated}}s{{end}}, err = {{$param.ConvertFuncExpr}}(val{{if $param.IsRepeated}}, {{$binding.Registry.GetRepeatedPathParamSeparator | printf "%c" | printf "%q"}}{{end}}, {{$enum.GoType $param.Target.Message.File.GoPkg.Path}}_value)
-{{else}}
- {{$param.AssignableExpr "protoReq"}}, err = {{$param.ConvertFuncExpr}}(val{{if $param.IsRepeated}}, {{$binding.Registry.GetRepeatedPathParamSeparator | printf "%c" | printf "%q"}}{{end}})
-{{end}}
- if err != nil {
- return nil, metadata, status.Errorf(codes.InvalidArgument, "type mismatch, parameter: %s, error: %v", {{$param | printf "%q"}}, err)
- }
-{{if and $enum $param.IsRepeated}}
- s := make([]{{$enum.GoType $param.Target.Message.File.GoPkg.Path}}, len(es))
- for i, v := range es {
- s[i] = {{$enum.GoType $param.Target.Message.File.GoPkg.Path}}(v)
- }
- {{$param.AssignableExpr "protoReq"}} = s
-{{else if $enum}}
- {{$param.AssignableExpr "protoReq"}} = {{$enum.GoType $param.Target.Message.File.GoPkg.Path}}(e)
-{{end}}
- {{end}}
-{{end}}
-{{if .HasQueryParam}}
- if err := runtime.PopulateQueryParameters(&protoReq, req.URL.Query(), filter_{{.Method.Service.GetName}}_{{.Method.GetName}}_{{.Index}}); err != nil {
- return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
- }
-{{end}}
-{{if .Method.GetServerStreaming}}
- // TODO
-{{else}}
- msg, err := server.{{.Method.GetName}}(ctx, &protoReq)
- return msg, metadata, err
-{{end}}
-}`))
-
- localTrailerTemplate = template.Must(template.New("local-trailer").Parse(`
-{{$UseRequestContext := .UseRequestContext}}
-{{range $svc := .Services}}
-// Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}Server registers the http handlers for service {{$svc.GetName}} to "mux".
-// UnaryRPC :call {{$svc.GetName}}Server directly.
-// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
-func Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}Server(ctx context.Context, mux *runtime.ServeMux, server {{$svc.GetName}}Server) error {
- {{range $m := $svc.Methods}}
- {{range $b := $m.Bindings}}
- {{if or $m.GetClientStreaming $m.GetServerStreaming}}
- mux.Handle({{$b.HTTPMethod | printf "%q"}}, pattern_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
- err := status.Error(codes.Unimplemented, "streaming calls are not yet supported in the in-process transport")
- _, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
- runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
- return
- })
- {{else}}
- mux.Handle({{$b.HTTPMethod | printf "%q"}}, pattern_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
- {{- if $UseRequestContext }}
- ctx, cancel := context.WithCancel(req.Context())
- {{- else -}}
- ctx, cancel := context.WithCancel(ctx)
- {{- end }}
- defer cancel()
- inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
- rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)
- if err != nil {
- runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
- return
- }
- resp, md, err := local_request_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(rctx, inboundMarshaler, server, req, pathParams)
- ctx = runtime.NewServerMetadataContext(ctx, md)
- if err != nil {
- runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
- return
- }
-
- {{ if $b.ResponseBody }}
- forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, response_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}{resp}, mux.GetForwardResponseOptions()...)
- {{ else }}
- forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
- {{end}}
- })
- {{end}}
- {{end}}
- {{end}}
- return nil
-}
-{{end}}`))
-
- trailerTemplate = template.Must(template.New("trailer").Parse(`
-{{$UseRequestContext := .UseRequestContext}}
-{{range $svc := .Services}}
-// Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}FromEndpoint is same as Register{{$svc.GetName}}{{$.RegisterFuncSuffix}} but
-// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
-func Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}FromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
- conn, err := grpc.Dial(endpoint, opts...)
- if err != nil {
- return err
- }
- defer func() {
- if err != nil {
- if cerr := conn.Close(); cerr != nil {
- grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
- }
- return
- }
- go func() {
- <-ctx.Done()
- if cerr := conn.Close(); cerr != nil {
- grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
- }
- }()
- }()
-
- return Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}(ctx, mux, conn)
-}
-
-// Register{{$svc.GetName}}{{$.RegisterFuncSuffix}} registers the http handlers for service {{$svc.GetName}} to "mux".
-// The handlers forward requests to the grpc endpoint over "conn".
-func Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
- return Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}Client(ctx, mux, New{{$svc.GetName}}Client(conn))
-}
-
-// Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}Client registers the http handlers for service {{$svc.GetName}}
-// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "{{$svc.GetName}}Client".
-// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "{{$svc.GetName}}Client"
-// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
-// "{{$svc.GetName}}Client" to call the correct interceptors.
-func Register{{$svc.GetName}}{{$.RegisterFuncSuffix}}Client(ctx context.Context, mux *runtime.ServeMux, client {{$svc.GetName}}Client) error {
- {{range $m := $svc.Methods}}
- {{range $b := $m.Bindings}}
- mux.Handle({{$b.HTTPMethod | printf "%q"}}, pattern_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
- {{- if $UseRequestContext }}
- ctx, cancel := context.WithCancel(req.Context())
- {{- else -}}
- ctx, cancel := context.WithCancel(ctx)
- {{- end }}
- defer cancel()
- inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
- rctx, err := runtime.AnnotateContext(ctx, mux, req)
- if err != nil {
- runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
- return
- }
- resp, md, err := request_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(rctx, inboundMarshaler, client, req, pathParams)
- ctx = runtime.NewServerMetadataContext(ctx, md)
- if err != nil {
- runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
- return
- }
- {{if $m.GetServerStreaming}}
- forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, func() (proto.Message, error) { return resp.Recv() }, mux.GetForwardResponseOptions()...)
- {{else}}
- {{ if $b.ResponseBody }}
- forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, response_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}{resp}, mux.GetForwardResponseOptions()...)
- {{ else }}
- forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
- {{end}}
- {{end}}
- })
- {{end}}
- {{end}}
- return nil
-}
-
-{{range $m := $svc.Methods}}
-{{range $b := $m.Bindings}}
-{{if $b.ResponseBody}}
-type response_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}} struct {
- proto.Message
-}
-
-func (m response_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}}) XXX_ResponseBody() interface{} {
- response := m.Message.(*{{$m.ResponseType.GoType $m.Service.File.GoPkg.Path}})
- return {{$b.ResponseBody.AssignableExpr "response"}}
-}
-{{end}}
-{{end}}
-{{end}}
-
-var (
- {{range $m := $svc.Methods}}
- {{range $b := $m.Bindings}}
- pattern_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}} = runtime.MustPattern(runtime.NewPattern({{$b.PathTmpl.Version}}, {{$b.PathTmpl.OpCodes | printf "%#v"}}, {{$b.PathTmpl.Pool | printf "%#v"}}, {{$b.PathTmpl.Verb | printf "%q"}}, runtime.AssumeColonVerbOpt({{$.AssumeColonVerb}})))
- {{end}}
- {{end}}
-)
-
-var (
- {{range $m := $svc.Methods}}
- {{range $b := $m.Bindings}}
- forward_{{$svc.GetName}}_{{$m.GetName}}_{{$b.Index}} = {{if $m.GetServerStreaming}}runtime.ForwardResponseStream{{else}}runtime.ForwardResponseMessage{{end}}
- {{end}}
- {{end}}
-)
-{{end}}`))
-)
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/BUILD.bazel
deleted file mode 100644
index 89f94a1..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/BUILD.bazel
+++ /dev/null
@@ -1,32 +0,0 @@
-load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
-
-package(default_visibility = ["//:generators"])
-
-go_library(
- name = "go_default_library",
- srcs = [
- "compile.go",
- "parse.go",
- "types.go",
- ],
- importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule",
- deps = [
- "//utilities:go_default_library",
- "@com_github_golang_glog//:go_default_library",
- ],
-)
-
-go_test(
- name = "go_default_test",
- size = "small",
- srcs = [
- "compile_test.go",
- "parse_test.go",
- "types_test.go",
- ],
- embed = [":go_default_library"],
- deps = [
- "//utilities:go_default_library",
- "@com_github_golang_glog//:go_default_library",
- ],
-)
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/compile.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/compile.go
deleted file mode 100644
index 437039a..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/compile.go
+++ /dev/null
@@ -1,117 +0,0 @@
-package httprule
-
-import (
- "github.com/grpc-ecosystem/grpc-gateway/utilities"
-)
-
-const (
- opcodeVersion = 1
-)
-
-// Template is a compiled representation of path templates.
-type Template struct {
- // Version is the version number of the format.
- Version int
- // OpCodes is a sequence of operations.
- OpCodes []int
- // Pool is a constant pool
- Pool []string
- // Verb is a VERB part in the template.
- Verb string
- // Fields is a list of field paths bound in this template.
- Fields []string
- // Original template (example: /v1/a_bit_of_everything)
- Template string
-}
-
-// Compiler compiles utilities representation of path templates into marshallable operations.
-// They can be unmarshalled by runtime.NewPattern.
-type Compiler interface {
- Compile() Template
-}
-
-type op struct {
- // code is the opcode of the operation
- code utilities.OpCode
-
- // str is a string operand of the code.
- // num is ignored if str is not empty.
- str string
-
- // num is a numeric operand of the code.
- num int
-}
-
-func (w wildcard) compile() []op {
- return []op{
- {code: utilities.OpPush},
- }
-}
-
-func (w deepWildcard) compile() []op {
- return []op{
- {code: utilities.OpPushM},
- }
-}
-
-func (l literal) compile() []op {
- return []op{
- {
- code: utilities.OpLitPush,
- str: string(l),
- },
- }
-}
-
-func (v variable) compile() []op {
- var ops []op
- for _, s := range v.segments {
- ops = append(ops, s.compile()...)
- }
- ops = append(ops, op{
- code: utilities.OpConcatN,
- num: len(v.segments),
- }, op{
- code: utilities.OpCapture,
- str: v.path,
- })
-
- return ops
-}
-
-func (t template) Compile() Template {
- var rawOps []op
- for _, s := range t.segments {
- rawOps = append(rawOps, s.compile()...)
- }
-
- var (
- ops []int
- pool []string
- fields []string
- )
- consts := make(map[string]int)
- for _, op := range rawOps {
- ops = append(ops, int(op.code))
- if op.str == "" {
- ops = append(ops, op.num)
- } else {
- if _, ok := consts[op.str]; !ok {
- consts[op.str] = len(pool)
- pool = append(pool, op.str)
- }
- ops = append(ops, consts[op.str])
- }
- if op.code == utilities.OpCapture {
- fields = append(fields, op.str)
- }
- }
- return Template{
- Version: opcodeVersion,
- OpCodes: ops,
- Pool: pool,
- Verb: t.verb,
- Fields: fields,
- Template: t.template,
- }
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/fuzz.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/fuzz.go
deleted file mode 100644
index 138f7c1..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/fuzz.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// +build gofuzz
-
-package httprule
-
-func Fuzz(data []byte) int {
- _, err := Parse(string(data))
- if err != nil {
- return 0
- }
- return 0
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/parse.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/parse.go
deleted file mode 100644
index f933cd8..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/parse.go
+++ /dev/null
@@ -1,351 +0,0 @@
-package httprule
-
-import (
- "fmt"
- "strings"
-
- "github.com/golang/glog"
-)
-
-// InvalidTemplateError indicates that the path template is not valid.
-type InvalidTemplateError struct {
- tmpl string
- msg string
-}
-
-func (e InvalidTemplateError) Error() string {
- return fmt.Sprintf("%s: %s", e.msg, e.tmpl)
-}
-
-// Parse parses the string representation of path template
-func Parse(tmpl string) (Compiler, error) {
- if !strings.HasPrefix(tmpl, "/") {
- return template{}, InvalidTemplateError{tmpl: tmpl, msg: "no leading /"}
- }
- tokens, verb := tokenize(tmpl[1:])
-
- p := parser{tokens: tokens}
- segs, err := p.topLevelSegments()
- if err != nil {
- return template{}, InvalidTemplateError{tmpl: tmpl, msg: err.Error()}
- }
-
- return template{
- segments: segs,
- verb: verb,
- template: tmpl,
- }, nil
-}
-
-func tokenize(path string) (tokens []string, verb string) {
- if path == "" {
- return []string{eof}, ""
- }
-
- const (
- init = iota
- field
- nested
- )
- var (
- st = init
- )
- for path != "" {
- var idx int
- switch st {
- case init:
- idx = strings.IndexAny(path, "/{")
- case field:
- idx = strings.IndexAny(path, ".=}")
- case nested:
- idx = strings.IndexAny(path, "/}")
- }
- if idx < 0 {
- tokens = append(tokens, path)
- break
- }
- switch r := path[idx]; r {
- case '/', '.':
- case '{':
- st = field
- case '=':
- st = nested
- case '}':
- st = init
- }
- if idx == 0 {
- tokens = append(tokens, path[idx:idx+1])
- } else {
- tokens = append(tokens, path[:idx], path[idx:idx+1])
- }
- path = path[idx+1:]
- }
-
- l := len(tokens)
- t := tokens[l-1]
- if idx := strings.LastIndex(t, ":"); idx == 0 {
- tokens, verb = tokens[:l-1], t[1:]
- } else if idx > 0 {
- tokens[l-1], verb = t[:idx], t[idx+1:]
- }
- tokens = append(tokens, eof)
- return tokens, verb
-}
-
-// parser is a parser of the template syntax defined in github.com/googleapis/googleapis/google/api/http.proto.
-type parser struct {
- tokens []string
- accepted []string
-}
-
-// topLevelSegments is the target of this parser.
-func (p *parser) topLevelSegments() ([]segment, error) {
- glog.V(1).Infof("Parsing %q", p.tokens)
- segs, err := p.segments()
- if err != nil {
- return nil, err
- }
- glog.V(2).Infof("accept segments: %q; %q", p.accepted, p.tokens)
- if _, err := p.accept(typeEOF); err != nil {
- return nil, fmt.Errorf("unexpected token %q after segments %q", p.tokens[0], strings.Join(p.accepted, ""))
- }
- glog.V(2).Infof("accept eof: %q; %q", p.accepted, p.tokens)
- return segs, nil
-}
-
-func (p *parser) segments() ([]segment, error) {
- s, err := p.segment()
- if err != nil {
- return nil, err
- }
- glog.V(2).Infof("accept segment: %q; %q", p.accepted, p.tokens)
-
- segs := []segment{s}
- for {
- if _, err := p.accept("/"); err != nil {
- return segs, nil
- }
- s, err := p.segment()
- if err != nil {
- return segs, err
- }
- segs = append(segs, s)
- glog.V(2).Infof("accept segment: %q; %q", p.accepted, p.tokens)
- }
-}
-
-func (p *parser) segment() (segment, error) {
- if _, err := p.accept("*"); err == nil {
- return wildcard{}, nil
- }
- if _, err := p.accept("**"); err == nil {
- return deepWildcard{}, nil
- }
- if l, err := p.literal(); err == nil {
- return l, nil
- }
-
- v, err := p.variable()
- if err != nil {
- return nil, fmt.Errorf("segment neither wildcards, literal or variable: %v", err)
- }
- return v, err
-}
-
-func (p *parser) literal() (segment, error) {
- lit, err := p.accept(typeLiteral)
- if err != nil {
- return nil, err
- }
- return literal(lit), nil
-}
-
-func (p *parser) variable() (segment, error) {
- if _, err := p.accept("{"); err != nil {
- return nil, err
- }
-
- path, err := p.fieldPath()
- if err != nil {
- return nil, err
- }
-
- var segs []segment
- if _, err := p.accept("="); err == nil {
- segs, err = p.segments()
- if err != nil {
- return nil, fmt.Errorf("invalid segment in variable %q: %v", path, err)
- }
- } else {
- segs = []segment{wildcard{}}
- }
-
- if _, err := p.accept("}"); err != nil {
- return nil, fmt.Errorf("unterminated variable segment: %s", path)
- }
- return variable{
- path: path,
- segments: segs,
- }, nil
-}
-
-func (p *parser) fieldPath() (string, error) {
- c, err := p.accept(typeIdent)
- if err != nil {
- return "", err
- }
- components := []string{c}
- for {
- if _, err = p.accept("."); err != nil {
- return strings.Join(components, "."), nil
- }
- c, err := p.accept(typeIdent)
- if err != nil {
- return "", fmt.Errorf("invalid field path component: %v", err)
- }
- components = append(components, c)
- }
-}
-
-// A termType is a type of terminal symbols.
-type termType string
-
-// These constants define some of valid values of termType.
-// They improve readability of parse functions.
-//
-// You can also use "/", "*", "**", "." or "=" as valid values.
-const (
- typeIdent = termType("ident")
- typeLiteral = termType("literal")
- typeEOF = termType("$")
-)
-
-const (
- // eof is the terminal symbol which always appears at the end of token sequence.
- eof = "\u0000"
-)
-
-// accept tries to accept a token in "p".
-// This function consumes a token and returns it if it matches to the specified "term".
-// If it doesn't match, the function does not consume any tokens and return an error.
-func (p *parser) accept(term termType) (string, error) {
- t := p.tokens[0]
- switch term {
- case "/", "*", "**", ".", "=", "{", "}":
- if t != string(term) && t != "/" {
- return "", fmt.Errorf("expected %q but got %q", term, t)
- }
- case typeEOF:
- if t != eof {
- return "", fmt.Errorf("expected EOF but got %q", t)
- }
- case typeIdent:
- if err := expectIdent(t); err != nil {
- return "", err
- }
- case typeLiteral:
- if err := expectPChars(t); err != nil {
- return "", err
- }
- default:
- return "", fmt.Errorf("unknown termType %q", term)
- }
- p.tokens = p.tokens[1:]
- p.accepted = append(p.accepted, t)
- return t, nil
-}
-
-// expectPChars determines if "t" consists of only pchars defined in RFC3986.
-//
-// https://www.ietf.org/rfc/rfc3986.txt, P.49
-// pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
-// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
-// sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
-// / "*" / "+" / "," / ";" / "="
-// pct-encoded = "%" HEXDIG HEXDIG
-func expectPChars(t string) error {
- const (
- init = iota
- pct1
- pct2
- )
- st := init
- for _, r := range t {
- if st != init {
- if !isHexDigit(r) {
- return fmt.Errorf("invalid hexdigit: %c(%U)", r, r)
- }
- switch st {
- case pct1:
- st = pct2
- case pct2:
- st = init
- }
- continue
- }
-
- // unreserved
- switch {
- case 'A' <= r && r <= 'Z':
- continue
- case 'a' <= r && r <= 'z':
- continue
- case '0' <= r && r <= '9':
- continue
- }
- switch r {
- case '-', '.', '_', '~':
- // unreserved
- case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=':
- // sub-delims
- case ':', '@':
- // rest of pchar
- case '%':
- // pct-encoded
- st = pct1
- default:
- return fmt.Errorf("invalid character in path segment: %q(%U)", r, r)
- }
- }
- if st != init {
- return fmt.Errorf("invalid percent-encoding in %q", t)
- }
- return nil
-}
-
-// expectIdent determines if "ident" is a valid identifier in .proto schema ([[:alpha:]_][[:alphanum:]_]*).
-func expectIdent(ident string) error {
- if ident == "" {
- return fmt.Errorf("empty identifier")
- }
- for pos, r := range ident {
- switch {
- case '0' <= r && r <= '9':
- if pos == 0 {
- return fmt.Errorf("identifier starting with digit: %s", ident)
- }
- continue
- case 'A' <= r && r <= 'Z':
- continue
- case 'a' <= r && r <= 'z':
- continue
- case r == '_':
- continue
- default:
- return fmt.Errorf("invalid character %q(%U) in identifier: %s", r, r, ident)
- }
- }
- return nil
-}
-
-func isHexDigit(r rune) bool {
- switch {
- case '0' <= r && r <= '9':
- return true
- case 'A' <= r && r <= 'F':
- return true
- case 'a' <= r && r <= 'f':
- return true
- }
- return false
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/types.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/types.go
deleted file mode 100644
index 5a814a0..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule/types.go
+++ /dev/null
@@ -1,60 +0,0 @@
-package httprule
-
-import (
- "fmt"
- "strings"
-)
-
-type template struct {
- segments []segment
- verb string
- template string
-}
-
-type segment interface {
- fmt.Stringer
- compile() (ops []op)
-}
-
-type wildcard struct{}
-
-type deepWildcard struct{}
-
-type literal string
-
-type variable struct {
- path string
- segments []segment
-}
-
-func (wildcard) String() string {
- return "*"
-}
-
-func (deepWildcard) String() string {
- return "**"
-}
-
-func (l literal) String() string {
- return string(l)
-}
-
-func (v variable) String() string {
- var segs []string
- for _, s := range v.segments {
- segs = append(segs, s.String())
- }
- return fmt.Sprintf("{%s=%s}", v.path, strings.Join(segs, "/"))
-}
-
-func (t template) String() string {
- var segs []string
- for _, s := range t.segments {
- segs = append(segs, s.String())
- }
- str := strings.Join(segs, "/")
- if t.verb != "" {
- str = fmt.Sprintf("%s:%s", str, t.verb)
- }
- return "/" + str
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/main.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/main.go
deleted file mode 100644
index 291ba7d..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/main.go
+++ /dev/null
@@ -1,141 +0,0 @@
-// Command protoc-gen-grpc-gateway is a plugin for Google protocol buffer
-// compiler to generate a reverse-proxy, which converts incoming RESTful
-// HTTP/1 requests gRPC invocation.
-// You rarely need to run this program directly. Instead, put this program
-// into your $PATH with a name "protoc-gen-grpc-gateway" and run
-// protoc --grpc-gateway_out=output_directory path/to/input.proto
-//
-// See README.md for more details.
-package main
-
-import (
- "flag"
- "fmt"
- "os"
- "strings"
-
- "github.com/golang/glog"
- "github.com/golang/protobuf/proto"
- plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
- "github.com/grpc-ecosystem/grpc-gateway/codegenerator"
- "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
- "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway"
-)
-
-var (
- importPrefix = flag.String("import_prefix", "", "prefix to be added to go package paths for imported proto files")
- importPath = flag.String("import_path", "", "used as the package if no input files declare go_package. If it contains slashes, everything up to the rightmost slash is ignored.")
- registerFuncSuffix = flag.String("register_func_suffix", "Handler", "used to construct names of generated Register*<Suffix> methods.")
- useRequestContext = flag.Bool("request_context", true, "determine whether to use http.Request's context or not")
- allowDeleteBody = flag.Bool("allow_delete_body", false, "unless set, HTTP DELETE methods may not have a body")
- grpcAPIConfiguration = flag.String("grpc_api_configuration", "", "path to gRPC API Configuration in YAML format")
- pathType = flag.String("paths", "", "specifies how the paths of generated files are structured")
- allowRepeatedFieldsInBody = flag.Bool("allow_repeated_fields_in_body", false, "allows to use repeated field in `body` and `response_body` field of `google.api.http` annotation option")
- repeatedPathParamSeparator = flag.String("repeated_path_param_separator", "csv", "configures how repeated fields should be split. Allowed values are `csv`, `pipes`, `ssv` and `tsv`.")
- allowPatchFeature = flag.Bool("allow_patch_feature", true, "determines whether to use PATCH feature involving update masks (using google.protobuf.FieldMask).")
- allowColonFinalSegments = flag.Bool("allow_colon_final_segments", false, "determines whether colons are permitted in the final segment of a path")
- versionFlag = flag.Bool("version", false, "print the current verison")
-)
-
-// Variables set by goreleaser at build time
-var (
- version = "dev"
- commit = "unknown"
- date = "unknown"
-)
-
-func main() {
- flag.Parse()
- defer glog.Flush()
-
- if *versionFlag {
- fmt.Printf("Version %v, commit %v, built at %v\n", version, commit, date)
- os.Exit(0)
- }
-
- reg := descriptor.NewRegistry()
-
- glog.V(1).Info("Parsing code generator request")
- req, err := codegenerator.ParseRequest(os.Stdin)
- if err != nil {
- glog.Fatal(err)
- }
- glog.V(1).Info("Parsed code generator request")
- if req.Parameter != nil {
- for _, p := range strings.Split(req.GetParameter(), ",") {
- spec := strings.SplitN(p, "=", 2)
- if len(spec) == 1 {
- if err := flag.CommandLine.Set(spec[0], ""); err != nil {
- glog.Fatalf("Cannot set flag %s", p)
- }
- continue
- }
- name, value := spec[0], spec[1]
- if strings.HasPrefix(name, "M") {
- reg.AddPkgMap(name[1:], value)
- continue
- }
- if err := flag.CommandLine.Set(name, value); err != nil {
- glog.Fatalf("Cannot set flag %s", p)
- }
- }
- }
-
- g := gengateway.New(reg, *useRequestContext, *registerFuncSuffix, *pathType, *allowPatchFeature)
-
- if *grpcAPIConfiguration != "" {
- if err := reg.LoadGrpcAPIServiceFromYAML(*grpcAPIConfiguration); err != nil {
- emitError(err)
- return
- }
- }
-
- reg.SetPrefix(*importPrefix)
- reg.SetImportPath(*importPath)
- reg.SetAllowDeleteBody(*allowDeleteBody)
- reg.SetAllowRepeatedFieldsInBody(*allowRepeatedFieldsInBody)
- reg.SetAllowColonFinalSegments(*allowColonFinalSegments)
- if err := reg.SetRepeatedPathParamSeparator(*repeatedPathParamSeparator); err != nil {
- emitError(err)
- return
- }
- if err := reg.Load(req); err != nil {
- emitError(err)
- return
- }
-
- var targets []*descriptor.File
- for _, target := range req.FileToGenerate {
- f, err := reg.LookupFile(target)
- if err != nil {
- glog.Fatal(err)
- }
- targets = append(targets, f)
- }
-
- out, err := g.Generate(targets)
- glog.V(1).Info("Processed code generator request")
- if err != nil {
- emitError(err)
- return
- }
- emitFiles(out)
-}
-
-func emitFiles(out []*plugin.CodeGeneratorResponse_File) {
- emitResp(&plugin.CodeGeneratorResponse{File: out})
-}
-
-func emitError(err error) {
- emitResp(&plugin.CodeGeneratorResponse{Error: proto.String(err.Error())})
-}
-
-func emitResp(resp *plugin.CodeGeneratorResponse) {
- buf, err := proto.Marshal(resp)
- if err != nil {
- glog.Fatal(err)
- }
- if _, err := os.Stdout.Write(buf); err != nil {
- glog.Fatal(err)
- }
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/BUILD.bazel
deleted file mode 100644
index d5a1d05..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/BUILD.bazel
+++ /dev/null
@@ -1,30 +0,0 @@
-load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library", "go_test")
-
-package(default_visibility = ["//visibility:private"])
-
-go_library(
- name = "go_default_library",
- srcs = ["main.go"],
- importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger",
- deps = [
- "//codegenerator:go_default_library",
- "//protoc-gen-grpc-gateway/descriptor:go_default_library",
- "//protoc-gen-swagger/genswagger:go_default_library",
- "@com_github_golang_glog//:go_default_library",
- "@com_github_golang_protobuf//proto:go_default_library",
- "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto",
- ],
-)
-
-go_binary(
- name = "protoc-gen-swagger",
- embed = [":go_default_library"],
- visibility = ["//visibility:public"],
-)
-
-go_test(
- name = "go_default_test",
- size = "small",
- srcs = ["main_test.go"],
- embed = [":go_default_library"],
-)
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/defs.bzl b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/defs.bzl
deleted file mode 100644
index 2cb1f22..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/defs.bzl
+++ /dev/null
@@ -1,195 +0,0 @@
-"""Generated an open-api spec for a grpc api spec.
-
-Reads the the api spec in protobuf format and generate an open-api spec.
-Optionally applies settings from the grpc-service configuration.
-"""
-
-load("@rules_proto//proto:defs.bzl", "ProtoInfo")
-
-# TODO(yannic): Replace with |proto_common.direct_source_infos| when
-# https://github.com/bazelbuild/rules_proto/pull/22 lands.
-def _direct_source_infos(proto_info, provided_sources = []):
- """Returns sequence of `ProtoFileInfo` for `proto_info`'s direct sources.
-
- Files that are both in `proto_info`'s direct sources and in
- `provided_sources` are skipped. This is useful, e.g., for well-known
- protos that are already provided by the Protobuf runtime.
-
- Args:
- proto_info: An instance of `ProtoInfo`.
- provided_sources: Optional. A sequence of files to ignore.
- Usually, these files are already provided by the
- Protocol Buffer runtime (e.g. Well-Known protos).
-
- Returns: A sequence of `ProtoFileInfo` containing information about
- `proto_info`'s direct sources.
- """
-
- source_root = proto_info.proto_source_root
- if "." == source_root:
- return [struct(file = src, import_path = src.path) for src in proto_info.direct_sources]
-
- offset = len(source_root) + 1 # + '/'.
-
- infos = []
- for src in proto_info.direct_sources:
- # TODO(yannic): Remove this hack when we drop support for Bazel < 1.0.
- local_offset = offset
- if src.root.path and not source_root.startswith(src.root.path):
- # Before Bazel 1.0, `proto_source_root` wasn't guaranteed to be a
- # prefix of `src.path`. This could happend, e.g., if `file` was
- # generated (https://github.com/bazelbuild/bazel/issues/9215).
- local_offset += len(src.root.path) + 1 # + '/'.
- infos.append(struct(file = src, import_path = src.path[local_offset:]))
-
- return infos
-
-def _run_proto_gen_swagger(
- actions,
- proto_info,
- target_name,
- transitive_proto_srcs,
- protoc,
- protoc_gen_swagger,
- grpc_api_configuration,
- single_output,
- json_names_for_fields):
- args = actions.args()
-
- args.add("--plugin", "protoc-gen-swagger=%s" % protoc_gen_swagger.path)
-
- args.add("--swagger_opt", "logtostderr=true")
- args.add("--swagger_opt", "allow_repeated_fields_in_body=true")
-
- extra_inputs = []
- if grpc_api_configuration:
- extra_inputs.append(grpc_api_configuration)
- args.add("--swagger_opt", "grpc_api_configuration=%s" % grpc_api_configuration.path)
-
- if json_names_for_fields:
- args.add("--swagger_opt", "json_names_for_fields=true")
-
- proto_file_infos = _direct_source_infos(proto_info)
-
- # TODO(yannic): Use |proto_info.transitive_descriptor_sets| when
- # https://github.com/bazelbuild/bazel/issues/9337 is fixed.
- args.add_all(proto_info.transitive_proto_path, format_each = "--proto_path=%s")
-
- if single_output:
- args.add("--swagger_opt", "allow_merge=true")
- args.add("--swagger_opt", "merge_file_name=%s" % target_name)
-
- swagger_file = actions.declare_file("%s.swagger.json" % target_name)
- args.add("--swagger_out", swagger_file.dirname)
-
- args.add_all([f.import_path for f in proto_file_infos])
-
- actions.run(
- executable = protoc,
- tools = [protoc_gen_swagger],
- inputs = depset(
- direct = extra_inputs,
- transitive = [transitive_proto_srcs],
- ),
- outputs = [swagger_file],
- arguments = [args],
- )
-
- return [swagger_file]
-
- # TODO(yannic): We may be able to generate all files in a single action,
- # but that will change at least the semantics of `use_go_template.proto`.
- swagger_files = []
- for proto_file_info in proto_file_infos:
- # TODO(yannic): This probably doesn't work as expected: we only add this
- # option after we have seen it, so `.proto` sources that happen to be
- # in the list of `.proto` files before `use_go_template.proto` will be
- # compiled without this option, and all sources that get compiled after
- # `use_go_template.proto` will have this option on.
- if proto_file_info.file.basename == "use_go_template.proto":
- args.add("--swagger_opt", "use_go_templates=true")
-
- file_name = "%s.swagger.json" % proto_file_info.import_path[:-len(".proto")]
- swagger_file = actions.declare_file(
- "_virtual_imports/%s/%s" % (target_name, file_name),
- )
-
- file_args = actions.args()
-
- offset = len(file_name) + 1 # + '/'.
- file_args.add("--swagger_out", swagger_file.path[:-offset])
-
- file_args.add(proto_file_info.import_path)
-
- actions.run(
- executable = protoc,
- tools = [protoc_gen_swagger],
- inputs = depset(
- direct = extra_inputs,
- transitive = [transitive_proto_srcs],
- ),
- outputs = [swagger_file],
- arguments = [args, file_args],
- )
- swagger_files.append(swagger_file)
-
- return swagger_files
-
-def _proto_gen_swagger_impl(ctx):
- proto = ctx.attr.proto[ProtoInfo]
- return [
- DefaultInfo(
- files = depset(
- _run_proto_gen_swagger(
- actions = ctx.actions,
- proto_info = proto,
- target_name = ctx.attr.name,
- transitive_proto_srcs = depset(
- direct = ctx.files._well_known_protos,
- transitive = [proto.transitive_sources],
- ),
- protoc = ctx.executable._protoc,
- protoc_gen_swagger = ctx.executable._protoc_gen_swagger,
- grpc_api_configuration = ctx.file.grpc_api_configuration,
- single_output = ctx.attr.single_output,
- json_names_for_fields = ctx.attr.json_names_for_fields,
- ),
- ),
- ),
- ]
-
-protoc_gen_swagger = rule(
- attrs = {
- "proto": attr.label(
- mandatory = True,
- providers = [ProtoInfo],
- ),
- "grpc_api_configuration": attr.label(
- allow_single_file = True,
- mandatory = False,
- ),
- "single_output": attr.bool(
- default = False,
- mandatory = False,
- ),
- "json_names_for_fields": attr.bool(
- default = False,
- mandatory = False,
- ),
- "_protoc": attr.label(
- default = "@com_google_protobuf//:protoc",
- executable = True,
- cfg = "host",
- ),
- "_well_known_protos": attr.label(
- default = "@com_google_protobuf//:well_known_protos",
- allow_files = True,
- ),
- "_protoc_gen_swagger": attr.label(
- default = Label("//protoc-gen-swagger:protoc-gen-swagger"),
- executable = True,
- cfg = "host",
- ),
- },
- implementation = _proto_gen_swagger_impl,
-)
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/BUILD.bazel b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/BUILD.bazel
deleted file mode 100644
index c89eb04..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/BUILD.bazel
+++ /dev/null
@@ -1,48 +0,0 @@
-load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
-
-package(default_visibility = ["//protoc-gen-swagger:__subpackages__"])
-
-go_library(
- name = "go_default_library",
- srcs = [
- "doc.go",
- "generator.go",
- "helpers.go",
- "helpers_go111_old.go",
- "template.go",
- "types.go",
- ],
- importpath = "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger",
- deps = [
- "//internal:go_default_library",
- "//protoc-gen-grpc-gateway/descriptor:go_default_library",
- "//protoc-gen-grpc-gateway/generator:go_default_library",
- "//protoc-gen-swagger/options:go_default_library",
- "@com_github_golang_glog//:go_default_library",
- "@com_github_golang_protobuf//descriptor:go_default_library_gen",
- "@com_github_golang_protobuf//jsonpb:go_default_library_gen",
- "@com_github_golang_protobuf//proto:go_default_library",
- "@com_github_golang_protobuf//protoc-gen-go/generator:go_default_library_gen",
- "@io_bazel_rules_go//proto/wkt:any_go_proto",
- "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto",
- "@io_bazel_rules_go//proto/wkt:descriptor_go_proto",
- "@io_bazel_rules_go//proto/wkt:struct_go_proto",
- ],
-)
-
-go_test(
- name = "go_default_test",
- size = "small",
- srcs = ["template_test.go"],
- embed = [":go_default_library"],
- deps = [
- "//protoc-gen-grpc-gateway/descriptor:go_default_library",
- "//protoc-gen-grpc-gateway/httprule:go_default_library",
- "//protoc-gen-swagger/options:go_default_library",
- "@com_github_golang_protobuf//proto:go_default_library",
- "@io_bazel_rules_go//proto/wkt:any_go_proto",
- "@io_bazel_rules_go//proto/wkt:compiler_plugin_go_proto",
- "@io_bazel_rules_go//proto/wkt:descriptor_go_proto",
- "@io_bazel_rules_go//proto/wkt:struct_go_proto",
- ],
-)
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/doc.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/doc.go
deleted file mode 100644
index 4d28716..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/doc.go
+++ /dev/null
@@ -1,2 +0,0 @@
-// Package genswagger provides a code generator for swagger.
-package genswagger
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/generator.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/generator.go
deleted file mode 100644
index ecf1135..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/generator.go
+++ /dev/null
@@ -1,240 +0,0 @@
-package genswagger
-
-import (
- "bytes"
- "encoding/json"
- "errors"
- "fmt"
- "path/filepath"
- "reflect"
- "strings"
-
- "github.com/golang/glog"
- pbdescriptor "github.com/golang/protobuf/descriptor"
- "github.com/golang/protobuf/proto"
- protocdescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
- plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
- "github.com/golang/protobuf/ptypes/any"
- "github.com/grpc-ecosystem/grpc-gateway/internal"
- "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
- gen "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator"
- swagger_options "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options"
-)
-
-var (
- errNoTargetService = errors.New("no target service defined in the file")
-)
-
-type generator struct {
- reg *descriptor.Registry
-}
-
-type wrapper struct {
- fileName string
- swagger *swaggerObject
-}
-
-// New returns a new generator which generates grpc gateway files.
-func New(reg *descriptor.Registry) gen.Generator {
- return &generator{reg: reg}
-}
-
-// Merge a lot of swagger file (wrapper) to single one swagger file
-func mergeTargetFile(targets []*wrapper, mergeFileName string) *wrapper {
- var mergedTarget *wrapper
- for _, f := range targets {
- if mergedTarget == nil {
- mergedTarget = &wrapper{
- fileName: mergeFileName,
- swagger: f.swagger,
- }
- } else {
- for k, v := range f.swagger.Definitions {
- mergedTarget.swagger.Definitions[k] = v
- }
- for k, v := range f.swagger.Paths {
- mergedTarget.swagger.Paths[k] = v
- }
- for k, v := range f.swagger.SecurityDefinitions {
- mergedTarget.swagger.SecurityDefinitions[k] = v
- }
- mergedTarget.swagger.Security = append(mergedTarget.swagger.Security, f.swagger.Security...)
- }
- }
- return mergedTarget
-}
-
-// Q: What's up with the alias types here?
-// A: We don't want to completely override how these structs are marshaled into
-// JSON, we only want to add fields (see below, extensionMarshalJSON).
-// An infinite recursion would happen if we'd call json.Marshal on the struct
-// that has swaggerObject as an embedded field. To avoid that, we'll create
-// type aliases, and those don't have the custom MarshalJSON methods defined
-// on them. See http://choly.ca/post/go-json-marshalling/ (or, if it ever
-// goes away, use
-// https://web.archive.org/web/20190806073003/http://choly.ca/post/go-json-marshalling/.
-func (so swaggerObject) MarshalJSON() ([]byte, error) {
- type alias swaggerObject
- return extensionMarshalJSON(alias(so), so.extensions)
-}
-
-func (so swaggerInfoObject) MarshalJSON() ([]byte, error) {
- type alias swaggerInfoObject
- return extensionMarshalJSON(alias(so), so.extensions)
-}
-
-func (so swaggerSecuritySchemeObject) MarshalJSON() ([]byte, error) {
- type alias swaggerSecuritySchemeObject
- return extensionMarshalJSON(alias(so), so.extensions)
-}
-
-func (so swaggerOperationObject) MarshalJSON() ([]byte, error) {
- type alias swaggerOperationObject
- return extensionMarshalJSON(alias(so), so.extensions)
-}
-
-func (so swaggerResponseObject) MarshalJSON() ([]byte, error) {
- type alias swaggerResponseObject
- return extensionMarshalJSON(alias(so), so.extensions)
-}
-
-func extensionMarshalJSON(so interface{}, extensions []extension) ([]byte, error) {
- // To append arbitrary keys to the struct we'll render into json,
- // we're creating another struct that embeds the original one, and
- // its extra fields:
- //
- // The struct will look like
- // struct {
- // *swaggerCore
- // XGrpcGatewayFoo json.RawMessage `json:"x-grpc-gateway-foo"`
- // XGrpcGatewayBar json.RawMessage `json:"x-grpc-gateway-bar"`
- // }
- // and thus render into what we want -- the JSON of swaggerCore with the
- // extensions appended.
- fields := []reflect.StructField{
- reflect.StructField{ // embedded
- Name: "Embedded",
- Type: reflect.TypeOf(so),
- Anonymous: true,
- },
- }
- for _, ext := range extensions {
- fields = append(fields, reflect.StructField{
- Name: fieldName(ext.key),
- Type: reflect.TypeOf(ext.value),
- Tag: reflect.StructTag(fmt.Sprintf("json:\"%s\"", ext.key)),
- })
- }
-
- t := reflect.StructOf(fields)
- s := reflect.New(t).Elem()
- s.Field(0).Set(reflect.ValueOf(so))
- for _, ext := range extensions {
- s.FieldByName(fieldName(ext.key)).Set(reflect.ValueOf(ext.value))
- }
- return json.Marshal(s.Interface())
-}
-
-// encodeSwagger converts swagger file obj to plugin.CodeGeneratorResponse_File
-func encodeSwagger(file *wrapper) (*plugin.CodeGeneratorResponse_File, error) {
- var formatted bytes.Buffer
- enc := json.NewEncoder(&formatted)
- enc.SetIndent("", " ")
- if err := enc.Encode(*file.swagger); err != nil {
- return nil, err
- }
- name := file.fileName
- ext := filepath.Ext(name)
- base := strings.TrimSuffix(name, ext)
- output := fmt.Sprintf("%s.swagger.json", base)
- return &plugin.CodeGeneratorResponse_File{
- Name: proto.String(output),
- Content: proto.String(formatted.String()),
- }, nil
-}
-
-func (g *generator) Generate(targets []*descriptor.File) ([]*plugin.CodeGeneratorResponse_File, error) {
- var files []*plugin.CodeGeneratorResponse_File
- if g.reg.IsAllowMerge() {
- var mergedTarget *descriptor.File
- // try to find proto leader
- for _, f := range targets {
- if proto.HasExtension(f.Options, swagger_options.E_Openapiv2Swagger) {
- mergedTarget = f
- break
- }
- }
- // merge protos to leader
- for _, f := range targets {
- if mergedTarget == nil {
- mergedTarget = f
- } else {
- mergedTarget.Enums = append(mergedTarget.Enums, f.Enums...)
- mergedTarget.Messages = append(mergedTarget.Messages, f.Messages...)
- mergedTarget.Services = append(mergedTarget.Services, f.Services...)
- }
- }
-
- targets = nil
- targets = append(targets, mergedTarget)
- }
-
- var swaggers []*wrapper
- for _, file := range targets {
- glog.V(1).Infof("Processing %s", file.GetName())
- swagger, err := applyTemplate(param{File: file, reg: g.reg})
- if err == errNoTargetService {
- glog.V(1).Infof("%s: %v", file.GetName(), err)
- continue
- }
- if err != nil {
- return nil, err
- }
- swaggers = append(swaggers, &wrapper{
- fileName: file.GetName(),
- swagger: swagger,
- })
- }
-
- if g.reg.IsAllowMerge() {
- targetSwagger := mergeTargetFile(swaggers, g.reg.GetMergeFileName())
- f, err := encodeSwagger(targetSwagger)
- if err != nil {
- return nil, fmt.Errorf("failed to encode swagger for %s: %s", g.reg.GetMergeFileName(), err)
- }
- files = append(files, f)
- glog.V(1).Infof("New swagger file will emit")
- } else {
- for _, file := range swaggers {
- f, err := encodeSwagger(file)
- if err != nil {
- return nil, fmt.Errorf("failed to encode swagger for %s: %s", file.fileName, err)
- }
- files = append(files, f)
- glog.V(1).Infof("New swagger file will emit")
- }
- }
- return files, nil
-}
-
-//AddStreamError Adds grpc.gateway.runtime.StreamError and google.protobuf.Any to registry for stream responses
-func AddStreamError(reg *descriptor.Registry) error {
- //load internal protos
- any := fileDescriptorProtoForMessage(&any.Any{})
- streamError := fileDescriptorProtoForMessage(&internal.StreamError{})
- if err := reg.Load(&plugin.CodeGeneratorRequest{
- ProtoFile: []*protocdescriptor.FileDescriptorProto{
- any,
- streamError,
- },
- }); err != nil {
- return err
- }
- return nil
-}
-
-func fileDescriptorProtoForMessage(msg pbdescriptor.Message) *protocdescriptor.FileDescriptorProto {
- fdp, _ := pbdescriptor.ForMessage(msg)
- fdp.SourceCodeInfo = &protocdescriptor.SourceCodeInfo{}
- return fdp
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/helpers.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/helpers.go
deleted file mode 100644
index 3615596..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/helpers.go
+++ /dev/null
@@ -1,9 +0,0 @@
-//+build go1.12
-
-package genswagger
-
-import "strings"
-
-func fieldName(k string) string {
- return strings.ReplaceAll(strings.Title(k), "-", "_")
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/helpers_go111_old.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/helpers_go111_old.go
deleted file mode 100644
index 8e9458d..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/helpers_go111_old.go
+++ /dev/null
@@ -1,9 +0,0 @@
-//+build !go1.12
-
-package genswagger
-
-import "strings"
-
-func fieldName(k string) string {
- return strings.Replace(strings.Title(k), "-", "_", -1)
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/template.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/template.go
deleted file mode 100644
index 1b9e14d..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/template.go
+++ /dev/null
@@ -1,1799 +0,0 @@
-package genswagger
-
-import (
- "bytes"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "os"
- "reflect"
- "regexp"
- "sort"
- "strconv"
- "strings"
- "sync"
- "text/template"
-
- "github.com/golang/glog"
- "github.com/golang/protobuf/jsonpb"
- "github.com/golang/protobuf/proto"
- pbdescriptor "github.com/golang/protobuf/protoc-gen-go/descriptor"
- gogen "github.com/golang/protobuf/protoc-gen-go/generator"
- structpb "github.com/golang/protobuf/ptypes/struct"
- "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
- swagger_options "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options"
-)
-
-var wktSchemas = map[string]schemaCore{
- ".google.protobuf.Timestamp": schemaCore{
- Type: "string",
- Format: "date-time",
- },
- ".google.protobuf.Duration": schemaCore{
- Type: "string",
- },
- ".google.protobuf.StringValue": schemaCore{
- Type: "string",
- },
- ".google.protobuf.BytesValue": schemaCore{
- Type: "string",
- Format: "byte",
- },
- ".google.protobuf.Int32Value": schemaCore{
- Type: "integer",
- Format: "int32",
- },
- ".google.protobuf.UInt32Value": schemaCore{
- Type: "integer",
- Format: "int64",
- },
- ".google.protobuf.Int64Value": schemaCore{
- Type: "string",
- Format: "int64",
- },
- ".google.protobuf.UInt64Value": schemaCore{
- Type: "string",
- Format: "uint64",
- },
- ".google.protobuf.FloatValue": schemaCore{
- Type: "number",
- Format: "float",
- },
- ".google.protobuf.DoubleValue": schemaCore{
- Type: "number",
- Format: "double",
- },
- ".google.protobuf.BoolValue": schemaCore{
- Type: "boolean",
- Format: "boolean",
- },
- ".google.protobuf.Empty": schemaCore{},
- ".google.protobuf.Struct": schemaCore{
- Type: "object",
- },
- ".google.protobuf.Value": schemaCore{
- Type: "object",
- },
- ".google.protobuf.ListValue": schemaCore{
- Type: "array",
- Items: (*swaggerItemsObject)(&schemaCore{
- Type: "object",
- }),
- },
- ".google.protobuf.NullValue": schemaCore{
- Type: "string",
- },
-}
-
-func listEnumNames(enum *descriptor.Enum) (names []string) {
- for _, value := range enum.GetValue() {
- names = append(names, value.GetName())
- }
- return names
-}
-
-func getEnumDefault(enum *descriptor.Enum) string {
- for _, value := range enum.GetValue() {
- if value.GetNumber() == 0 {
- return value.GetName()
- }
- }
- return ""
-}
-
-// messageToQueryParameters converts a message to a list of swagger query parameters.
-func messageToQueryParameters(message *descriptor.Message, reg *descriptor.Registry, pathParams []descriptor.Parameter) (params []swaggerParameterObject, err error) {
- for _, field := range message.Fields {
- p, err := queryParams(message, field, "", reg, pathParams)
- if err != nil {
- return nil, err
- }
- params = append(params, p...)
- }
- return params, nil
-}
-
-// queryParams converts a field to a list of swagger query parameters recursively.
-func queryParams(message *descriptor.Message, field *descriptor.Field, prefix string, reg *descriptor.Registry, pathParams []descriptor.Parameter) (params []swaggerParameterObject, err error) {
- // make sure the parameter is not already listed as a path parameter
- for _, pathParam := range pathParams {
- if pathParam.Target == field {
- return nil, nil
- }
- }
- schema := schemaOfField(field, reg, nil)
- fieldType := field.GetTypeName()
- if message.File != nil {
- comments := fieldProtoComments(reg, message, field)
- if err := updateSwaggerDataFromComments(reg, &schema, message, comments, false); err != nil {
- return nil, err
- }
- }
-
- isEnum := field.GetType() == pbdescriptor.FieldDescriptorProto_TYPE_ENUM
- items := schema.Items
- if schema.Type != "" || isEnum {
- if schema.Type == "object" {
- return nil, nil // TODO: currently, mapping object in query parameter is not supported
- }
- if items != nil && (items.Type == "" || items.Type == "object") && !isEnum {
- return nil, nil // TODO: currently, mapping object in query parameter is not supported
- }
- desc := schema.Description
- if schema.Title != "" { // merge title because title of parameter object will be ignored
- desc = strings.TrimSpace(schema.Title + ". " + schema.Description)
- }
-
- // verify if the field is required
- required := false
- for _, fieldName := range schema.Required {
- if fieldName == field.GetName() {
- required = true
- break
- }
- }
-
- param := swaggerParameterObject{
- Description: desc,
- In: "query",
- Default: schema.Default,
- Type: schema.Type,
- Items: schema.Items,
- Format: schema.Format,
- Required: required,
- }
- if param.Type == "array" {
- param.CollectionFormat = "multi"
- }
-
- if reg.GetUseJSONNamesForFields() {
- param.Name = prefix + field.GetJsonName()
- } else {
- param.Name = prefix + field.GetName()
- }
-
- if isEnum {
- enum, err := reg.LookupEnum("", fieldType)
- if err != nil {
- return nil, fmt.Errorf("unknown enum type %s", fieldType)
- }
- if items != nil { // array
- param.Items = &swaggerItemsObject{
- Type: "string",
- Enum: listEnumNames(enum),
- }
- } else {
- param.Type = "string"
- param.Enum = listEnumNames(enum)
- param.Default = getEnumDefault(enum)
- }
- valueComments := enumValueProtoComments(reg, enum)
- if valueComments != "" {
- param.Description = strings.TrimLeft(param.Description+"\n\n "+valueComments, "\n")
- }
- }
- return []swaggerParameterObject{param}, nil
- }
-
- // nested type, recurse
- msg, err := reg.LookupMsg("", fieldType)
- if err != nil {
- return nil, fmt.Errorf("unknown message type %s", fieldType)
- }
- for _, nestedField := range msg.Fields {
- p, err := queryParams(msg, nestedField, prefix+field.GetName()+".", reg, pathParams)
- if err != nil {
- return nil, err
- }
- params = append(params, p...)
- }
- return params, nil
-}
-
-// findServicesMessagesAndEnumerations discovers all messages and enums defined in the RPC methods of the service.
-func findServicesMessagesAndEnumerations(s []*descriptor.Service, reg *descriptor.Registry, m messageMap, ms messageMap, e enumMap, refs refMap) {
- for _, svc := range s {
- for _, meth := range svc.Methods {
- // Request may be fully included in query
- if _, ok := refs[fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg))]; ok {
- if !skipRenderingRef(meth.RequestType.FQMN()) {
- m[fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg)] = meth.RequestType
- }
- }
- findNestedMessagesAndEnumerations(meth.RequestType, reg, m, e)
-
- if !skipRenderingRef(meth.ResponseType.FQMN()) {
- m[fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg)] = meth.ResponseType
- if meth.GetServerStreaming() {
- runtimeStreamError := fullyQualifiedNameToSwaggerName(".grpc.gateway.runtime.StreamError", reg)
- glog.V(1).Infof("StreamError FQMN: %s", runtimeStreamError)
- streamError, err := reg.LookupMsg(".grpc.gateway.runtime", "StreamError")
- if err == nil {
- glog.V(1).Infof("StreamError: %v", streamError)
- m[runtimeStreamError] = streamError
- findNestedMessagesAndEnumerations(streamError, reg, m, e)
- } else {
- //just in case there is an error looking up StreamError
- glog.Error(err)
- }
- ms[fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg)] = meth.ResponseType
- }
- }
- findNestedMessagesAndEnumerations(meth.ResponseType, reg, m, e)
- }
- }
-}
-
-// findNestedMessagesAndEnumerations those can be generated by the services.
-func findNestedMessagesAndEnumerations(message *descriptor.Message, reg *descriptor.Registry, m messageMap, e enumMap) {
- // Iterate over all the fields that
- for _, t := range message.Fields {
- fieldType := t.GetTypeName()
- // If the type is an empty string then it is a proto primitive
- if fieldType != "" {
- if _, ok := m[fieldType]; !ok {
- msg, err := reg.LookupMsg("", fieldType)
- if err != nil {
- enum, err := reg.LookupEnum("", fieldType)
- if err != nil {
- panic(err)
- }
- e[fieldType] = enum
- continue
- }
- m[fieldType] = msg
- findNestedMessagesAndEnumerations(msg, reg, m, e)
- }
- }
- }
-}
-
-func skipRenderingRef(refName string) bool {
- _, ok := wktSchemas[refName]
- return ok
-}
-
-func renderMessagesAsDefinition(messages messageMap, d swaggerDefinitionsObject, reg *descriptor.Registry, customRefs refMap) {
- for name, msg := range messages {
- if skipRenderingRef(name) {
- continue
- }
-
- if opt := msg.GetOptions(); opt != nil && opt.MapEntry != nil && *opt.MapEntry {
- continue
- }
- schema := swaggerSchemaObject{
- schemaCore: schemaCore{
- Type: "object",
- },
- }
- msgComments := protoComments(reg, msg.File, msg.Outers, "MessageType", int32(msg.Index))
- if err := updateSwaggerDataFromComments(reg, &schema, msg, msgComments, false); err != nil {
- panic(err)
- }
- opts, err := extractSchemaOptionFromMessageDescriptor(msg.DescriptorProto)
- if err != nil {
- panic(err)
- }
- if opts != nil {
- protoSchema := swaggerSchemaFromProtoSchema(opts, reg, customRefs, msg)
-
- // Warning: Make sure not to overwrite any fields already set on the schema type.
- schema.ExternalDocs = protoSchema.ExternalDocs
- schema.ReadOnly = protoSchema.ReadOnly
- schema.MultipleOf = protoSchema.MultipleOf
- schema.Maximum = protoSchema.Maximum
- schema.ExclusiveMaximum = protoSchema.ExclusiveMaximum
- schema.Minimum = protoSchema.Minimum
- schema.ExclusiveMinimum = protoSchema.ExclusiveMinimum
- schema.MaxLength = protoSchema.MaxLength
- schema.MinLength = protoSchema.MinLength
- schema.Pattern = protoSchema.Pattern
- schema.Default = protoSchema.Default
- schema.MaxItems = protoSchema.MaxItems
- schema.MinItems = protoSchema.MinItems
- schema.UniqueItems = protoSchema.UniqueItems
- schema.MaxProperties = protoSchema.MaxProperties
- schema.MinProperties = protoSchema.MinProperties
- schema.Required = protoSchema.Required
- if protoSchema.schemaCore.Type != "" || protoSchema.schemaCore.Ref != "" {
- schema.schemaCore = protoSchema.schemaCore
- }
- if protoSchema.Title != "" {
- schema.Title = protoSchema.Title
- }
- if protoSchema.Description != "" {
- schema.Description = protoSchema.Description
- }
- if protoSchema.Example != nil {
- schema.Example = protoSchema.Example
- }
- }
-
- for _, f := range msg.Fields {
- fieldValue := schemaOfField(f, reg, customRefs)
- comments := fieldProtoComments(reg, msg, f)
- if err := updateSwaggerDataFromComments(reg, &fieldValue, f, comments, false); err != nil {
- panic(err)
- }
-
- kv := keyVal{Value: fieldValue}
- if reg.GetUseJSONNamesForFields() {
- kv.Key = f.GetJsonName()
- } else {
- kv.Key = f.GetName()
- }
- if schema.Properties == nil {
- schema.Properties = &swaggerSchemaObjectProperties{}
- }
- *schema.Properties = append(*schema.Properties, kv)
- }
- d[fullyQualifiedNameToSwaggerName(msg.FQMN(), reg)] = schema
- }
-}
-
-// schemaOfField returns a swagger Schema Object for a protobuf field.
-func schemaOfField(f *descriptor.Field, reg *descriptor.Registry, refs refMap) swaggerSchemaObject {
- const (
- singular = 0
- array = 1
- object = 2
- )
- var (
- core schemaCore
- aggregate int
- )
-
- fd := f.FieldDescriptorProto
- if m, err := reg.LookupMsg("", f.GetTypeName()); err == nil {
- if opt := m.GetOptions(); opt != nil && opt.MapEntry != nil && *opt.MapEntry {
- fd = m.GetField()[1]
- aggregate = object
- }
- }
- if fd.GetLabel() == pbdescriptor.FieldDescriptorProto_LABEL_REPEATED {
- aggregate = array
- }
-
- var props *swaggerSchemaObjectProperties
-
- switch ft := fd.GetType(); ft {
- case pbdescriptor.FieldDescriptorProto_TYPE_ENUM, pbdescriptor.FieldDescriptorProto_TYPE_MESSAGE, pbdescriptor.FieldDescriptorProto_TYPE_GROUP:
- if wktSchema, ok := wktSchemas[fd.GetTypeName()]; ok {
- core = wktSchema
-
- if fd.GetTypeName() == ".google.protobuf.Empty" {
- props = &swaggerSchemaObjectProperties{}
- }
- } else {
- core = schemaCore{
- Ref: "#/definitions/" + fullyQualifiedNameToSwaggerName(fd.GetTypeName(), reg),
- }
- if refs != nil {
- refs[fd.GetTypeName()] = struct{}{}
-
- }
- }
- default:
- ftype, format, ok := primitiveSchema(ft)
- if ok {
- core = schemaCore{Type: ftype, Format: format}
- } else {
- core = schemaCore{Type: ft.String(), Format: "UNKNOWN"}
- }
- }
-
- ret := swaggerSchemaObject{}
-
- switch aggregate {
- case array:
- ret = swaggerSchemaObject{
- schemaCore: schemaCore{
- Type: "array",
- Items: (*swaggerItemsObject)(&core),
- },
- }
- case object:
- ret = swaggerSchemaObject{
- schemaCore: schemaCore{
- Type: "object",
- },
- AdditionalProperties: &swaggerSchemaObject{Properties: props, schemaCore: core},
- }
- default:
- ret = swaggerSchemaObject{
- schemaCore: core,
- Properties: props,
- }
- }
-
- if j, err := extractJSONSchemaFromFieldDescriptor(fd); err == nil {
- updateSwaggerObjectFromJSONSchema(&ret, j, reg, f)
- }
-
- return ret
-}
-
-// primitiveSchema returns a pair of "Type" and "Format" in JSON Schema for
-// the given primitive field type.
-// The last return parameter is true iff the field type is actually primitive.
-func primitiveSchema(t pbdescriptor.FieldDescriptorProto_Type) (ftype, format string, ok bool) {
- switch t {
- case pbdescriptor.FieldDescriptorProto_TYPE_DOUBLE:
- return "number", "double", true
- case pbdescriptor.FieldDescriptorProto_TYPE_FLOAT:
- return "number", "float", true
- case pbdescriptor.FieldDescriptorProto_TYPE_INT64:
- return "string", "int64", true
- case pbdescriptor.FieldDescriptorProto_TYPE_UINT64:
- // 64bit integer types are marshaled as string in the default JSONPb marshaler.
- // TODO(yugui) Add an option to declare 64bit integers as int64.
- //
- // NOTE: uint64 is not a predefined format of integer type in Swagger spec.
- // So we cannot expect that uint64 is commonly supported by swagger processor.
- return "string", "uint64", true
- case pbdescriptor.FieldDescriptorProto_TYPE_INT32:
- return "integer", "int32", true
- case pbdescriptor.FieldDescriptorProto_TYPE_FIXED64:
- // Ditto.
- return "string", "uint64", true
- case pbdescriptor.FieldDescriptorProto_TYPE_FIXED32:
- // Ditto.
- return "integer", "int64", true
- case pbdescriptor.FieldDescriptorProto_TYPE_BOOL:
- return "boolean", "boolean", true
- case pbdescriptor.FieldDescriptorProto_TYPE_STRING:
- // NOTE: in swagger specifition, format should be empty on string type
- return "string", "", true
- case pbdescriptor.FieldDescriptorProto_TYPE_BYTES:
- return "string", "byte", true
- case pbdescriptor.FieldDescriptorProto_TYPE_UINT32:
- // Ditto.
- return "integer", "int64", true
- case pbdescriptor.FieldDescriptorProto_TYPE_SFIXED32:
- return "integer", "int32", true
- case pbdescriptor.FieldDescriptorProto_TYPE_SFIXED64:
- return "string", "int64", true
- case pbdescriptor.FieldDescriptorProto_TYPE_SINT32:
- return "integer", "int32", true
- case pbdescriptor.FieldDescriptorProto_TYPE_SINT64:
- return "string", "int64", true
- default:
- return "", "", false
- }
-}
-
-// renderEnumerationsAsDefinition inserts enums into the definitions object.
-func renderEnumerationsAsDefinition(enums enumMap, d swaggerDefinitionsObject, reg *descriptor.Registry) {
- for _, enum := range enums {
- enumComments := protoComments(reg, enum.File, enum.Outers, "EnumType", int32(enum.Index))
-
- // it may be necessary to sort the result of the GetValue function.
- enumNames := listEnumNames(enum)
- defaultValue := getEnumDefault(enum)
- valueComments := enumValueProtoComments(reg, enum)
- if valueComments != "" {
- enumComments = strings.TrimLeft(enumComments+"\n\n "+valueComments, "\n")
- }
- enumSchemaObject := swaggerSchemaObject{
- schemaCore: schemaCore{
- Type: "string",
- Enum: enumNames,
- Default: defaultValue,
- },
- }
- if err := updateSwaggerDataFromComments(reg, &enumSchemaObject, enum, enumComments, false); err != nil {
- panic(err)
- }
-
- d[fullyQualifiedNameToSwaggerName(enum.FQEN(), reg)] = enumSchemaObject
- }
-}
-
-// Take in a FQMN or FQEN and return a swagger safe version of the FQMN
-func fullyQualifiedNameToSwaggerName(fqn string, reg *descriptor.Registry) string {
- registriesSeenMutex.Lock()
- defer registriesSeenMutex.Unlock()
- if mapping, present := registriesSeen[reg]; present {
- return mapping[fqn]
- }
- mapping := resolveFullyQualifiedNameToSwaggerNames(append(reg.GetAllFQMNs(), reg.GetAllFQENs()...), reg.GetUseFQNForSwaggerName())
- registriesSeen[reg] = mapping
- return mapping[fqn]
-}
-
-// registriesSeen is used to memoise calls to resolveFullyQualifiedNameToSwaggerNames so
-// we don't repeat it unnecessarily, since it can take some time.
-var registriesSeen = map[*descriptor.Registry]map[string]string{}
-var registriesSeenMutex sync.Mutex
-
-// Take the names of every proto and "uniq-ify" them. The idea is to produce a
-// set of names that meet a couple of conditions. They must be stable, they
-// must be unique, and they must be shorter than the FQN.
-//
-// This likely could be made better. This will always generate the same names
-// but may not always produce optimal names. This is a reasonably close
-// approximation of what they should look like in most cases.
-func resolveFullyQualifiedNameToSwaggerNames(messages []string, useFQNForSwaggerName bool) map[string]string {
- packagesByDepth := make(map[int][][]string)
- uniqueNames := make(map[string]string)
-
- hierarchy := func(pkg string) []string {
- return strings.Split(pkg, ".")
- }
-
- for _, p := range messages {
- h := hierarchy(p)
- for depth := range h {
- if _, ok := packagesByDepth[depth]; !ok {
- packagesByDepth[depth] = make([][]string, 0)
- }
- packagesByDepth[depth] = append(packagesByDepth[depth], h[len(h)-depth:])
- }
- }
-
- count := func(list [][]string, item []string) int {
- i := 0
- for _, element := range list {
- if reflect.DeepEqual(element, item) {
- i++
- }
- }
- return i
- }
-
- for _, p := range messages {
- if useFQNForSwaggerName {
- // strip leading dot from proto fqn
- uniqueNames[p] = p[1:]
- } else {
- h := hierarchy(p)
- for depth := 0; depth < len(h); depth++ {
- if count(packagesByDepth[depth], h[len(h)-depth:]) == 1 {
- uniqueNames[p] = strings.Join(h[len(h)-depth-1:], "")
- break
- }
- if depth == len(h)-1 {
- uniqueNames[p] = strings.Join(h, "")
- }
- }
- }
- }
- return uniqueNames
-}
-
-var canRegexp = regexp.MustCompile("{([a-zA-Z][a-zA-Z0-9_.]*).*}")
-
-// Swagger expects paths of the form /path/{string_value} but grpc-gateway paths are expected to be of the form /path/{string_value=strprefix/*}. This should reformat it correctly.
-func templateToSwaggerPath(path string, reg *descriptor.Registry, fields []*descriptor.Field) string {
- // It seems like the right thing to do here is to just use
- // strings.Split(path, "/") but that breaks badly when you hit a url like
- // /{my_field=prefix/*}/ and end up with 2 sections representing my_field.
- // Instead do the right thing and write a small pushdown (counter) automata
- // for it.
- var parts []string
- depth := 0
- buffer := ""
- jsonBuffer := ""
- for _, char := range path {
- switch char {
- case '{':
- // Push on the stack
- depth++
- buffer += string(char)
- jsonBuffer = ""
- jsonBuffer += string(char)
- break
- case '}':
- if depth == 0 {
- panic("Encountered } without matching { before it.")
- }
- // Pop from the stack
- depth--
- buffer += string(char)
- if reg.GetUseJSONNamesForFields() &&
- len(jsonBuffer) > 1 {
- jsonSnakeCaseName := string(jsonBuffer[1:])
- jsonCamelCaseName := string(lowerCamelCase(jsonSnakeCaseName, fields))
- prev := string(buffer[:len(buffer)-len(jsonSnakeCaseName)-2])
- buffer = strings.Join([]string{prev, "{", jsonCamelCaseName, "}"}, "")
- jsonBuffer = ""
- }
- case '/':
- if depth == 0 {
- parts = append(parts, buffer)
- buffer = ""
- // Since the stack was empty when we hit the '/' we are done with this
- // section.
- continue
- }
- buffer += string(char)
- jsonBuffer += string(char)
- default:
- buffer += string(char)
- jsonBuffer += string(char)
- break
- }
- }
-
- // Now append the last element to parts
- parts = append(parts, buffer)
-
- // Parts is now an array of segments of the path. Interestingly, since the
- // syntax for this subsection CAN be handled by a regexp since it has no
- // memory.
- for index, part := range parts {
- // If part is a resource name such as "parent", "name", "user.name", the format info must be retained.
- prefix := canRegexp.ReplaceAllString(part, "$1")
- if isResourceName(prefix) {
- continue
- }
- parts[index] = canRegexp.ReplaceAllString(part, "{$1}")
- }
-
- return strings.Join(parts, "/")
-}
-
-func isResourceName(prefix string) bool {
- words := strings.Split(prefix, ".")
- l := len(words)
- field := words[l-1]
- words = strings.Split(field, ":")
- field = words[0]
- return field == "parent" || field == "name"
-}
-
-func renderServices(services []*descriptor.Service, paths swaggerPathsObject, reg *descriptor.Registry, requestResponseRefs, customRefs refMap) error {
- // Correctness of svcIdx and methIdx depends on 'services' containing the services in the same order as the 'file.Service' array.
- for svcIdx, svc := range services {
- for methIdx, meth := range svc.Methods {
- for bIdx, b := range meth.Bindings {
- // Iterate over all the swagger parameters
- parameters := swaggerParametersObject{}
- for _, parameter := range b.PathParams {
-
- var paramType, paramFormat, desc, collectionFormat, defaultValue string
- var enumNames []string
- var items *swaggerItemsObject
- var minItems *int
- switch pt := parameter.Target.GetType(); pt {
- case pbdescriptor.FieldDescriptorProto_TYPE_GROUP, pbdescriptor.FieldDescriptorProto_TYPE_MESSAGE:
- if descriptor.IsWellKnownType(parameter.Target.GetTypeName()) {
- if parameter.IsRepeated() {
- return fmt.Errorf("only primitive and enum types are allowed in repeated path parameters")
- }
- schema := schemaOfField(parameter.Target, reg, customRefs)
- paramType = schema.Type
- paramFormat = schema.Format
- desc = schema.Description
- defaultValue = schema.Default
- } else {
- return fmt.Errorf("only primitive and well-known types are allowed in path parameters")
- }
- case pbdescriptor.FieldDescriptorProto_TYPE_ENUM:
- paramType = "string"
- paramFormat = ""
- enum, err := reg.LookupEnum("", parameter.Target.GetTypeName())
- if err != nil {
- return err
- }
- enumNames = listEnumNames(enum)
- schema := schemaOfField(parameter.Target, reg, customRefs)
- desc = schema.Description
- defaultValue = schema.Default
- default:
- var ok bool
- paramType, paramFormat, ok = primitiveSchema(pt)
- if !ok {
- return fmt.Errorf("unknown field type %v", pt)
- }
-
- schema := schemaOfField(parameter.Target, reg, customRefs)
- desc = schema.Description
- defaultValue = schema.Default
- }
-
- if parameter.IsRepeated() {
- core := schemaCore{Type: paramType, Format: paramFormat}
- if parameter.IsEnum() {
- var s []string
- core.Enum = enumNames
- enumNames = s
- }
- items = (*swaggerItemsObject)(&core)
- paramType = "array"
- paramFormat = ""
- collectionFormat = reg.GetRepeatedPathParamSeparatorName()
- minItems = new(int)
- *minItems = 1
- }
-
- if desc == "" {
- desc = fieldProtoComments(reg, parameter.Target.Message, parameter.Target)
- }
- parameterString := parameter.String()
- if reg.GetUseJSONNamesForFields() {
- parameterString = lowerCamelCase(parameterString, meth.RequestType.Fields)
- }
- parameters = append(parameters, swaggerParameterObject{
- Name: parameterString,
- Description: desc,
- In: "path",
- Required: true,
- Default: defaultValue,
- // Parameters in gRPC-Gateway can only be strings?
- Type: paramType,
- Format: paramFormat,
- Enum: enumNames,
- Items: items,
- CollectionFormat: collectionFormat,
- MinItems: minItems,
- })
- }
- // Now check if there is a body parameter
- if b.Body != nil {
- var schema swaggerSchemaObject
- desc := ""
-
- if len(b.Body.FieldPath) == 0 {
- schema = swaggerSchemaObject{
- schemaCore: schemaCore{},
- }
-
- wknSchemaCore, isWkn := wktSchemas[meth.RequestType.FQMN()]
- if !isWkn {
- schema.Ref = fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.RequestType.FQMN(), reg))
- } else {
- schema.schemaCore = wknSchemaCore
-
- // Special workaround for Empty: it's well-known type but wknSchemas only returns schema.schemaCore; but we need to set schema.Properties which is a level higher.
- if meth.RequestType.FQMN() == ".google.protobuf.Empty" {
- schema.Properties = &swaggerSchemaObjectProperties{}
- }
- }
- } else {
- lastField := b.Body.FieldPath[len(b.Body.FieldPath)-1]
- schema = schemaOfField(lastField.Target, reg, customRefs)
- if schema.Description != "" {
- desc = schema.Description
- } else {
- desc = fieldProtoComments(reg, lastField.Target.Message, lastField.Target)
- }
- }
-
- if meth.GetClientStreaming() {
- desc += " (streaming inputs)"
- }
- parameters = append(parameters, swaggerParameterObject{
- Name: "body",
- Description: desc,
- In: "body",
- Required: true,
- Schema: &schema,
- })
- } else if b.HTTPMethod == "GET" || b.HTTPMethod == "DELETE" {
- // add the parameters to the query string
- queryParams, err := messageToQueryParameters(meth.RequestType, reg, b.PathParams)
- if err != nil {
- return err
- }
- parameters = append(parameters, queryParams...)
- }
-
- pathItemObject, ok := paths[templateToSwaggerPath(b.PathTmpl.Template, reg, meth.RequestType.Fields)]
- if !ok {
- pathItemObject = swaggerPathItemObject{}
- }
-
- methProtoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.ServiceDescriptorProto)(nil)), "Method")
- desc := "A successful response."
- var responseSchema swaggerSchemaObject
-
- if b.ResponseBody == nil || len(b.ResponseBody.FieldPath) == 0 {
- responseSchema = swaggerSchemaObject{
- schemaCore: schemaCore{},
- }
-
- // Don't link to a full definition for
- // empty; it's overly verbose.
- // schema.Properties{} renders it as
- // well, without a definition
- wknSchemaCore, isWkn := wktSchemas[meth.ResponseType.FQMN()]
- if !isWkn {
- responseSchema.Ref = fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg))
- } else {
- responseSchema.schemaCore = wknSchemaCore
-
- // Special workaround for Empty: it's well-known type but wknSchemas only returns schema.schemaCore; but we need to set schema.Properties which is a level higher.
- if meth.ResponseType.FQMN() == ".google.protobuf.Empty" {
- responseSchema.Properties = &swaggerSchemaObjectProperties{}
- }
- }
- } else {
- // This is resolving the value of response_body in the google.api.HttpRule
- lastField := b.ResponseBody.FieldPath[len(b.ResponseBody.FieldPath)-1]
- responseSchema = schemaOfField(lastField.Target, reg, customRefs)
- if responseSchema.Description != "" {
- desc = responseSchema.Description
- } else {
- desc = fieldProtoComments(reg, lastField.Target.Message, lastField.Target)
- }
- }
- if meth.GetServerStreaming() {
- desc += "(streaming responses)"
- responseSchema.Type = "object"
- responseSchema.Title = fmt.Sprintf("Stream result of %s", fullyQualifiedNameToSwaggerName(meth.ResponseType.FQMN(), reg))
- responseSchema.Properties = &swaggerSchemaObjectProperties{
- keyVal{
- Key: "result",
- Value: swaggerSchemaObject{
- schemaCore: schemaCore{
- Ref: responseSchema.Ref,
- },
- },
- },
- keyVal{
- Key: "error",
- Value: swaggerSchemaObject{
- schemaCore: schemaCore{
- Ref: fmt.Sprintf("#/definitions/%s", fullyQualifiedNameToSwaggerName(".grpc.gateway.runtime.StreamError", reg))},
- },
- },
- }
- responseSchema.Ref = ""
- }
-
- tag := svc.GetName()
- if pkg := svc.File.GetPackage(); pkg != "" && reg.IsIncludePackageInTags() {
- tag = pkg + "." + tag
- }
-
- operationObject := &swaggerOperationObject{
- Tags: []string{tag},
- Parameters: parameters,
- Responses: swaggerResponsesObject{
- "200": swaggerResponseObject{
- Description: desc,
- Schema: responseSchema,
- },
- },
- }
- if bIdx == 0 {
- operationObject.OperationID = fmt.Sprintf("%s", meth.GetName())
- } else {
- // OperationID must be unique in an OpenAPI v2 definition.
- operationObject.OperationID = fmt.Sprintf("%s%d", meth.GetName(), bIdx+1)
- }
-
- // Fill reference map with referenced request messages
- for _, param := range operationObject.Parameters {
- if param.Schema != nil && param.Schema.Ref != "" {
- requestResponseRefs[param.Schema.Ref] = struct{}{}
- }
- }
-
- methComments := protoComments(reg, svc.File, nil, "Service", int32(svcIdx), methProtoPath, int32(methIdx))
- if err := updateSwaggerDataFromComments(reg, operationObject, meth, methComments, false); err != nil {
- panic(err)
- }
-
- opts, err := extractOperationOptionFromMethodDescriptor(meth.MethodDescriptorProto)
- if opts != nil {
- if err != nil {
- panic(err)
- }
- operationObject.ExternalDocs = protoExternalDocumentationToSwaggerExternalDocumentation(opts.ExternalDocs, reg, meth)
- // TODO(ivucica): this would be better supported by looking whether the method is deprecated in the proto file
- operationObject.Deprecated = opts.Deprecated
-
- if opts.Summary != "" {
- operationObject.Summary = opts.Summary
- }
- if opts.Description != "" {
- operationObject.Description = opts.Description
- }
- if len(opts.Tags) > 0 {
- operationObject.Tags = make([]string, len(opts.Tags))
- copy(operationObject.Tags, opts.Tags)
- }
- if opts.OperationId != "" {
- operationObject.OperationID = opts.OperationId
- }
- if opts.Security != nil {
- newSecurity := []swaggerSecurityRequirementObject{}
- if operationObject.Security != nil {
- newSecurity = *operationObject.Security
- }
- for _, secReq := range opts.Security {
- newSecReq := swaggerSecurityRequirementObject{}
- for secReqKey, secReqValue := range secReq.SecurityRequirement {
- if secReqValue == nil {
- continue
- }
-
- newSecReqValue := make([]string, len(secReqValue.Scope))
- copy(newSecReqValue, secReqValue.Scope)
- newSecReq[secReqKey] = newSecReqValue
- }
-
- if len(newSecReq) > 0 {
- newSecurity = append(newSecurity, newSecReq)
- }
- }
- operationObject.Security = &newSecurity
- }
- if opts.Responses != nil {
- for name, resp := range opts.Responses {
- respObj := swaggerResponseObject{
- Description: resp.Description,
- Schema: swaggerSchemaFromProtoSchema(resp.Schema, reg, customRefs, meth),
- }
- if resp.Extensions != nil {
- exts, err := processExtensions(resp.Extensions)
- if err != nil {
- return err
- }
- respObj.extensions = exts
- }
- operationObject.Responses[name] = respObj
- }
- }
-
- if opts.Extensions != nil {
- exts, err := processExtensions(opts.Extensions)
- if err != nil {
- return err
- }
- operationObject.extensions = exts
- }
-
- // TODO(ivucica): add remaining fields of operation object
- }
-
- switch b.HTTPMethod {
- case "DELETE":
- pathItemObject.Delete = operationObject
- break
- case "GET":
- pathItemObject.Get = operationObject
- break
- case "POST":
- pathItemObject.Post = operationObject
- break
- case "PUT":
- pathItemObject.Put = operationObject
- break
- case "PATCH":
- pathItemObject.Patch = operationObject
- break
- }
- paths[templateToSwaggerPath(b.PathTmpl.Template, reg, meth.RequestType.Fields)] = pathItemObject
- }
- }
- }
-
- // Success! return nil on the error object
- return nil
-}
-
-// This function is called with a param which contains the entire definition of a method.
-func applyTemplate(p param) (*swaggerObject, error) {
- // Create the basic template object. This is the object that everything is
- // defined off of.
- s := swaggerObject{
- // Swagger 2.0 is the version of this document
- Swagger: "2.0",
- Consumes: []string{"application/json"},
- Produces: []string{"application/json"},
- Paths: make(swaggerPathsObject),
- Definitions: make(swaggerDefinitionsObject),
- Info: swaggerInfoObject{
- Title: *p.File.Name,
- Version: "version not set",
- },
- }
-
- // Loops through all the services and their exposed GET/POST/PUT/DELETE definitions
- // and create entries for all of them.
- // Also adds custom user specified references to second map.
- requestResponseRefs, customRefs := refMap{}, refMap{}
- if err := renderServices(p.Services, s.Paths, p.reg, requestResponseRefs, customRefs); err != nil {
- panic(err)
- }
-
- // Find all the service's messages and enumerations that are defined (recursively)
- // and write request, response and other custom (but referenced) types out as definition objects.
- m := messageMap{}
- ms := messageMap{}
- e := enumMap{}
- findServicesMessagesAndEnumerations(p.Services, p.reg, m, ms, e, requestResponseRefs)
- renderMessagesAsDefinition(m, s.Definitions, p.reg, customRefs)
- renderEnumerationsAsDefinition(e, s.Definitions, p.reg)
-
- // File itself might have some comments and metadata.
- packageProtoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Package")
- packageComments := protoComments(p.reg, p.File, nil, "Package", packageProtoPath)
- if err := updateSwaggerDataFromComments(p.reg, &s, p, packageComments, true); err != nil {
- panic(err)
- }
-
- // There may be additional options in the swagger option in the proto.
- spb, err := extractSwaggerOptionFromFileDescriptor(p.FileDescriptorProto)
- if err != nil {
- panic(err)
- }
- if spb != nil {
- if spb.Swagger != "" {
- s.Swagger = spb.Swagger
- }
- if spb.Info != nil {
- if spb.Info.Title != "" {
- s.Info.Title = spb.Info.Title
- }
- if spb.Info.Description != "" {
- s.Info.Description = spb.Info.Description
- }
- if spb.Info.TermsOfService != "" {
- s.Info.TermsOfService = spb.Info.TermsOfService
- }
- if spb.Info.Version != "" {
- s.Info.Version = spb.Info.Version
- }
- if spb.Info.Contact != nil {
- if s.Info.Contact == nil {
- s.Info.Contact = &swaggerContactObject{}
- }
- if spb.Info.Contact.Name != "" {
- s.Info.Contact.Name = spb.Info.Contact.Name
- }
- if spb.Info.Contact.Url != "" {
- s.Info.Contact.URL = spb.Info.Contact.Url
- }
- if spb.Info.Contact.Email != "" {
- s.Info.Contact.Email = spb.Info.Contact.Email
- }
- }
- if spb.Info.License != nil {
- if s.Info.License == nil {
- s.Info.License = &swaggerLicenseObject{}
- }
- if spb.Info.License.Name != "" {
- s.Info.License.Name = spb.Info.License.Name
- }
- if spb.Info.License.Url != "" {
- s.Info.License.URL = spb.Info.License.Url
- }
- }
- if spb.Info.Extensions != nil {
- exts, err := processExtensions(spb.Info.Extensions)
- if err != nil {
- return nil, err
- }
- s.Info.extensions = exts
- }
- }
- if spb.Host != "" {
- s.Host = spb.Host
- }
- if spb.BasePath != "" {
- s.BasePath = spb.BasePath
- }
- if len(spb.Schemes) > 0 {
- s.Schemes = make([]string, len(spb.Schemes))
- for i, scheme := range spb.Schemes {
- s.Schemes[i] = strings.ToLower(scheme.String())
- }
- }
- if len(spb.Consumes) > 0 {
- s.Consumes = make([]string, len(spb.Consumes))
- copy(s.Consumes, spb.Consumes)
- }
- if len(spb.Produces) > 0 {
- s.Produces = make([]string, len(spb.Produces))
- copy(s.Produces, spb.Produces)
- }
- if spb.SecurityDefinitions != nil && spb.SecurityDefinitions.Security != nil {
- if s.SecurityDefinitions == nil {
- s.SecurityDefinitions = swaggerSecurityDefinitionsObject{}
- }
- for secDefKey, secDefValue := range spb.SecurityDefinitions.Security {
- var newSecDefValue swaggerSecuritySchemeObject
- if oldSecDefValue, ok := s.SecurityDefinitions[secDefKey]; !ok {
- newSecDefValue = swaggerSecuritySchemeObject{}
- } else {
- newSecDefValue = oldSecDefValue
- }
- if secDefValue.Type != swagger_options.SecurityScheme_TYPE_INVALID {
- switch secDefValue.Type {
- case swagger_options.SecurityScheme_TYPE_BASIC:
- newSecDefValue.Type = "basic"
- case swagger_options.SecurityScheme_TYPE_API_KEY:
- newSecDefValue.Type = "apiKey"
- case swagger_options.SecurityScheme_TYPE_OAUTH2:
- newSecDefValue.Type = "oauth2"
- }
- }
- if secDefValue.Description != "" {
- newSecDefValue.Description = secDefValue.Description
- }
- if secDefValue.Name != "" {
- newSecDefValue.Name = secDefValue.Name
- }
- if secDefValue.In != swagger_options.SecurityScheme_IN_INVALID {
- switch secDefValue.In {
- case swagger_options.SecurityScheme_IN_QUERY:
- newSecDefValue.In = "query"
- case swagger_options.SecurityScheme_IN_HEADER:
- newSecDefValue.In = "header"
- }
- }
- if secDefValue.Flow != swagger_options.SecurityScheme_FLOW_INVALID {
- switch secDefValue.Flow {
- case swagger_options.SecurityScheme_FLOW_IMPLICIT:
- newSecDefValue.Flow = "implicit"
- case swagger_options.SecurityScheme_FLOW_PASSWORD:
- newSecDefValue.Flow = "password"
- case swagger_options.SecurityScheme_FLOW_APPLICATION:
- newSecDefValue.Flow = "application"
- case swagger_options.SecurityScheme_FLOW_ACCESS_CODE:
- newSecDefValue.Flow = "accessCode"
- }
- }
- if secDefValue.AuthorizationUrl != "" {
- newSecDefValue.AuthorizationURL = secDefValue.AuthorizationUrl
- }
- if secDefValue.TokenUrl != "" {
- newSecDefValue.TokenURL = secDefValue.TokenUrl
- }
- if secDefValue.Scopes != nil {
- if newSecDefValue.Scopes == nil {
- newSecDefValue.Scopes = swaggerScopesObject{}
- }
- for scopeKey, scopeDesc := range secDefValue.Scopes.Scope {
- newSecDefValue.Scopes[scopeKey] = scopeDesc
- }
- }
- if secDefValue.Extensions != nil {
- exts, err := processExtensions(secDefValue.Extensions)
- if err != nil {
- return nil, err
- }
- newSecDefValue.extensions = exts
- }
- s.SecurityDefinitions[secDefKey] = newSecDefValue
- }
- }
- if spb.Security != nil {
- newSecurity := []swaggerSecurityRequirementObject{}
- if s.Security == nil {
- newSecurity = []swaggerSecurityRequirementObject{}
- } else {
- newSecurity = s.Security
- }
- for _, secReq := range spb.Security {
- newSecReq := swaggerSecurityRequirementObject{}
- for secReqKey, secReqValue := range secReq.SecurityRequirement {
- newSecReqValue := make([]string, len(secReqValue.Scope))
- copy(newSecReqValue, secReqValue.Scope)
- newSecReq[secReqKey] = newSecReqValue
- }
- newSecurity = append(newSecurity, newSecReq)
- }
- s.Security = newSecurity
- }
- s.ExternalDocs = protoExternalDocumentationToSwaggerExternalDocumentation(spb.ExternalDocs, p.reg, spb)
- // Populate all Paths with Responses set at top level,
- // preferring Responses already set over those at the top level.
- if spb.Responses != nil {
- for _, verbs := range s.Paths {
- var maps []swaggerResponsesObject
- if verbs.Delete != nil {
- maps = append(maps, verbs.Delete.Responses)
- }
- if verbs.Get != nil {
- maps = append(maps, verbs.Get.Responses)
- }
- if verbs.Post != nil {
- maps = append(maps, verbs.Post.Responses)
- }
- if verbs.Put != nil {
- maps = append(maps, verbs.Put.Responses)
- }
- if verbs.Patch != nil {
- maps = append(maps, verbs.Patch.Responses)
- }
-
- for k, v := range spb.Responses {
- for _, respMap := range maps {
- if _, ok := respMap[k]; ok {
- // Don't overwrite already existing Responses
- continue
- }
- respMap[k] = swaggerResponseObject{
- Description: v.Description,
- Schema: swaggerSchemaFromProtoSchema(v.Schema, p.reg, customRefs, nil),
- }
- }
- }
- }
- }
-
- if spb.Extensions != nil {
- exts, err := processExtensions(spb.Extensions)
- if err != nil {
- return nil, err
- }
- s.extensions = exts
- }
-
- // Additional fields on the OpenAPI v2 spec's "Swagger" object
- // should be added here, once supported in the proto.
- }
-
- // Finally add any references added by users that aren't
- // otherwise rendered.
- addCustomRefs(s.Definitions, p.reg, customRefs)
-
- return &s, nil
-}
-
-func processExtensions(inputExts map[string]*structpb.Value) ([]extension, error) {
- exts := []extension{}
- for k, v := range inputExts {
- if !strings.HasPrefix(k, "x-") {
- return nil, fmt.Errorf("Extension keys need to start with \"x-\": %q", k)
- }
- ext, err := (&jsonpb.Marshaler{Indent: " "}).MarshalToString(v)
- if err != nil {
- return nil, err
- }
- exts = append(exts, extension{key: k, value: json.RawMessage(ext)})
- }
- sort.Slice(exts, func(i, j int) bool { return exts[i].key < exts[j].key })
- return exts, nil
-}
-
-// updateSwaggerDataFromComments updates a Swagger object based on a comment
-// from the proto file.
-//
-// First paragraph of a comment is used for summary. Remaining paragraphs of
-// a comment are used for description. If 'Summary' field is not present on
-// the passed swaggerObject, the summary and description are joined by \n\n.
-//
-// If there is a field named 'Info', its 'Summary' and 'Description' fields
-// will be updated instead.
-//
-// If there is no 'Summary', the same behavior will be attempted on 'Title',
-// but only if the last character is not a period.
-func updateSwaggerDataFromComments(reg *descriptor.Registry, swaggerObject interface{}, data interface{}, comment string, isPackageObject bool) error {
- if len(comment) == 0 {
- return nil
- }
-
- // Checks whether the "use_go_templates" flag is set to true
- if reg.GetUseGoTemplate() {
- comment = goTemplateComments(comment, data, reg)
- }
-
- // Figure out what to apply changes to.
- swaggerObjectValue := reflect.ValueOf(swaggerObject)
- infoObjectValue := swaggerObjectValue.Elem().FieldByName("Info")
- if !infoObjectValue.CanSet() {
- // No such field? Apply summary and description directly to
- // passed object.
- infoObjectValue = swaggerObjectValue.Elem()
- }
-
- // Figure out which properties to update.
- summaryValue := infoObjectValue.FieldByName("Summary")
- descriptionValue := infoObjectValue.FieldByName("Description")
- readOnlyValue := infoObjectValue.FieldByName("ReadOnly")
-
- if readOnlyValue.Kind() == reflect.Bool && readOnlyValue.CanSet() && strings.Contains(comment, "Output only.") {
- readOnlyValue.Set(reflect.ValueOf(true))
- }
-
- usingTitle := false
- if !summaryValue.CanSet() {
- summaryValue = infoObjectValue.FieldByName("Title")
- usingTitle = true
- }
-
- paragraphs := strings.Split(comment, "\n\n")
-
- // If there is a summary (or summary-equivalent) and it's empty, use the first
- // paragraph as summary, and the rest as description.
- if summaryValue.CanSet() {
- summary := strings.TrimSpace(paragraphs[0])
- description := strings.TrimSpace(strings.Join(paragraphs[1:], "\n\n"))
- if !usingTitle || (len(summary) > 0 && summary[len(summary)-1] != '.') {
- // overrides the schema value only if it's empty
- // keep the comment precedence when updating the package definition
- if summaryValue.Len() == 0 || isPackageObject {
- summaryValue.Set(reflect.ValueOf(summary))
- }
- if len(description) > 0 {
- if !descriptionValue.CanSet() {
- return fmt.Errorf("Encountered object type with a summary, but no description")
- }
- // overrides the schema value only if it's empty
- // keep the comment precedence when updating the package definition
- if descriptionValue.Len() == 0 || isPackageObject {
- descriptionValue.Set(reflect.ValueOf(description))
- }
- }
- return nil
- }
- }
-
- // There was no summary field on the swaggerObject. Try to apply the
- // whole comment into description if the swagger object description is empty.
- if descriptionValue.CanSet() {
- if descriptionValue.Len() == 0 || isPackageObject {
- descriptionValue.Set(reflect.ValueOf(strings.Join(paragraphs, "\n\n")))
- }
- return nil
- }
-
- return fmt.Errorf("no description nor summary property")
-}
-
-func fieldProtoComments(reg *descriptor.Registry, msg *descriptor.Message, field *descriptor.Field) string {
- protoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil)), "Field")
- for i, f := range msg.Fields {
- if f == field {
- return protoComments(reg, msg.File, msg.Outers, "MessageType", int32(msg.Index), protoPath, int32(i))
- }
- }
- return ""
-}
-
-func enumValueProtoComments(reg *descriptor.Registry, enum *descriptor.Enum) string {
- protoPath := protoPathIndex(reflect.TypeOf((*pbdescriptor.EnumDescriptorProto)(nil)), "Value")
- var comments []string
- for idx, value := range enum.GetValue() {
- name := value.GetName()
- str := protoComments(reg, enum.File, enum.Outers, "EnumType", int32(enum.Index), protoPath, int32(idx))
- if str != "" {
- comments = append(comments, name+": "+str)
- }
- }
- if len(comments) > 0 {
- return "- " + strings.Join(comments, "\n - ")
- }
- return ""
-}
-
-func protoComments(reg *descriptor.Registry, file *descriptor.File, outers []string, typeName string, typeIndex int32, fieldPaths ...int32) string {
- if file.SourceCodeInfo == nil {
- fmt.Fprintln(os.Stderr, "descriptor.File should not contain nil SourceCodeInfo")
- return ""
- }
-
- outerPaths := make([]int32, len(outers))
- for i := range outers {
- location := ""
- if file.Package != nil {
- location = file.GetPackage()
- }
-
- msg, err := reg.LookupMsg(location, strings.Join(outers[:i+1], "."))
- if err != nil {
- panic(err)
- }
- outerPaths[i] = int32(msg.Index)
- }
-
- for _, loc := range file.SourceCodeInfo.Location {
- if !isProtoPathMatches(loc.Path, outerPaths, typeName, typeIndex, fieldPaths) {
- continue
- }
- comments := ""
- if loc.LeadingComments != nil {
- comments = strings.TrimRight(*loc.LeadingComments, "\n")
- comments = strings.TrimSpace(comments)
- // TODO(ivucica): this is a hack to fix "// " being interpreted as "//".
- // perhaps we should:
- // - split by \n
- // - determine if every (but first and last) line begins with " "
- // - trim every line only if that is the case
- // - join by \n
- comments = strings.Replace(comments, "\n ", "\n", -1)
- }
- return comments
- }
- return ""
-}
-
-func goTemplateComments(comment string, data interface{}, reg *descriptor.Registry) string {
- var temp bytes.Buffer
- tpl, err := template.New("").Funcs(template.FuncMap{
- // Allows importing documentation from a file
- "import": func(name string) string {
- file, err := ioutil.ReadFile(name)
- if err != nil {
- return err.Error()
- }
- // Runs template over imported file
- return goTemplateComments(string(file), data, reg)
- },
- // Grabs title and description from a field
- "fieldcomments": func(msg *descriptor.Message, field *descriptor.Field) string {
- return strings.Replace(fieldProtoComments(reg, msg, field), "\n", "<br>", -1)
- },
- }).Parse(comment)
- if err != nil {
- // If there is an error parsing the templating insert the error as string in the comment
- // to make it easier to debug the template error
- return err.Error()
- }
- err = tpl.Execute(&temp, data)
- if err != nil {
- // If there is an error executing the templating insert the error as string in the comment
- // to make it easier to debug the error
- return err.Error()
- }
- return temp.String()
-}
-
-var messageProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "MessageType")
-var nestedProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil)), "NestedType")
-var packageProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Package")
-var serviceProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil)), "Service")
-var methodProtoPath = protoPathIndex(reflect.TypeOf((*pbdescriptor.ServiceDescriptorProto)(nil)), "Method")
-
-func isProtoPathMatches(paths []int32, outerPaths []int32, typeName string, typeIndex int32, fieldPaths []int32) bool {
- if typeName == "Package" && typeIndex == packageProtoPath {
- // path for package comments is just [2], and all the other processing
- // is too complex for it.
- if len(paths) == 0 || typeIndex != paths[0] {
- return false
- }
- return true
- }
-
- if len(paths) != len(outerPaths)*2+2+len(fieldPaths) {
- return false
- }
-
- if typeName == "Method" {
- if paths[0] != serviceProtoPath || paths[2] != methodProtoPath {
- return false
- }
- paths = paths[2:]
- } else {
- typeNameDescriptor := reflect.TypeOf((*pbdescriptor.FileDescriptorProto)(nil))
-
- if len(outerPaths) > 0 {
- if paths[0] != messageProtoPath || paths[1] != outerPaths[0] {
- return false
- }
- paths = paths[2:]
- outerPaths = outerPaths[1:]
-
- for i, v := range outerPaths {
- if paths[i*2] != nestedProtoPath || paths[i*2+1] != v {
- return false
- }
- }
- paths = paths[len(outerPaths)*2:]
-
- if typeName == "MessageType" {
- typeName = "NestedType"
- }
- typeNameDescriptor = reflect.TypeOf((*pbdescriptor.DescriptorProto)(nil))
- }
-
- if paths[0] != protoPathIndex(typeNameDescriptor, typeName) || paths[1] != typeIndex {
- return false
- }
- paths = paths[2:]
- }
-
- for i, v := range fieldPaths {
- if paths[i] != v {
- return false
- }
- }
- return true
-}
-
-// protoPathIndex returns a path component for google.protobuf.descriptor.SourceCode_Location.
-//
-// Specifically, it returns an id as generated from descriptor proto which
-// can be used to determine what type the id following it in the path is.
-// For example, if we are trying to locate comments related to a field named
-// `Address` in a message named `Person`, the path will be:
-//
-// [4, a, 2, b]
-//
-// While `a` gets determined by the order in which the messages appear in
-// the proto file, and `b` is the field index specified in the proto
-// file itself, the path actually needs to specify that `a` refers to a
-// message and not, say, a service; and that `b` refers to a field and not
-// an option.
-//
-// protoPathIndex figures out the values 4 and 2 in the above example. Because
-// messages are top level objects, the value of 4 comes from field id for
-// `MessageType` inside `google.protobuf.descriptor.FileDescriptor` message.
-// This field has a message type `google.protobuf.descriptor.DescriptorProto`.
-// And inside message `DescriptorProto`, there is a field named `Field` with id
-// 2.
-//
-// Some code generators seem to be hardcoding these values; this method instead
-// interprets them from `descriptor.proto`-derived Go source as necessary.
-func protoPathIndex(descriptorType reflect.Type, what string) int32 {
- field, ok := descriptorType.Elem().FieldByName(what)
- if !ok {
- panic(fmt.Errorf("could not find protobuf descriptor type id for %s", what))
- }
- pbtag := field.Tag.Get("protobuf")
- if pbtag == "" {
- panic(fmt.Errorf("no Go tag 'protobuf' on protobuf descriptor for %s", what))
- }
- path, err := strconv.Atoi(strings.Split(pbtag, ",")[1])
- if err != nil {
- panic(fmt.Errorf("protobuf descriptor id for %s cannot be converted to a number: %s", what, err.Error()))
- }
-
- return int32(path)
-}
-
-// extractOperationOptionFromMethodDescriptor extracts the message of type
-// swagger_options.Operation from a given proto method's descriptor.
-func extractOperationOptionFromMethodDescriptor(meth *pbdescriptor.MethodDescriptorProto) (*swagger_options.Operation, error) {
- if meth.Options == nil {
- return nil, nil
- }
- if !proto.HasExtension(meth.Options, swagger_options.E_Openapiv2Operation) {
- return nil, nil
- }
- ext, err := proto.GetExtension(meth.Options, swagger_options.E_Openapiv2Operation)
- if err != nil {
- return nil, err
- }
- opts, ok := ext.(*swagger_options.Operation)
- if !ok {
- return nil, fmt.Errorf("extension is %T; want an Operation", ext)
- }
- return opts, nil
-}
-
-// extractSchemaOptionFromMessageDescriptor extracts the message of type
-// swagger_options.Schema from a given proto message's descriptor.
-func extractSchemaOptionFromMessageDescriptor(msg *pbdescriptor.DescriptorProto) (*swagger_options.Schema, error) {
- if msg.Options == nil {
- return nil, nil
- }
- if !proto.HasExtension(msg.Options, swagger_options.E_Openapiv2Schema) {
- return nil, nil
- }
- ext, err := proto.GetExtension(msg.Options, swagger_options.E_Openapiv2Schema)
- if err != nil {
- return nil, err
- }
- opts, ok := ext.(*swagger_options.Schema)
- if !ok {
- return nil, fmt.Errorf("extension is %T; want a Schema", ext)
- }
- return opts, nil
-}
-
-// extractSwaggerOptionFromFileDescriptor extracts the message of type
-// swagger_options.Swagger from a given proto method's descriptor.
-func extractSwaggerOptionFromFileDescriptor(file *pbdescriptor.FileDescriptorProto) (*swagger_options.Swagger, error) {
- if file.Options == nil {
- return nil, nil
- }
- if !proto.HasExtension(file.Options, swagger_options.E_Openapiv2Swagger) {
- return nil, nil
- }
- ext, err := proto.GetExtension(file.Options, swagger_options.E_Openapiv2Swagger)
- if err != nil {
- return nil, err
- }
- opts, ok := ext.(*swagger_options.Swagger)
- if !ok {
- return nil, fmt.Errorf("extension is %T; want a Swagger object", ext)
- }
- return opts, nil
-}
-
-func extractJSONSchemaFromFieldDescriptor(fd *pbdescriptor.FieldDescriptorProto) (*swagger_options.JSONSchema, error) {
- if fd.Options == nil {
- return nil, nil
- }
- if !proto.HasExtension(fd.Options, swagger_options.E_Openapiv2Field) {
- return nil, nil
- }
- ext, err := proto.GetExtension(fd.Options, swagger_options.E_Openapiv2Field)
- if err != nil {
- return nil, err
- }
- opts, ok := ext.(*swagger_options.JSONSchema)
- if !ok {
- return nil, fmt.Errorf("extension is %T; want a JSONSchema object", ext)
- }
- return opts, nil
-}
-
-func protoJSONSchemaToSwaggerSchemaCore(j *swagger_options.JSONSchema, reg *descriptor.Registry, refs refMap) schemaCore {
- ret := schemaCore{}
-
- if j.GetRef() != "" {
- swaggerName := fullyQualifiedNameToSwaggerName(j.GetRef(), reg)
- if swaggerName != "" {
- ret.Ref = "#/definitions/" + swaggerName
- if refs != nil {
- refs[j.GetRef()] = struct{}{}
- }
- } else {
- ret.Ref += j.GetRef()
- }
- } else {
- f, t := protoJSONSchemaTypeToFormat(j.GetType())
- ret.Format = f
- ret.Type = t
- }
-
- return ret
-}
-
-func updateSwaggerObjectFromJSONSchema(s *swaggerSchemaObject, j *swagger_options.JSONSchema, reg *descriptor.Registry, data interface{}) {
- s.Title = j.GetTitle()
- s.Description = j.GetDescription()
- if reg.GetUseGoTemplate() {
- s.Title = goTemplateComments(s.Title, data, reg)
- s.Description = goTemplateComments(s.Description, data, reg)
- }
-
- s.ReadOnly = j.GetReadOnly()
- s.MultipleOf = j.GetMultipleOf()
- s.Maximum = j.GetMaximum()
- s.ExclusiveMaximum = j.GetExclusiveMaximum()
- s.Minimum = j.GetMinimum()
- s.ExclusiveMinimum = j.GetExclusiveMinimum()
- s.MaxLength = j.GetMaxLength()
- s.MinLength = j.GetMinLength()
- s.Pattern = j.GetPattern()
- s.Default = j.GetDefault()
- s.MaxItems = j.GetMaxItems()
- s.MinItems = j.GetMinItems()
- s.UniqueItems = j.GetUniqueItems()
- s.MaxProperties = j.GetMaxProperties()
- s.MinProperties = j.GetMinProperties()
- s.Required = j.GetRequired()
- if overrideType := j.GetType(); len(overrideType) > 0 {
- s.Type = strings.ToLower(overrideType[0].String())
- }
-}
-
-func swaggerSchemaFromProtoSchema(s *swagger_options.Schema, reg *descriptor.Registry, refs refMap, data interface{}) swaggerSchemaObject {
- ret := swaggerSchemaObject{
- ExternalDocs: protoExternalDocumentationToSwaggerExternalDocumentation(s.GetExternalDocs(), reg, data),
- }
-
- ret.schemaCore = protoJSONSchemaToSwaggerSchemaCore(s.GetJsonSchema(), reg, refs)
- updateSwaggerObjectFromJSONSchema(&ret, s.GetJsonSchema(), reg, data)
-
- if s != nil && s.Example != nil {
- ret.Example = json.RawMessage(s.Example.Value)
- }
-
- return ret
-}
-
-func protoJSONSchemaTypeToFormat(in []swagger_options.JSONSchema_JSONSchemaSimpleTypes) (string, string) {
- if len(in) == 0 {
- return "", ""
- }
-
- // Can't support more than 1 type, just return the first element.
- // This is due to an inconsistency in the design of the openapiv2 proto
- // and that used in schemaCore. schemaCore uses the v3 definition of types,
- // which only allows a single string, while the openapiv2 proto uses the OpenAPI v2
- // definition, which defers to the JSON schema definition, which allows a string or an array.
- // Sources:
- // https://swagger.io/specification/#itemsObject
- // https://tools.ietf.org/html/draft-fge-json-schema-validation-00#section-5.5.2
- switch in[0] {
- case swagger_options.JSONSchema_UNKNOWN, swagger_options.JSONSchema_NULL:
- return "", ""
- case swagger_options.JSONSchema_OBJECT:
- return "object", ""
- case swagger_options.JSONSchema_ARRAY:
- return "array", ""
- case swagger_options.JSONSchema_BOOLEAN:
- return "boolean", "boolean"
- case swagger_options.JSONSchema_INTEGER:
- return "integer", "int32"
- case swagger_options.JSONSchema_NUMBER:
- return "number", "double"
- case swagger_options.JSONSchema_STRING:
- // NOTE: in swagger specifition, format should be empty on string type
- return "string", ""
- default:
- // Maybe panic?
- return "", ""
- }
-}
-
-func protoExternalDocumentationToSwaggerExternalDocumentation(in *swagger_options.ExternalDocumentation, reg *descriptor.Registry, data interface{}) *swaggerExternalDocumentationObject {
- if in == nil {
- return nil
- }
-
- if reg.GetUseGoTemplate() {
- in.Description = goTemplateComments(in.Description, data, reg)
- }
-
- return &swaggerExternalDocumentationObject{
- Description: in.Description,
- URL: in.Url,
- }
-}
-
-func addCustomRefs(d swaggerDefinitionsObject, reg *descriptor.Registry, refs refMap) {
- if len(refs) == 0 {
- return
- }
- msgMap := make(messageMap)
- enumMap := make(enumMap)
- for ref := range refs {
- if _, ok := d[fullyQualifiedNameToSwaggerName(ref, reg)]; ok {
- // Skip already existing definitions
- delete(refs, ref)
- continue
- }
- msg, err := reg.LookupMsg("", ref)
- if err == nil {
- msgMap[fullyQualifiedNameToSwaggerName(ref, reg)] = msg
- continue
- }
- enum, err := reg.LookupEnum("", ref)
- if err == nil {
- enumMap[fullyQualifiedNameToSwaggerName(ref, reg)] = enum
- continue
- }
-
- // ?? Should be either enum or msg
- }
- renderMessagesAsDefinition(msgMap, d, reg, refs)
- renderEnumerationsAsDefinition(enumMap, d, reg)
-
- // Run again in case any new refs were added
- addCustomRefs(d, reg, refs)
-}
-
-func lowerCamelCase(fieldName string, fields []*descriptor.Field) string {
- for _, oneField := range fields {
- if oneField.GetName() == fieldName {
- return oneField.GetJsonName()
- }
- }
- parameterString := gogen.CamelCase(fieldName)
- builder := &strings.Builder{}
- builder.WriteString(strings.ToLower(string(parameterString[0])))
- builder.WriteString(parameterString[1:])
- return builder.String()
-}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/types.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/types.go
deleted file mode 100644
index 5765706..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger/types.go
+++ /dev/null
@@ -1,253 +0,0 @@
-package genswagger
-
-import (
- "bytes"
- "encoding/json"
-
- "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
-)
-
-type param struct {
- *descriptor.File
- reg *descriptor.Registry
-}
-
-type binding struct {
- *descriptor.Binding
-}
-
-// http://swagger.io/specification/#infoObject
-type swaggerInfoObject struct {
- Title string `json:"title"`
- Description string `json:"description,omitempty"`
- TermsOfService string `json:"termsOfService,omitempty"`
- Version string `json:"version"`
-
- Contact *swaggerContactObject `json:"contact,omitempty"`
- License *swaggerLicenseObject `json:"license,omitempty"`
-
- extensions []extension
-}
-
-// http://swagger.io/specification/#contactObject
-type swaggerContactObject struct {
- Name string `json:"name,omitempty"`
- URL string `json:"url,omitempty"`
- Email string `json:"email,omitempty"`
-}
-
-// http://swagger.io/specification/#licenseObject
-type swaggerLicenseObject struct {
- Name string `json:"name,omitempty"`
- URL string `json:"url,omitempty"`
-}
-
-// http://swagger.io/specification/#externalDocumentationObject
-type swaggerExternalDocumentationObject struct {
- Description string `json:"description,omitempty"`
- URL string `json:"url,omitempty"`
-}
-
-type extension struct {
- key string
- value json.RawMessage
-}
-
-// http://swagger.io/specification/#swaggerObject
-type swaggerObject struct {
- Swagger string `json:"swagger"`
- Info swaggerInfoObject `json:"info"`
- Host string `json:"host,omitempty"`
- BasePath string `json:"basePath,omitempty"`
- Schemes []string `json:"schemes,omitempty"`
- Consumes []string `json:"consumes"`
- Produces []string `json:"produces"`
- Paths swaggerPathsObject `json:"paths"`
- Definitions swaggerDefinitionsObject `json:"definitions"`
- SecurityDefinitions swaggerSecurityDefinitionsObject `json:"securityDefinitions,omitempty"`
- Security []swaggerSecurityRequirementObject `json:"security,omitempty"`
- ExternalDocs *swaggerExternalDocumentationObject `json:"externalDocs,omitempty"`
-
- extensions []extension
-}
-
-// http://swagger.io/specification/#securityDefinitionsObject
-type swaggerSecurityDefinitionsObject map[string]swaggerSecuritySchemeObject
-
-// http://swagger.io/specification/#securitySchemeObject
-type swaggerSecuritySchemeObject struct {
- Type string `json:"type"`
- Description string `json:"description,omitempty"`
- Name string `json:"name,omitempty"`
- In string `json:"in,omitempty"`
- Flow string `json:"flow,omitempty"`
- AuthorizationURL string `json:"authorizationUrl,omitempty"`
- TokenURL string `json:"tokenUrl,omitempty"`
- Scopes swaggerScopesObject `json:"scopes,omitempty"`
-
- extensions []extension
-}
-
-// http://swagger.io/specification/#scopesObject
-type swaggerScopesObject map[string]string
-
-// http://swagger.io/specification/#securityRequirementObject
-type swaggerSecurityRequirementObject map[string][]string
-
-// http://swagger.io/specification/#pathsObject
-type swaggerPathsObject map[string]swaggerPathItemObject
-
-// http://swagger.io/specification/#pathItemObject
-type swaggerPathItemObject struct {
- Get *swaggerOperationObject `json:"get,omitempty"`
- Delete *swaggerOperationObject `json:"delete,omitempty"`
- Post *swaggerOperationObject `json:"post,omitempty"`
- Put *swaggerOperationObject `json:"put,omitempty"`
- Patch *swaggerOperationObject `json:"patch,omitempty"`
-}
-
-// http://swagger.io/specification/#operationObject
-type swaggerOperationObject struct {
- Summary string `json:"summary,omitempty"`
- Description string `json:"description,omitempty"`
- OperationID string `json:"operationId"`
- Responses swaggerResponsesObject `json:"responses"`
- Parameters swaggerParametersObject `json:"parameters,omitempty"`
- Tags []string `json:"tags,omitempty"`
- Deprecated bool `json:"deprecated,omitempty"`
-
- Security *[]swaggerSecurityRequirementObject `json:"security,omitempty"`
- ExternalDocs *swaggerExternalDocumentationObject `json:"externalDocs,omitempty"`
-
- extensions []extension
-}
-
-type swaggerParametersObject []swaggerParameterObject
-
-// http://swagger.io/specification/#parameterObject
-type swaggerParameterObject struct {
- Name string `json:"name"`
- Description string `json:"description,omitempty"`
- In string `json:"in,omitempty"`
- Required bool `json:"required"`
- Type string `json:"type,omitempty"`
- Format string `json:"format,omitempty"`
- Items *swaggerItemsObject `json:"items,omitempty"`
- Enum []string `json:"enum,omitempty"`
- CollectionFormat string `json:"collectionFormat,omitempty"`
- Default string `json:"default,omitempty"`
- MinItems *int `json:"minItems,omitempty"`
-
- // Or you can explicitly refer to another type. If this is defined all
- // other fields should be empty
- Schema *swaggerSchemaObject `json:"schema,omitempty"`
-}
-
-// core part of schema, which is common to itemsObject and schemaObject.
-// http://swagger.io/specification/#itemsObject
-type schemaCore struct {
- Type string `json:"type,omitempty"`
- Format string `json:"format,omitempty"`
- Ref string `json:"$ref,omitempty"`
- Example json.RawMessage `json:"example,omitempty"`
-
- Items *swaggerItemsObject `json:"items,omitempty"`
-
- // If the item is an enumeration include a list of all the *NAMES* of the
- // enum values. I'm not sure how well this will work but assuming all enums
- // start from 0 index it will be great. I don't think that is a good assumption.
- Enum []string `json:"enum,omitempty"`
- Default string `json:"default,omitempty"`
-}
-
-type swaggerItemsObject schemaCore
-
-// http://swagger.io/specification/#responsesObject
-type swaggerResponsesObject map[string]swaggerResponseObject
-
-// http://swagger.io/specification/#responseObject
-type swaggerResponseObject struct {
- Description string `json:"description"`
- Schema swaggerSchemaObject `json:"schema"`
-
- extensions []extension
-}
-
-type keyVal struct {
- Key string
- Value interface{}
-}
-
-type swaggerSchemaObjectProperties []keyVal
-
-func (op swaggerSchemaObjectProperties) MarshalJSON() ([]byte, error) {
- var buf bytes.Buffer
- buf.WriteString("{")
- for i, kv := range op {
- if i != 0 {
- buf.WriteString(",")
- }
- key, err := json.Marshal(kv.Key)
- if err != nil {
- return nil, err
- }
- buf.Write(key)
- buf.WriteString(":")
- val, err := json.Marshal(kv.Value)
- if err != nil {
- return nil, err
- }
- buf.Write(val)
- }
-
- buf.WriteString("}")
- return buf.Bytes(), nil
-}
-
-// http://swagger.io/specification/#schemaObject
-type swaggerSchemaObject struct {
- schemaCore
- // Properties can be recursively defined
- Properties *swaggerSchemaObjectProperties `json:"properties,omitempty"`
- AdditionalProperties *swaggerSchemaObject `json:"additionalProperties,omitempty"`
-
- Description string `json:"description,omitempty"`
- Title string `json:"title,omitempty"`
-
- ExternalDocs *swaggerExternalDocumentationObject `json:"externalDocs,omitempty"`
-
- ReadOnly bool `json:"readOnly,omitempty"`
- MultipleOf float64 `json:"multipleOf,omitempty"`
- Maximum float64 `json:"maximum,omitempty"`
- ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"`
- Minimum float64 `json:"minimum,omitempty"`
- ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"`
- MaxLength uint64 `json:"maxLength,omitempty"`
- MinLength uint64 `json:"minLength,omitempty"`
- Pattern string `json:"pattern,omitempty"`
- MaxItems uint64 `json:"maxItems,omitempty"`
- MinItems uint64 `json:"minItems,omitempty"`
- UniqueItems bool `json:"uniqueItems,omitempty"`
- MaxProperties uint64 `json:"maxProperties,omitempty"`
- MinProperties uint64 `json:"minProperties,omitempty"`
- Required []string `json:"required,omitempty"`
-}
-
-// http://swagger.io/specification/#referenceObject
-type swaggerReferenceObject struct {
- Ref string `json:"$ref"`
-}
-
-// http://swagger.io/specification/#definitionsObject
-type swaggerDefinitionsObject map[string]swaggerSchemaObject
-
-// Internal type mapping from FQMN to descriptor.Message. Used as a set by the
-// findServiceMessages function.
-type messageMap map[string]*descriptor.Message
-
-// Internal type mapping from FQEN to descriptor.Enum. Used as a set by the
-// findServiceMessages function.
-type enumMap map[string]*descriptor.Enum
-
-// Internal type to store used references.
-type refMap map[string]struct{}
diff --git a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/main.go b/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/main.go
deleted file mode 100644
index 9befc25..0000000
--- a/vendor/github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/main.go
+++ /dev/null
@@ -1,200 +0,0 @@
-package main
-
-import (
- "flag"
- "fmt"
- "os"
- "strings"
-
- "github.com/golang/glog"
- "github.com/golang/protobuf/proto"
- plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
- "github.com/grpc-ecosystem/grpc-gateway/codegenerator"
- "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor"
- "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger"
-)
-
-var (
- importPrefix = flag.String("import_prefix", "", "prefix to be added to go package paths for imported proto files")
- file = flag.String("file", "-", "where to load data from")
- allowDeleteBody = flag.Bool("allow_delete_body", false, "unless set, HTTP DELETE methods may not have a body")
- grpcAPIConfiguration = flag.String("grpc_api_configuration", "", "path to gRPC API Configuration in YAML format")
- allowMerge = flag.Bool("allow_merge", false, "if set, generation one swagger file out of multiple protos")
- mergeFileName = flag.String("merge_file_name", "apidocs", "target swagger file name prefix after merge")
- useJSONNamesForFields = flag.Bool("json_names_for_fields", false, "if it sets Field.GetJsonName() will be used for generating swagger definitions, otherwise Field.GetName() will be used")
- repeatedPathParamSeparator = flag.String("repeated_path_param_separator", "csv", "configures how repeated fields should be split. Allowed values are `csv`, `pipes`, `ssv` and `tsv`.")
- versionFlag = flag.Bool("version", false, "print the current verison")
- allowRepeatedFieldsInBody = flag.Bool("allow_repeated_fields_in_body", false, "allows to use repeated field in `body` and `response_body` field of `google.api.http` annotation option")
- includePackageInTags = flag.Bool("include_package_in_tags", false, "if unset, the gRPC service name is added to the `Tags` field of each operation. if set and the `package` directive is shown in the proto file, the package name will be prepended to the service name")
- useFQNForSwaggerName = flag.Bool("fqn_for_swagger_name", false, "if set, the object's swagger names will use the fully qualify name from the proto definition (ie my.package.MyMessage.MyInnerMessage")
- useGoTemplate = flag.Bool("use_go_templates", false, "if set, you can use Go templates in protofile comments")
-)
-
-// Variables set by goreleaser at build time
-var (
- version = "dev"
- commit = "unknown"
- date = "unknown"
-)
-
-func main() {
- flag.Parse()
- defer glog.Flush()
-
- if *versionFlag {
- fmt.Printf("Version %v, commit %v, built at %v\n", version, commit, date)
- os.Exit(0)
- }
-
- reg := descriptor.NewRegistry()
-
- glog.V(1).Info("Processing code generator request")
- f := os.Stdin
- if *file != "-" {
- var err error
- f, err = os.Open(*file)
- if err != nil {
- glog.Fatal(err)
- }
- }
- glog.V(1).Info("Parsing code generator request")
- req, err := codegenerator.ParseRequest(f)
- if err != nil {
- glog.Fatal(err)
- }
- glog.V(1).Info("Parsed code generator request")
- pkgMap := make(map[string]string)
- if req.Parameter != nil {
- err := parseReqParam(req.GetParameter(), flag.CommandLine, pkgMap)
- if err != nil {
- glog.Fatalf("Error parsing flags: %v", err)
- }
- }
-
- reg.SetPrefix(*importPrefix)
- reg.SetAllowDeleteBody(*allowDeleteBody)
- reg.SetAllowMerge(*allowMerge)
- reg.SetMergeFileName(*mergeFileName)
- reg.SetUseJSONNamesForFields(*useJSONNamesForFields)
- reg.SetAllowRepeatedFieldsInBody(*allowRepeatedFieldsInBody)
- reg.SetIncludePackageInTags(*includePackageInTags)
- reg.SetUseFQNForSwaggerName(*useFQNForSwaggerName)
- reg.SetUseGoTemplate(*useGoTemplate)
- if err := reg.SetRepeatedPathParamSeparator(*repeatedPathParamSeparator); err != nil {
- emitError(err)
- return
- }
- for k, v := range pkgMap {
- reg.AddPkgMap(k, v)
- }
-
- if *grpcAPIConfiguration != "" {
- if err := reg.LoadGrpcAPIServiceFromYAML(*grpcAPIConfiguration); err != nil {
- emitError(err)
- return
- }
- }
-
- g := genswagger.New(reg)
-
- if err := genswagger.AddStreamError(reg); err != nil {
- emitError(err)
- return
- }
-
- if err := reg.Load(req); err != nil {
- emitError(err)
- return
- }
-
- var targets []*descriptor.File
- for _, target := range req.FileToGenerate {
- f, err := reg.LookupFile(target)
- if err != nil {
- glog.Fatal(err)
- }
- targets = append(targets, f)
- }
-
- out, err := g.Generate(targets)
- glog.V(1).Info("Processed code generator request")
- if err != nil {
- emitError(err)
- return
- }
- emitFiles(out)
-}
-
-func emitFiles(out []*plugin.CodeGeneratorResponse_File) {
- emitResp(&plugin.CodeGeneratorResponse{File: out})
-}
-
-func emitError(err error) {
- emitResp(&plugin.CodeGeneratorResponse{Error: proto.String(err.Error())})
-}
-
-func emitResp(resp *plugin.CodeGeneratorResponse) {
- buf, err := proto.Marshal(resp)
- if err != nil {
- glog.Fatal(err)
- }
- if _, err := os.Stdout.Write(buf); err != nil {
- glog.Fatal(err)
- }
-}
-
-// parseReqParam parses a CodeGeneratorRequest parameter and adds the
-// extracted values to the given FlagSet and pkgMap. Returns a non-nil
-// error if setting a flag failed.
-func parseReqParam(param string, f *flag.FlagSet, pkgMap map[string]string) error {
- if param == "" {
- return nil
- }
- for _, p := range strings.Split(param, ",") {
- spec := strings.SplitN(p, "=", 2)
- if len(spec) == 1 {
- if spec[0] == "allow_delete_body" {
- err := f.Set(spec[0], "true")
- if err != nil {
- return fmt.Errorf("Cannot set flag %s: %v", p, err)
- }
- continue
- }
- if spec[0] == "allow_merge" {
- err := f.Set(spec[0], "true")
- if err != nil {
- return fmt.Errorf("Cannot set flag %s: %v", p, err)
- }
- continue
- }
- if spec[0] == "allow_repeated_fields_in_body" {
- err := f.Set(spec[0], "true")
- if err != nil {
- return fmt.Errorf("Cannot set flag %s: %v", p, err)
- }
- continue
- }
- if spec[0] == "include_package_in_tags" {
- err := f.Set(spec[0], "true")
- if err != nil {
- return fmt.Errorf("Cannot set flag %s: %v", p, err)
- }
- continue
- }
- err := f.Set(spec[0], "")
- if err != nil {
- return fmt.Errorf("Cannot set flag %s: %v", p, err)
- }
- continue
- }
- name, value := spec[0], spec[1]
- if strings.HasPrefix(name, "M") {
- pkgMap[name[1:]] = value
- continue
- }
- if err := f.Set(name, value); err != nil {
- return fmt.Errorf("Cannot set flag %s: %v", p, err)
- }
- }
- return nil
-}
diff --git a/vendor/golang.org/x/sys/unix/mkasm_darwin.go b/vendor/golang.org/x/sys/unix/mkasm_darwin.go
deleted file mode 100644
index 4548b99..0000000
--- a/vendor/golang.org/x/sys/unix/mkasm_darwin.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-// mkasm_darwin.go generates assembly trampolines to call libSystem routines from Go.
-//This program must be run after mksyscall.go.
-package main
-
-import (
- "bytes"
- "fmt"
- "io/ioutil"
- "log"
- "os"
- "strings"
-)
-
-func main() {
- in1, err := ioutil.ReadFile("syscall_darwin.go")
- if err != nil {
- log.Fatalf("can't open syscall_darwin.go: %s", err)
- }
- arch := os.Args[1]
- in2, err := ioutil.ReadFile(fmt.Sprintf("syscall_darwin_%s.go", arch))
- if err != nil {
- log.Fatalf("can't open syscall_darwin_%s.go: %s", arch, err)
- }
- in3, err := ioutil.ReadFile(fmt.Sprintf("zsyscall_darwin_%s.go", arch))
- if err != nil {
- log.Fatalf("can't open zsyscall_darwin_%s.go: %s", arch, err)
- }
- in := string(in1) + string(in2) + string(in3)
-
- trampolines := map[string]bool{}
-
- var out bytes.Buffer
-
- fmt.Fprintf(&out, "// go run mkasm_darwin.go %s\n", strings.Join(os.Args[1:], " "))
- fmt.Fprintf(&out, "// Code generated by the command above; DO NOT EDIT.\n")
- fmt.Fprintf(&out, "\n")
- fmt.Fprintf(&out, "// +build go1.12\n")
- fmt.Fprintf(&out, "\n")
- fmt.Fprintf(&out, "#include \"textflag.h\"\n")
- for _, line := range strings.Split(in, "\n") {
- if !strings.HasPrefix(line, "func ") || !strings.HasSuffix(line, "_trampoline()") {
- continue
- }
- fn := line[5 : len(line)-13]
- if !trampolines[fn] {
- trampolines[fn] = true
- fmt.Fprintf(&out, "TEXT ·%s_trampoline(SB),NOSPLIT,$0-0\n", fn)
- fmt.Fprintf(&out, "\tJMP\t%s(SB)\n", fn)
- }
- }
- err = ioutil.WriteFile(fmt.Sprintf("zsyscall_darwin_%s.s", arch), out.Bytes(), 0644)
- if err != nil {
- log.Fatalf("can't write zsyscall_darwin_%s.s: %s", arch, err)
- }
-}
diff --git a/vendor/golang.org/x/sys/unix/mkpost.go b/vendor/golang.org/x/sys/unix/mkpost.go
deleted file mode 100644
index 9feddd0..0000000
--- a/vendor/golang.org/x/sys/unix/mkpost.go
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright 2016 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-// mkpost processes the output of cgo -godefs to
-// modify the generated types. It is used to clean up
-// the sys API in an architecture specific manner.
-//
-// mkpost is run after cgo -godefs; see README.md.
-package main
-
-import (
- "bytes"
- "fmt"
- "go/format"
- "io/ioutil"
- "log"
- "os"
- "regexp"
-)
-
-func main() {
- // Get the OS and architecture (using GOARCH_TARGET if it exists)
- goos := os.Getenv("GOOS")
- goarch := os.Getenv("GOARCH_TARGET")
- if goarch == "" {
- goarch = os.Getenv("GOARCH")
- }
- // Check that we are using the Docker-based build system if we should be.
- if goos == "linux" {
- if os.Getenv("GOLANG_SYS_BUILD") != "docker" {
- os.Stderr.WriteString("In the Docker-based build system, mkpost should not be called directly.\n")
- os.Stderr.WriteString("See README.md\n")
- os.Exit(1)
- }
- }
-
- b, err := ioutil.ReadAll(os.Stdin)
- if err != nil {
- log.Fatal(err)
- }
-
- // Intentionally export __val fields in Fsid and Sigset_t
- valRegex := regexp.MustCompile(`type (Fsid|Sigset_t) struct {(\s+)X__val(\s+\S+\s+)}`)
- b = valRegex.ReplaceAll(b, []byte("type $1 struct {${2}Val$3}"))
-
- // Intentionally export __fds_bits field in FdSet
- fdSetRegex := regexp.MustCompile(`type (FdSet) struct {(\s+)X__fds_bits(\s+\S+\s+)}`)
- b = fdSetRegex.ReplaceAll(b, []byte("type $1 struct {${2}Bits$3}"))
-
- // If we have empty Ptrace structs, we should delete them. Only s390x emits
- // nonempty Ptrace structs.
- ptraceRexexp := regexp.MustCompile(`type Ptrace((Psw|Fpregs|Per) struct {\s*})`)
- b = ptraceRexexp.ReplaceAll(b, nil)
-
- // Replace the control_regs union with a blank identifier for now.
- controlRegsRegex := regexp.MustCompile(`(Control_regs)\s+\[0\]uint64`)
- b = controlRegsRegex.ReplaceAll(b, []byte("_ [0]uint64"))
-
- // Remove fields that are added by glibc
- // Note that this is unstable as the identifers are private.
- removeFieldsRegex := regexp.MustCompile(`X__glibc\S*`)
- b = removeFieldsRegex.ReplaceAll(b, []byte("_"))
-
- // Convert [65]int8 to [65]byte in Utsname members to simplify
- // conversion to string; see golang.org/issue/20753
- convertUtsnameRegex := regexp.MustCompile(`((Sys|Node|Domain)name|Release|Version|Machine)(\s+)\[(\d+)\]u?int8`)
- b = convertUtsnameRegex.ReplaceAll(b, []byte("$1$3[$4]byte"))
-
- // Convert [1024]int8 to [1024]byte in Ptmget members
- convertPtmget := regexp.MustCompile(`([SC]n)(\s+)\[(\d+)\]u?int8`)
- b = convertPtmget.ReplaceAll(b, []byte("$1[$3]byte"))
-
- // Remove spare fields (e.g. in Statx_t)
- spareFieldsRegex := regexp.MustCompile(`X__spare\S*`)
- b = spareFieldsRegex.ReplaceAll(b, []byte("_"))
-
- // Remove cgo padding fields
- removePaddingFieldsRegex := regexp.MustCompile(`Pad_cgo_\d+`)
- b = removePaddingFieldsRegex.ReplaceAll(b, []byte("_"))
-
- // Remove padding, hidden, or unused fields
- removeFieldsRegex = regexp.MustCompile(`\b(X_\S+|Padding)`)
- b = removeFieldsRegex.ReplaceAll(b, []byte("_"))
-
- // Remove the first line of warning from cgo
- b = b[bytes.IndexByte(b, '\n')+1:]
- // Modify the command in the header to include:
- // mkpost, our own warning, and a build tag.
- replacement := fmt.Sprintf(`$1 | go run mkpost.go
-// Code generated by the command above; see README.md. DO NOT EDIT.
-
-// +build %s,%s`, goarch, goos)
- cgoCommandRegex := regexp.MustCompile(`(cgo -godefs .*)`)
- b = cgoCommandRegex.ReplaceAll(b, []byte(replacement))
-
- // gofmt
- b, err = format.Source(b)
- if err != nil {
- log.Fatal(err)
- }
-
- os.Stdout.Write(b)
-}
diff --git a/vendor/golang.org/x/sys/unix/mksyscall.go b/vendor/golang.org/x/sys/unix/mksyscall.go
deleted file mode 100644
index e4af942..0000000
--- a/vendor/golang.org/x/sys/unix/mksyscall.go
+++ /dev/null
@@ -1,407 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-/*
-This program reads a file containing function prototypes
-(like syscall_darwin.go) and generates system call bodies.
-The prototypes are marked by lines beginning with "//sys"
-and read like func declarations if //sys is replaced by func, but:
- * The parameter lists must give a name for each argument.
- This includes return parameters.
- * The parameter lists must give a type for each argument:
- the (x, y, z int) shorthand is not allowed.
- * If the return parameter is an error number, it must be named errno.
-
-A line beginning with //sysnb is like //sys, except that the
-goroutine will not be suspended during the execution of the system
-call. This must only be used for system calls which can never
-block, as otherwise the system call could cause all goroutines to
-hang.
-*/
-package main
-
-import (
- "bufio"
- "flag"
- "fmt"
- "os"
- "regexp"
- "strings"
-)
-
-var (
- b32 = flag.Bool("b32", false, "32bit big-endian")
- l32 = flag.Bool("l32", false, "32bit little-endian")
- plan9 = flag.Bool("plan9", false, "plan9")
- openbsd = flag.Bool("openbsd", false, "openbsd")
- netbsd = flag.Bool("netbsd", false, "netbsd")
- dragonfly = flag.Bool("dragonfly", false, "dragonfly")
- arm = flag.Bool("arm", false, "arm") // 64-bit value should use (even, odd)-pair
- tags = flag.String("tags", "", "build tags")
- filename = flag.String("output", "", "output file name (standard output if omitted)")
-)
-
-// cmdLine returns this programs's commandline arguments
-func cmdLine() string {
- return "go run mksyscall.go " + strings.Join(os.Args[1:], " ")
-}
-
-// buildTags returns build tags
-func buildTags() string {
- return *tags
-}
-
-// Param is function parameter
-type Param struct {
- Name string
- Type string
-}
-
-// usage prints the program usage
-func usage() {
- fmt.Fprintf(os.Stderr, "usage: go run mksyscall.go [-b32 | -l32] [-tags x,y] [file ...]\n")
- os.Exit(1)
-}
-
-// parseParamList parses parameter list and returns a slice of parameters
-func parseParamList(list string) []string {
- list = strings.TrimSpace(list)
- if list == "" {
- return []string{}
- }
- return regexp.MustCompile(`\s*,\s*`).Split(list, -1)
-}
-
-// parseParam splits a parameter into name and type
-func parseParam(p string) Param {
- ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p)
- if ps == nil {
- fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p)
- os.Exit(1)
- }
- return Param{ps[1], ps[2]}
-}
-
-func main() {
- // Get the OS and architecture (using GOARCH_TARGET if it exists)
- goos := os.Getenv("GOOS")
- if goos == "" {
- fmt.Fprintln(os.Stderr, "GOOS not defined in environment")
- os.Exit(1)
- }
- goarch := os.Getenv("GOARCH_TARGET")
- if goarch == "" {
- goarch = os.Getenv("GOARCH")
- }
-
- // Check that we are using the Docker-based build system if we should
- if goos == "linux" {
- if os.Getenv("GOLANG_SYS_BUILD") != "docker" {
- fmt.Fprintf(os.Stderr, "In the Docker-based build system, mksyscall should not be called directly.\n")
- fmt.Fprintf(os.Stderr, "See README.md\n")
- os.Exit(1)
- }
- }
-
- flag.Usage = usage
- flag.Parse()
- if len(flag.Args()) <= 0 {
- fmt.Fprintf(os.Stderr, "no files to parse provided\n")
- usage()
- }
-
- endianness := ""
- if *b32 {
- endianness = "big-endian"
- } else if *l32 {
- endianness = "little-endian"
- }
-
- libc := false
- if goos == "darwin" && strings.Contains(buildTags(), ",go1.12") {
- libc = true
- }
- trampolines := map[string]bool{}
-
- text := ""
- for _, path := range flag.Args() {
- file, err := os.Open(path)
- if err != nil {
- fmt.Fprintf(os.Stderr, err.Error())
- os.Exit(1)
- }
- s := bufio.NewScanner(file)
- for s.Scan() {
- t := s.Text()
- t = strings.TrimSpace(t)
- t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `)
- nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t)
- if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil {
- continue
- }
-
- // Line must be of the form
- // func Open(path string, mode int, perm int) (fd int, errno error)
- // Split into name, in params, out params.
- f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*((?i)SYS_[A-Z0-9_]+))?$`).FindStringSubmatch(t)
- if f == nil {
- fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t)
- os.Exit(1)
- }
- funct, inps, outps, sysname := f[2], f[3], f[4], f[5]
-
- // ClockGettime doesn't have a syscall number on Darwin, only generate libc wrappers.
- if goos == "darwin" && !libc && funct == "ClockGettime" {
- continue
- }
-
- // Split argument lists on comma.
- in := parseParamList(inps)
- out := parseParamList(outps)
-
- // Try in vain to keep people from editing this file.
- // The theory is that they jump into the middle of the file
- // without reading the header.
- text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"
-
- // Go function header.
- outDecl := ""
- if len(out) > 0 {
- outDecl = fmt.Sprintf(" (%s)", strings.Join(out, ", "))
- }
- text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outDecl)
-
- // Check if err return available
- errvar := ""
- for _, param := range out {
- p := parseParam(param)
- if p.Type == "error" {
- errvar = p.Name
- break
- }
- }
-
- // Prepare arguments to Syscall.
- var args []string
- n := 0
- for _, param := range in {
- p := parseParam(param)
- if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil {
- args = append(args, "uintptr(unsafe.Pointer("+p.Name+"))")
- } else if p.Type == "string" && errvar != "" {
- text += fmt.Sprintf("\tvar _p%d *byte\n", n)
- text += fmt.Sprintf("\t_p%d, %s = BytePtrFromString(%s)\n", n, errvar, p.Name)
- text += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar)
- args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
- n++
- } else if p.Type == "string" {
- fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n")
- text += fmt.Sprintf("\tvar _p%d *byte\n", n)
- text += fmt.Sprintf("\t_p%d, _ = BytePtrFromString(%s)\n", n, p.Name)
- args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
- n++
- } else if regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type) != nil {
- // Convert slice into pointer, length.
- // Have to be careful not to take address of &a[0] if len == 0:
- // pass dummy pointer in that case.
- // Used to pass nil, but some OSes or simulators reject write(fd, nil, 0).
- text += fmt.Sprintf("\tvar _p%d unsafe.Pointer\n", n)
- text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = unsafe.Pointer(&%s[0])\n\t}", p.Name, n, p.Name)
- text += fmt.Sprintf(" else {\n\t\t_p%d = unsafe.Pointer(&_zero)\n\t}\n", n)
- args = append(args, fmt.Sprintf("uintptr(_p%d)", n), fmt.Sprintf("uintptr(len(%s))", p.Name))
- n++
- } else if p.Type == "int64" && (*openbsd || *netbsd) {
- args = append(args, "0")
- if endianness == "big-endian" {
- args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name))
- } else if endianness == "little-endian" {
- args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name))
- } else {
- args = append(args, fmt.Sprintf("uintptr(%s)", p.Name))
- }
- } else if p.Type == "int64" && *dragonfly {
- if regexp.MustCompile(`^(?i)extp(read|write)`).FindStringSubmatch(funct) == nil {
- args = append(args, "0")
- }
- if endianness == "big-endian" {
- args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name))
- } else if endianness == "little-endian" {
- args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name))
- } else {
- args = append(args, fmt.Sprintf("uintptr(%s)", p.Name))
- }
- } else if (p.Type == "int64" || p.Type == "uint64") && endianness != "" {
- if len(args)%2 == 1 && *arm {
- // arm abi specifies 64-bit argument uses
- // (even, odd) pair
- args = append(args, "0")
- }
- if endianness == "big-endian" {
- args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name))
- } else {
- args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name))
- }
- } else {
- args = append(args, fmt.Sprintf("uintptr(%s)", p.Name))
- }
- }
-
- // Determine which form to use; pad args with zeros.
- asm := "Syscall"
- if nonblock != nil {
- if errvar == "" && goos == "linux" {
- asm = "RawSyscallNoError"
- } else {
- asm = "RawSyscall"
- }
- } else {
- if errvar == "" && goos == "linux" {
- asm = "SyscallNoError"
- }
- }
- if len(args) <= 3 {
- for len(args) < 3 {
- args = append(args, "0")
- }
- } else if len(args) <= 6 {
- asm += "6"
- for len(args) < 6 {
- args = append(args, "0")
- }
- } else if len(args) <= 9 {
- asm += "9"
- for len(args) < 9 {
- args = append(args, "0")
- }
- } else {
- fmt.Fprintf(os.Stderr, "%s:%s too many arguments to system call\n", path, funct)
- }
-
- // System call number.
- if sysname == "" {
- sysname = "SYS_" + funct
- sysname = regexp.MustCompile(`([a-z])([A-Z])`).ReplaceAllString(sysname, `${1}_$2`)
- sysname = strings.ToUpper(sysname)
- }
-
- var libcFn string
- if libc {
- asm = "syscall_" + strings.ToLower(asm[:1]) + asm[1:] // internal syscall call
- sysname = strings.TrimPrefix(sysname, "SYS_") // remove SYS_
- sysname = strings.ToLower(sysname) // lowercase
- if sysname == "getdirentries64" {
- // Special case - libSystem name and
- // raw syscall name don't match.
- sysname = "__getdirentries64"
- }
- libcFn = sysname
- sysname = "funcPC(libc_" + sysname + "_trampoline)"
- }
-
- // Actual call.
- arglist := strings.Join(args, ", ")
- call := fmt.Sprintf("%s(%s, %s)", asm, sysname, arglist)
-
- // Assign return values.
- body := ""
- ret := []string{"_", "_", "_"}
- doErrno := false
- for i := 0; i < len(out); i++ {
- p := parseParam(out[i])
- reg := ""
- if p.Name == "err" && !*plan9 {
- reg = "e1"
- ret[2] = reg
- doErrno = true
- } else if p.Name == "err" && *plan9 {
- ret[0] = "r0"
- ret[2] = "e1"
- break
- } else {
- reg = fmt.Sprintf("r%d", i)
- ret[i] = reg
- }
- if p.Type == "bool" {
- reg = fmt.Sprintf("%s != 0", reg)
- }
- if p.Type == "int64" && endianness != "" {
- // 64-bit number in r1:r0 or r0:r1.
- if i+2 > len(out) {
- fmt.Fprintf(os.Stderr, "%s:%s not enough registers for int64 return\n", path, funct)
- }
- if endianness == "big-endian" {
- reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i, i+1)
- } else {
- reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i+1, i)
- }
- ret[i] = fmt.Sprintf("r%d", i)
- ret[i+1] = fmt.Sprintf("r%d", i+1)
- }
- if reg != "e1" || *plan9 {
- body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg)
- }
- }
- if ret[0] == "_" && ret[1] == "_" && ret[2] == "_" {
- text += fmt.Sprintf("\t%s\n", call)
- } else {
- if errvar == "" && goos == "linux" {
- // raw syscall without error on Linux, see golang.org/issue/22924
- text += fmt.Sprintf("\t%s, %s := %s\n", ret[0], ret[1], call)
- } else {
- text += fmt.Sprintf("\t%s, %s, %s := %s\n", ret[0], ret[1], ret[2], call)
- }
- }
- text += body
-
- if *plan9 && ret[2] == "e1" {
- text += "\tif int32(r0) == -1 {\n"
- text += "\t\terr = e1\n"
- text += "\t}\n"
- } else if doErrno {
- text += "\tif e1 != 0 {\n"
- text += "\t\terr = errnoErr(e1)\n"
- text += "\t}\n"
- }
- text += "\treturn\n"
- text += "}\n\n"
-
- if libc && !trampolines[libcFn] {
- // some system calls share a trampoline, like read and readlen.
- trampolines[libcFn] = true
- // Declare assembly trampoline.
- text += fmt.Sprintf("func libc_%s_trampoline()\n", libcFn)
- // Assembly trampoline calls the libc_* function, which this magic
- // redirects to use the function from libSystem.
- text += fmt.Sprintf("//go:linkname libc_%s libc_%s\n", libcFn, libcFn)
- text += fmt.Sprintf("//go:cgo_import_dynamic libc_%s %s \"/usr/lib/libSystem.B.dylib\"\n", libcFn, libcFn)
- text += "\n"
- }
- }
- if err := s.Err(); err != nil {
- fmt.Fprintf(os.Stderr, err.Error())
- os.Exit(1)
- }
- file.Close()
- }
- fmt.Printf(srcTemplate, cmdLine(), buildTags(), text)
-}
-
-const srcTemplate = `// %s
-// Code generated by the command above; see README.md. DO NOT EDIT.
-
-// +build %s
-
-package unix
-
-import (
- "syscall"
- "unsafe"
-)
-
-var _ syscall.Errno
-
-%s
-`
diff --git a/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.go b/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.go
deleted file mode 100644
index 3be3cdf..0000000
--- a/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc.go
+++ /dev/null
@@ -1,415 +0,0 @@
-// Copyright 2019 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-/*
-This program reads a file containing function prototypes
-(like syscall_aix.go) and generates system call bodies.
-The prototypes are marked by lines beginning with "//sys"
-and read like func declarations if //sys is replaced by func, but:
- * The parameter lists must give a name for each argument.
- This includes return parameters.
- * The parameter lists must give a type for each argument:
- the (x, y, z int) shorthand is not allowed.
- * If the return parameter is an error number, it must be named err.
- * If go func name needs to be different than its libc name,
- * or the function is not in libc, name could be specified
- * at the end, after "=" sign, like
- //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt
-*/
-package main
-
-import (
- "bufio"
- "flag"
- "fmt"
- "os"
- "regexp"
- "strings"
-)
-
-var (
- b32 = flag.Bool("b32", false, "32bit big-endian")
- l32 = flag.Bool("l32", false, "32bit little-endian")
- aix = flag.Bool("aix", false, "aix")
- tags = flag.String("tags", "", "build tags")
-)
-
-// cmdLine returns this programs's commandline arguments
-func cmdLine() string {
- return "go run mksyscall_aix_ppc.go " + strings.Join(os.Args[1:], " ")
-}
-
-// buildTags returns build tags
-func buildTags() string {
- return *tags
-}
-
-// Param is function parameter
-type Param struct {
- Name string
- Type string
-}
-
-// usage prints the program usage
-func usage() {
- fmt.Fprintf(os.Stderr, "usage: go run mksyscall_aix_ppc.go [-b32 | -l32] [-tags x,y] [file ...]\n")
- os.Exit(1)
-}
-
-// parseParamList parses parameter list and returns a slice of parameters
-func parseParamList(list string) []string {
- list = strings.TrimSpace(list)
- if list == "" {
- return []string{}
- }
- return regexp.MustCompile(`\s*,\s*`).Split(list, -1)
-}
-
-// parseParam splits a parameter into name and type
-func parseParam(p string) Param {
- ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p)
- if ps == nil {
- fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p)
- os.Exit(1)
- }
- return Param{ps[1], ps[2]}
-}
-
-func main() {
- flag.Usage = usage
- flag.Parse()
- if len(flag.Args()) <= 0 {
- fmt.Fprintf(os.Stderr, "no files to parse provided\n")
- usage()
- }
-
- endianness := ""
- if *b32 {
- endianness = "big-endian"
- } else if *l32 {
- endianness = "little-endian"
- }
-
- pack := ""
- text := ""
- cExtern := "/*\n#include <stdint.h>\n#include <stddef.h>\n"
- for _, path := range flag.Args() {
- file, err := os.Open(path)
- if err != nil {
- fmt.Fprintf(os.Stderr, err.Error())
- os.Exit(1)
- }
- s := bufio.NewScanner(file)
- for s.Scan() {
- t := s.Text()
- t = strings.TrimSpace(t)
- t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `)
- if p := regexp.MustCompile(`^package (\S+)$`).FindStringSubmatch(t); p != nil && pack == "" {
- pack = p[1]
- }
- nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t)
- if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil {
- continue
- }
-
- // Line must be of the form
- // func Open(path string, mode int, perm int) (fd int, err error)
- // Split into name, in params, out params.
- f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$`).FindStringSubmatch(t)
- if f == nil {
- fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t)
- os.Exit(1)
- }
- funct, inps, outps, modname, sysname := f[2], f[3], f[4], f[5], f[6]
-
- // Split argument lists on comma.
- in := parseParamList(inps)
- out := parseParamList(outps)
-
- inps = strings.Join(in, ", ")
- outps = strings.Join(out, ", ")
-
- // Try in vain to keep people from editing this file.
- // The theory is that they jump into the middle of the file
- // without reading the header.
- text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"
-
- // Check if value return, err return available
- errvar := ""
- retvar := ""
- rettype := ""
- for _, param := range out {
- p := parseParam(param)
- if p.Type == "error" {
- errvar = p.Name
- } else {
- retvar = p.Name
- rettype = p.Type
- }
- }
-
- // System call name.
- if sysname == "" {
- sysname = funct
- }
- sysname = regexp.MustCompile(`([a-z])([A-Z])`).ReplaceAllString(sysname, `${1}_$2`)
- sysname = strings.ToLower(sysname) // All libc functions are lowercase.
-
- cRettype := ""
- if rettype == "unsafe.Pointer" {
- cRettype = "uintptr_t"
- } else if rettype == "uintptr" {
- cRettype = "uintptr_t"
- } else if regexp.MustCompile(`^_`).FindStringSubmatch(rettype) != nil {
- cRettype = "uintptr_t"
- } else if rettype == "int" {
- cRettype = "int"
- } else if rettype == "int32" {
- cRettype = "int"
- } else if rettype == "int64" {
- cRettype = "long long"
- } else if rettype == "uint32" {
- cRettype = "unsigned int"
- } else if rettype == "uint64" {
- cRettype = "unsigned long long"
- } else {
- cRettype = "int"
- }
- if sysname == "exit" {
- cRettype = "void"
- }
-
- // Change p.Types to c
- var cIn []string
- for _, param := range in {
- p := parseParam(param)
- if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil {
- cIn = append(cIn, "uintptr_t")
- } else if p.Type == "string" {
- cIn = append(cIn, "uintptr_t")
- } else if regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type) != nil {
- cIn = append(cIn, "uintptr_t", "size_t")
- } else if p.Type == "unsafe.Pointer" {
- cIn = append(cIn, "uintptr_t")
- } else if p.Type == "uintptr" {
- cIn = append(cIn, "uintptr_t")
- } else if regexp.MustCompile(`^_`).FindStringSubmatch(p.Type) != nil {
- cIn = append(cIn, "uintptr_t")
- } else if p.Type == "int" {
- cIn = append(cIn, "int")
- } else if p.Type == "int32" {
- cIn = append(cIn, "int")
- } else if p.Type == "int64" {
- cIn = append(cIn, "long long")
- } else if p.Type == "uint32" {
- cIn = append(cIn, "unsigned int")
- } else if p.Type == "uint64" {
- cIn = append(cIn, "unsigned long long")
- } else {
- cIn = append(cIn, "int")
- }
- }
-
- if funct != "fcntl" && funct != "FcntlInt" && funct != "readlen" && funct != "writelen" {
- if sysname == "select" {
- // select is a keyword of Go. Its name is
- // changed to c_select.
- cExtern += "#define c_select select\n"
- }
- // Imports of system calls from libc
- cExtern += fmt.Sprintf("%s %s", cRettype, sysname)
- cIn := strings.Join(cIn, ", ")
- cExtern += fmt.Sprintf("(%s);\n", cIn)
- }
-
- // So file name.
- if *aix {
- if modname == "" {
- modname = "libc.a/shr_64.o"
- } else {
- fmt.Fprintf(os.Stderr, "%s: only syscall using libc are available\n", funct)
- os.Exit(1)
- }
- }
-
- strconvfunc := "C.CString"
-
- // Go function header.
- if outps != "" {
- outps = fmt.Sprintf(" (%s)", outps)
- }
- if text != "" {
- text += "\n"
- }
-
- text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outps)
-
- // Prepare arguments to Syscall.
- var args []string
- n := 0
- argN := 0
- for _, param := range in {
- p := parseParam(param)
- if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil {
- args = append(args, "C.uintptr_t(uintptr(unsafe.Pointer("+p.Name+")))")
- } else if p.Type == "string" && errvar != "" {
- text += fmt.Sprintf("\t_p%d := uintptr(unsafe.Pointer(%s(%s)))\n", n, strconvfunc, p.Name)
- args = append(args, fmt.Sprintf("C.uintptr_t(_p%d)", n))
- n++
- } else if p.Type == "string" {
- fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n")
- text += fmt.Sprintf("\t_p%d := uintptr(unsafe.Pointer(%s(%s)))\n", n, strconvfunc, p.Name)
- args = append(args, fmt.Sprintf("C.uintptr_t(_p%d)", n))
- n++
- } else if m := regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type); m != nil {
- // Convert slice into pointer, length.
- // Have to be careful not to take address of &a[0] if len == 0:
- // pass nil in that case.
- text += fmt.Sprintf("\tvar _p%d *%s\n", n, m[1])
- text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = &%s[0]\n\t}\n", p.Name, n, p.Name)
- args = append(args, fmt.Sprintf("C.uintptr_t(uintptr(unsafe.Pointer(_p%d)))", n))
- n++
- text += fmt.Sprintf("\tvar _p%d int\n", n)
- text += fmt.Sprintf("\t_p%d = len(%s)\n", n, p.Name)
- args = append(args, fmt.Sprintf("C.size_t(_p%d)", n))
- n++
- } else if p.Type == "int64" && endianness != "" {
- if endianness == "big-endian" {
- args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name))
- } else {
- args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name))
- }
- n++
- } else if p.Type == "bool" {
- text += fmt.Sprintf("\tvar _p%d uint32\n", n)
- text += fmt.Sprintf("\tif %s {\n\t\t_p%d = 1\n\t} else {\n\t\t_p%d = 0\n\t}\n", p.Name, n, n)
- args = append(args, fmt.Sprintf("_p%d", n))
- } else if regexp.MustCompile(`^_`).FindStringSubmatch(p.Type) != nil {
- args = append(args, fmt.Sprintf("C.uintptr_t(uintptr(%s))", p.Name))
- } else if p.Type == "unsafe.Pointer" {
- args = append(args, fmt.Sprintf("C.uintptr_t(uintptr(%s))", p.Name))
- } else if p.Type == "int" {
- if (argN == 2) && ((funct == "readlen") || (funct == "writelen")) {
- args = append(args, fmt.Sprintf("C.size_t(%s)", p.Name))
- } else if argN == 0 && funct == "fcntl" {
- args = append(args, fmt.Sprintf("C.uintptr_t(%s)", p.Name))
- } else if (argN == 2) && ((funct == "fcntl") || (funct == "FcntlInt")) {
- args = append(args, fmt.Sprintf("C.uintptr_t(%s)", p.Name))
- } else {
- args = append(args, fmt.Sprintf("C.int(%s)", p.Name))
- }
- } else if p.Type == "int32" {
- args = append(args, fmt.Sprintf("C.int(%s)", p.Name))
- } else if p.Type == "int64" {
- args = append(args, fmt.Sprintf("C.longlong(%s)", p.Name))
- } else if p.Type == "uint32" {
- args = append(args, fmt.Sprintf("C.uint(%s)", p.Name))
- } else if p.Type == "uint64" {
- args = append(args, fmt.Sprintf("C.ulonglong(%s)", p.Name))
- } else if p.Type == "uintptr" {
- args = append(args, fmt.Sprintf("C.uintptr_t(%s)", p.Name))
- } else {
- args = append(args, fmt.Sprintf("C.int(%s)", p.Name))
- }
- argN++
- }
-
- // Actual call.
- arglist := strings.Join(args, ", ")
- call := ""
- if sysname == "exit" {
- if errvar != "" {
- call += "er :="
- } else {
- call += ""
- }
- } else if errvar != "" {
- call += "r0,er :="
- } else if retvar != "" {
- call += "r0,_ :="
- } else {
- call += ""
- }
- if sysname == "select" {
- // select is a keyword of Go. Its name is
- // changed to c_select.
- call += fmt.Sprintf("C.c_%s(%s)", sysname, arglist)
- } else {
- call += fmt.Sprintf("C.%s(%s)", sysname, arglist)
- }
-
- // Assign return values.
- body := ""
- for i := 0; i < len(out); i++ {
- p := parseParam(out[i])
- reg := ""
- if p.Name == "err" {
- reg = "e1"
- } else {
- reg = "r0"
- }
- if reg != "e1" {
- body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg)
- }
- }
-
- // verify return
- if sysname != "exit" && errvar != "" {
- if regexp.MustCompile(`^uintptr`).FindStringSubmatch(cRettype) != nil {
- body += "\tif (uintptr(r0) ==^uintptr(0) && er != nil) {\n"
- body += fmt.Sprintf("\t\t%s = er\n", errvar)
- body += "\t}\n"
- } else {
- body += "\tif (r0 ==-1 && er != nil) {\n"
- body += fmt.Sprintf("\t\t%s = er\n", errvar)
- body += "\t}\n"
- }
- } else if errvar != "" {
- body += "\tif (er != nil) {\n"
- body += fmt.Sprintf("\t\t%s = er\n", errvar)
- body += "\t}\n"
- }
-
- text += fmt.Sprintf("\t%s\n", call)
- text += body
-
- text += "\treturn\n"
- text += "}\n"
- }
- if err := s.Err(); err != nil {
- fmt.Fprintf(os.Stderr, err.Error())
- os.Exit(1)
- }
- file.Close()
- }
- imp := ""
- if pack != "unix" {
- imp = "import \"golang.org/x/sys/unix\"\n"
-
- }
- fmt.Printf(srcTemplate, cmdLine(), buildTags(), pack, cExtern, imp, text)
-}
-
-const srcTemplate = `// %s
-// Code generated by the command above; see README.md. DO NOT EDIT.
-
-// +build %s
-
-package %s
-
-
-%s
-*/
-import "C"
-import (
- "unsafe"
-)
-
-
-%s
-
-%s
-`
diff --git a/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.go b/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.go
deleted file mode 100644
index c960099..0000000
--- a/vendor/golang.org/x/sys/unix/mksyscall_aix_ppc64.go
+++ /dev/null
@@ -1,614 +0,0 @@
-// Copyright 2019 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-/*
-This program reads a file containing function prototypes
-(like syscall_aix.go) and generates system call bodies.
-The prototypes are marked by lines beginning with "//sys"
-and read like func declarations if //sys is replaced by func, but:
- * The parameter lists must give a name for each argument.
- This includes return parameters.
- * The parameter lists must give a type for each argument:
- the (x, y, z int) shorthand is not allowed.
- * If the return parameter is an error number, it must be named err.
- * If go func name needs to be different than its libc name,
- * or the function is not in libc, name could be specified
- * at the end, after "=" sign, like
- //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt
-
-
-This program will generate three files and handle both gc and gccgo implementation:
- - zsyscall_aix_ppc64.go: the common part of each implementation (error handler, pointer creation)
- - zsyscall_aix_ppc64_gc.go: gc part with //go_cgo_import_dynamic and a call to syscall6
- - zsyscall_aix_ppc64_gccgo.go: gccgo part with C function and conversion to C type.
-
- The generated code looks like this
-
-zsyscall_aix_ppc64.go
-func asyscall(...) (n int, err error) {
- // Pointer Creation
- r1, e1 := callasyscall(...)
- // Type Conversion
- // Error Handler
- return
-}
-
-zsyscall_aix_ppc64_gc.go
-//go:cgo_import_dynamic libc_asyscall asyscall "libc.a/shr_64.o"
-//go:linkname libc_asyscall libc_asyscall
-var asyscall syscallFunc
-
-func callasyscall(...) (r1 uintptr, e1 Errno) {
- r1, _, e1 = syscall6(uintptr(unsafe.Pointer(&libc_asyscall)), "nb_args", ... )
- return
-}
-
-zsyscall_aix_ppc64_ggcgo.go
-
-// int asyscall(...)
-
-import "C"
-
-func callasyscall(...) (r1 uintptr, e1 Errno) {
- r1 = uintptr(C.asyscall(...))
- e1 = syscall.GetErrno()
- return
-}
-*/
-
-package main
-
-import (
- "bufio"
- "flag"
- "fmt"
- "io/ioutil"
- "os"
- "regexp"
- "strings"
-)
-
-var (
- b32 = flag.Bool("b32", false, "32bit big-endian")
- l32 = flag.Bool("l32", false, "32bit little-endian")
- aix = flag.Bool("aix", false, "aix")
- tags = flag.String("tags", "", "build tags")
-)
-
-// cmdLine returns this programs's commandline arguments
-func cmdLine() string {
- return "go run mksyscall_aix_ppc64.go " + strings.Join(os.Args[1:], " ")
-}
-
-// buildTags returns build tags
-func buildTags() string {
- return *tags
-}
-
-// Param is function parameter
-type Param struct {
- Name string
- Type string
-}
-
-// usage prints the program usage
-func usage() {
- fmt.Fprintf(os.Stderr, "usage: go run mksyscall_aix_ppc64.go [-b32 | -l32] [-tags x,y] [file ...]\n")
- os.Exit(1)
-}
-
-// parseParamList parses parameter list and returns a slice of parameters
-func parseParamList(list string) []string {
- list = strings.TrimSpace(list)
- if list == "" {
- return []string{}
- }
- return regexp.MustCompile(`\s*,\s*`).Split(list, -1)
-}
-
-// parseParam splits a parameter into name and type
-func parseParam(p string) Param {
- ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p)
- if ps == nil {
- fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p)
- os.Exit(1)
- }
- return Param{ps[1], ps[2]}
-}
-
-func main() {
- flag.Usage = usage
- flag.Parse()
- if len(flag.Args()) <= 0 {
- fmt.Fprintf(os.Stderr, "no files to parse provided\n")
- usage()
- }
-
- endianness := ""
- if *b32 {
- endianness = "big-endian"
- } else if *l32 {
- endianness = "little-endian"
- }
-
- pack := ""
- // GCCGO
- textgccgo := ""
- cExtern := "/*\n#include <stdint.h>\n"
- // GC
- textgc := ""
- dynimports := ""
- linknames := ""
- var vars []string
- // COMMON
- textcommon := ""
- for _, path := range flag.Args() {
- file, err := os.Open(path)
- if err != nil {
- fmt.Fprintf(os.Stderr, err.Error())
- os.Exit(1)
- }
- s := bufio.NewScanner(file)
- for s.Scan() {
- t := s.Text()
- t = strings.TrimSpace(t)
- t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `)
- if p := regexp.MustCompile(`^package (\S+)$`).FindStringSubmatch(t); p != nil && pack == "" {
- pack = p[1]
- }
- nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t)
- if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil {
- continue
- }
-
- // Line must be of the form
- // func Open(path string, mode int, perm int) (fd int, err error)
- // Split into name, in params, out params.
- f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$`).FindStringSubmatch(t)
- if f == nil {
- fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t)
- os.Exit(1)
- }
- funct, inps, outps, modname, sysname := f[2], f[3], f[4], f[5], f[6]
-
- // Split argument lists on comma.
- in := parseParamList(inps)
- out := parseParamList(outps)
-
- inps = strings.Join(in, ", ")
- outps = strings.Join(out, ", ")
-
- if sysname == "" {
- sysname = funct
- }
-
- onlyCommon := false
- if funct == "readlen" || funct == "writelen" || funct == "FcntlInt" || funct == "FcntlFlock" {
- // This function call another syscall which is already implemented.
- // Therefore, the gc and gccgo part must not be generated.
- onlyCommon = true
- }
-
- // Try in vain to keep people from editing this file.
- // The theory is that they jump into the middle of the file
- // without reading the header.
-
- textcommon += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"
- if !onlyCommon {
- textgccgo += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"
- textgc += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"
- }
-
- // Check if value return, err return available
- errvar := ""
- rettype := ""
- for _, param := range out {
- p := parseParam(param)
- if p.Type == "error" {
- errvar = p.Name
- } else {
- rettype = p.Type
- }
- }
-
- sysname = regexp.MustCompile(`([a-z])([A-Z])`).ReplaceAllString(sysname, `${1}_$2`)
- sysname = strings.ToLower(sysname) // All libc functions are lowercase.
-
- // GCCGO Prototype return type
- cRettype := ""
- if rettype == "unsafe.Pointer" {
- cRettype = "uintptr_t"
- } else if rettype == "uintptr" {
- cRettype = "uintptr_t"
- } else if regexp.MustCompile(`^_`).FindStringSubmatch(rettype) != nil {
- cRettype = "uintptr_t"
- } else if rettype == "int" {
- cRettype = "int"
- } else if rettype == "int32" {
- cRettype = "int"
- } else if rettype == "int64" {
- cRettype = "long long"
- } else if rettype == "uint32" {
- cRettype = "unsigned int"
- } else if rettype == "uint64" {
- cRettype = "unsigned long long"
- } else {
- cRettype = "int"
- }
- if sysname == "exit" {
- cRettype = "void"
- }
-
- // GCCGO Prototype arguments type
- var cIn []string
- for i, param := range in {
- p := parseParam(param)
- if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil {
- cIn = append(cIn, "uintptr_t")
- } else if p.Type == "string" {
- cIn = append(cIn, "uintptr_t")
- } else if regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type) != nil {
- cIn = append(cIn, "uintptr_t", "size_t")
- } else if p.Type == "unsafe.Pointer" {
- cIn = append(cIn, "uintptr_t")
- } else if p.Type == "uintptr" {
- cIn = append(cIn, "uintptr_t")
- } else if regexp.MustCompile(`^_`).FindStringSubmatch(p.Type) != nil {
- cIn = append(cIn, "uintptr_t")
- } else if p.Type == "int" {
- if (i == 0 || i == 2) && funct == "fcntl" {
- // These fcntl arguments needs to be uintptr to be able to call FcntlInt and FcntlFlock
- cIn = append(cIn, "uintptr_t")
- } else {
- cIn = append(cIn, "int")
- }
-
- } else if p.Type == "int32" {
- cIn = append(cIn, "int")
- } else if p.Type == "int64" {
- cIn = append(cIn, "long long")
- } else if p.Type == "uint32" {
- cIn = append(cIn, "unsigned int")
- } else if p.Type == "uint64" {
- cIn = append(cIn, "unsigned long long")
- } else {
- cIn = append(cIn, "int")
- }
- }
-
- if !onlyCommon {
- // GCCGO Prototype Generation
- // Imports of system calls from libc
- if sysname == "select" {
- // select is a keyword of Go. Its name is
- // changed to c_select.
- cExtern += "#define c_select select\n"
- }
- cExtern += fmt.Sprintf("%s %s", cRettype, sysname)
- cIn := strings.Join(cIn, ", ")
- cExtern += fmt.Sprintf("(%s);\n", cIn)
- }
- // GC Library name
- if modname == "" {
- modname = "libc.a/shr_64.o"
- } else {
- fmt.Fprintf(os.Stderr, "%s: only syscall using libc are available\n", funct)
- os.Exit(1)
- }
- sysvarname := fmt.Sprintf("libc_%s", sysname)
-
- if !onlyCommon {
- // GC Runtime import of function to allow cross-platform builds.
- dynimports += fmt.Sprintf("//go:cgo_import_dynamic %s %s \"%s\"\n", sysvarname, sysname, modname)
- // GC Link symbol to proc address variable.
- linknames += fmt.Sprintf("//go:linkname %s %s\n", sysvarname, sysvarname)
- // GC Library proc address variable.
- vars = append(vars, sysvarname)
- }
-
- strconvfunc := "BytePtrFromString"
- strconvtype := "*byte"
-
- // Go function header.
- if outps != "" {
- outps = fmt.Sprintf(" (%s)", outps)
- }
- if textcommon != "" {
- textcommon += "\n"
- }
-
- textcommon += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outps)
-
- // Prepare arguments tocall.
- var argscommon []string // Arguments in the common part
- var argscall []string // Arguments for call prototype
- var argsgc []string // Arguments for gc call (with syscall6)
- var argsgccgo []string // Arguments for gccgo call (with C.name_of_syscall)
- n := 0
- argN := 0
- for _, param := range in {
- p := parseParam(param)
- if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil {
- argscommon = append(argscommon, fmt.Sprintf("uintptr(unsafe.Pointer(%s))", p.Name))
- argscall = append(argscall, fmt.Sprintf("%s uintptr", p.Name))
- argsgc = append(argsgc, p.Name)
- argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(%s)", p.Name))
- } else if p.Type == "string" && errvar != "" {
- textcommon += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype)
- textcommon += fmt.Sprintf("\t_p%d, %s = %s(%s)\n", n, errvar, strconvfunc, p.Name)
- textcommon += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar)
-
- argscommon = append(argscommon, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
- argscall = append(argscall, fmt.Sprintf("_p%d uintptr ", n))
- argsgc = append(argsgc, fmt.Sprintf("_p%d", n))
- argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(_p%d)", n))
- n++
- } else if p.Type == "string" {
- fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n")
- textcommon += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype)
- textcommon += fmt.Sprintf("\t_p%d, %s = %s(%s)\n", n, errvar, strconvfunc, p.Name)
- textcommon += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar)
-
- argscommon = append(argscommon, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
- argscall = append(argscall, fmt.Sprintf("_p%d uintptr", n))
- argsgc = append(argsgc, fmt.Sprintf("_p%d", n))
- argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(_p%d)", n))
- n++
- } else if m := regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type); m != nil {
- // Convert slice into pointer, length.
- // Have to be careful not to take address of &a[0] if len == 0:
- // pass nil in that case.
- textcommon += fmt.Sprintf("\tvar _p%d *%s\n", n, m[1])
- textcommon += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = &%s[0]\n\t}\n", p.Name, n, p.Name)
- argscommon = append(argscommon, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n), fmt.Sprintf("len(%s)", p.Name))
- argscall = append(argscall, fmt.Sprintf("_p%d uintptr", n), fmt.Sprintf("_lenp%d int", n))
- argsgc = append(argsgc, fmt.Sprintf("_p%d", n), fmt.Sprintf("uintptr(_lenp%d)", n))
- argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(_p%d)", n), fmt.Sprintf("C.size_t(_lenp%d)", n))
- n++
- } else if p.Type == "int64" && endianness != "" {
- fmt.Fprintf(os.Stderr, path+":"+funct+" uses int64 with 32 bits mode. Case not yet implemented\n")
- } else if p.Type == "bool" {
- fmt.Fprintf(os.Stderr, path+":"+funct+" uses bool. Case not yet implemented\n")
- } else if regexp.MustCompile(`^_`).FindStringSubmatch(p.Type) != nil || p.Type == "unsafe.Pointer" {
- argscommon = append(argscommon, fmt.Sprintf("uintptr(%s)", p.Name))
- argscall = append(argscall, fmt.Sprintf("%s uintptr", p.Name))
- argsgc = append(argsgc, p.Name)
- argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(%s)", p.Name))
- } else if p.Type == "int" {
- if (argN == 0 || argN == 2) && ((funct == "fcntl") || (funct == "FcntlInt") || (funct == "FcntlFlock")) {
- // These fcntl arguments need to be uintptr to be able to call FcntlInt and FcntlFlock
- argscommon = append(argscommon, fmt.Sprintf("uintptr(%s)", p.Name))
- argscall = append(argscall, fmt.Sprintf("%s uintptr", p.Name))
- argsgc = append(argsgc, p.Name)
- argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(%s)", p.Name))
-
- } else {
- argscommon = append(argscommon, p.Name)
- argscall = append(argscall, fmt.Sprintf("%s int", p.Name))
- argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name))
- argsgccgo = append(argsgccgo, fmt.Sprintf("C.int(%s)", p.Name))
- }
- } else if p.Type == "int32" {
- argscommon = append(argscommon, p.Name)
- argscall = append(argscall, fmt.Sprintf("%s int32", p.Name))
- argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name))
- argsgccgo = append(argsgccgo, fmt.Sprintf("C.int(%s)", p.Name))
- } else if p.Type == "int64" {
- argscommon = append(argscommon, p.Name)
- argscall = append(argscall, fmt.Sprintf("%s int64", p.Name))
- argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name))
- argsgccgo = append(argsgccgo, fmt.Sprintf("C.longlong(%s)", p.Name))
- } else if p.Type == "uint32" {
- argscommon = append(argscommon, p.Name)
- argscall = append(argscall, fmt.Sprintf("%s uint32", p.Name))
- argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name))
- argsgccgo = append(argsgccgo, fmt.Sprintf("C.uint(%s)", p.Name))
- } else if p.Type == "uint64" {
- argscommon = append(argscommon, p.Name)
- argscall = append(argscall, fmt.Sprintf("%s uint64", p.Name))
- argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name))
- argsgccgo = append(argsgccgo, fmt.Sprintf("C.ulonglong(%s)", p.Name))
- } else if p.Type == "uintptr" {
- argscommon = append(argscommon, p.Name)
- argscall = append(argscall, fmt.Sprintf("%s uintptr", p.Name))
- argsgc = append(argsgc, p.Name)
- argsgccgo = append(argsgccgo, fmt.Sprintf("C.uintptr_t(%s)", p.Name))
- } else {
- argscommon = append(argscommon, fmt.Sprintf("int(%s)", p.Name))
- argscall = append(argscall, fmt.Sprintf("%s int", p.Name))
- argsgc = append(argsgc, fmt.Sprintf("uintptr(%s)", p.Name))
- argsgccgo = append(argsgccgo, fmt.Sprintf("C.int(%s)", p.Name))
- }
- argN++
- }
- nargs := len(argsgc)
-
- // COMMON function generation
- argscommonlist := strings.Join(argscommon, ", ")
- callcommon := fmt.Sprintf("call%s(%s)", sysname, argscommonlist)
- ret := []string{"_", "_"}
- body := ""
- doErrno := false
- for i := 0; i < len(out); i++ {
- p := parseParam(out[i])
- reg := ""
- if p.Name == "err" {
- reg = "e1"
- ret[1] = reg
- doErrno = true
- } else {
- reg = "r0"
- ret[0] = reg
- }
- if p.Type == "bool" {
- reg = fmt.Sprintf("%s != 0", reg)
- }
- if reg != "e1" {
- body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg)
- }
- }
- if ret[0] == "_" && ret[1] == "_" {
- textcommon += fmt.Sprintf("\t%s\n", callcommon)
- } else {
- textcommon += fmt.Sprintf("\t%s, %s := %s\n", ret[0], ret[1], callcommon)
- }
- textcommon += body
-
- if doErrno {
- textcommon += "\tif e1 != 0 {\n"
- textcommon += "\t\terr = errnoErr(e1)\n"
- textcommon += "\t}\n"
- }
- textcommon += "\treturn\n"
- textcommon += "}\n"
-
- if onlyCommon {
- continue
- }
-
- // CALL Prototype
- callProto := fmt.Sprintf("func call%s(%s) (r1 uintptr, e1 Errno) {\n", sysname, strings.Join(argscall, ", "))
-
- // GC function generation
- asm := "syscall6"
- if nonblock != nil {
- asm = "rawSyscall6"
- }
-
- if len(argsgc) <= 6 {
- for len(argsgc) < 6 {
- argsgc = append(argsgc, "0")
- }
- } else {
- fmt.Fprintf(os.Stderr, "%s: too many arguments to system call", funct)
- os.Exit(1)
- }
- argsgclist := strings.Join(argsgc, ", ")
- callgc := fmt.Sprintf("%s(uintptr(unsafe.Pointer(&%s)), %d, %s)", asm, sysvarname, nargs, argsgclist)
-
- textgc += callProto
- textgc += fmt.Sprintf("\tr1, _, e1 = %s\n", callgc)
- textgc += "\treturn\n}\n"
-
- // GCCGO function generation
- argsgccgolist := strings.Join(argsgccgo, ", ")
- var callgccgo string
- if sysname == "select" {
- // select is a keyword of Go. Its name is
- // changed to c_select.
- callgccgo = fmt.Sprintf("C.c_%s(%s)", sysname, argsgccgolist)
- } else {
- callgccgo = fmt.Sprintf("C.%s(%s)", sysname, argsgccgolist)
- }
- textgccgo += callProto
- textgccgo += fmt.Sprintf("\tr1 = uintptr(%s)\n", callgccgo)
- textgccgo += "\te1 = syscall.GetErrno()\n"
- textgccgo += "\treturn\n}\n"
- }
- if err := s.Err(); err != nil {
- fmt.Fprintf(os.Stderr, err.Error())
- os.Exit(1)
- }
- file.Close()
- }
- imp := ""
- if pack != "unix" {
- imp = "import \"golang.org/x/sys/unix\"\n"
-
- }
-
- // Print zsyscall_aix_ppc64.go
- err := ioutil.WriteFile("zsyscall_aix_ppc64.go",
- []byte(fmt.Sprintf(srcTemplate1, cmdLine(), buildTags(), pack, imp, textcommon)),
- 0644)
- if err != nil {
- fmt.Fprintf(os.Stderr, err.Error())
- os.Exit(1)
- }
-
- // Print zsyscall_aix_ppc64_gc.go
- vardecls := "\t" + strings.Join(vars, ",\n\t")
- vardecls += " syscallFunc"
- err = ioutil.WriteFile("zsyscall_aix_ppc64_gc.go",
- []byte(fmt.Sprintf(srcTemplate2, cmdLine(), buildTags(), pack, imp, dynimports, linknames, vardecls, textgc)),
- 0644)
- if err != nil {
- fmt.Fprintf(os.Stderr, err.Error())
- os.Exit(1)
- }
-
- // Print zsyscall_aix_ppc64_gccgo.go
- err = ioutil.WriteFile("zsyscall_aix_ppc64_gccgo.go",
- []byte(fmt.Sprintf(srcTemplate3, cmdLine(), buildTags(), pack, cExtern, imp, textgccgo)),
- 0644)
- if err != nil {
- fmt.Fprintf(os.Stderr, err.Error())
- os.Exit(1)
- }
-}
-
-const srcTemplate1 = `// %s
-// Code generated by the command above; see README.md. DO NOT EDIT.
-
-// +build %s
-
-package %s
-
-import (
- "unsafe"
-)
-
-
-%s
-
-%s
-`
-const srcTemplate2 = `// %s
-// Code generated by the command above; see README.md. DO NOT EDIT.
-
-// +build %s
-// +build !gccgo
-
-package %s
-
-import (
- "unsafe"
-)
-%s
-%s
-%s
-type syscallFunc uintptr
-
-var (
-%s
-)
-
-// Implemented in runtime/syscall_aix.go.
-func rawSyscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
-func syscall6(trap, nargs, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2 uintptr, err Errno)
-
-%s
-`
-const srcTemplate3 = `// %s
-// Code generated by the command above; see README.md. DO NOT EDIT.
-
-// +build %s
-// +build gccgo
-
-package %s
-
-%s
-*/
-import "C"
-import (
- "syscall"
-)
-
-
-%s
-
-%s
-`
diff --git a/vendor/golang.org/x/sys/unix/mksyscall_solaris.go b/vendor/golang.org/x/sys/unix/mksyscall_solaris.go
deleted file mode 100644
index 3d86473..0000000
--- a/vendor/golang.org/x/sys/unix/mksyscall_solaris.go
+++ /dev/null
@@ -1,335 +0,0 @@
-// Copyright 2019 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-/*
- This program reads a file containing function prototypes
- (like syscall_solaris.go) and generates system call bodies.
- The prototypes are marked by lines beginning with "//sys"
- and read like func declarations if //sys is replaced by func, but:
- * The parameter lists must give a name for each argument.
- This includes return parameters.
- * The parameter lists must give a type for each argument:
- the (x, y, z int) shorthand is not allowed.
- * If the return parameter is an error number, it must be named err.
- * If go func name needs to be different than its libc name,
- * or the function is not in libc, name could be specified
- * at the end, after "=" sign, like
- //sys getsockopt(s int, level int, name int, val uintptr, vallen *_Socklen) (err error) = libsocket.getsockopt
-*/
-
-package main
-
-import (
- "bufio"
- "flag"
- "fmt"
- "os"
- "regexp"
- "strings"
-)
-
-var (
- b32 = flag.Bool("b32", false, "32bit big-endian")
- l32 = flag.Bool("l32", false, "32bit little-endian")
- tags = flag.String("tags", "", "build tags")
-)
-
-// cmdLine returns this programs's commandline arguments
-func cmdLine() string {
- return "go run mksyscall_solaris.go " + strings.Join(os.Args[1:], " ")
-}
-
-// buildTags returns build tags
-func buildTags() string {
- return *tags
-}
-
-// Param is function parameter
-type Param struct {
- Name string
- Type string
-}
-
-// usage prints the program usage
-func usage() {
- fmt.Fprintf(os.Stderr, "usage: go run mksyscall_solaris.go [-b32 | -l32] [-tags x,y] [file ...]\n")
- os.Exit(1)
-}
-
-// parseParamList parses parameter list and returns a slice of parameters
-func parseParamList(list string) []string {
- list = strings.TrimSpace(list)
- if list == "" {
- return []string{}
- }
- return regexp.MustCompile(`\s*,\s*`).Split(list, -1)
-}
-
-// parseParam splits a parameter into name and type
-func parseParam(p string) Param {
- ps := regexp.MustCompile(`^(\S*) (\S*)$`).FindStringSubmatch(p)
- if ps == nil {
- fmt.Fprintf(os.Stderr, "malformed parameter: %s\n", p)
- os.Exit(1)
- }
- return Param{ps[1], ps[2]}
-}
-
-func main() {
- flag.Usage = usage
- flag.Parse()
- if len(flag.Args()) <= 0 {
- fmt.Fprintf(os.Stderr, "no files to parse provided\n")
- usage()
- }
-
- endianness := ""
- if *b32 {
- endianness = "big-endian"
- } else if *l32 {
- endianness = "little-endian"
- }
-
- pack := ""
- text := ""
- dynimports := ""
- linknames := ""
- var vars []string
- for _, path := range flag.Args() {
- file, err := os.Open(path)
- if err != nil {
- fmt.Fprintf(os.Stderr, err.Error())
- os.Exit(1)
- }
- s := bufio.NewScanner(file)
- for s.Scan() {
- t := s.Text()
- t = strings.TrimSpace(t)
- t = regexp.MustCompile(`\s+`).ReplaceAllString(t, ` `)
- if p := regexp.MustCompile(`^package (\S+)$`).FindStringSubmatch(t); p != nil && pack == "" {
- pack = p[1]
- }
- nonblock := regexp.MustCompile(`^\/\/sysnb `).FindStringSubmatch(t)
- if regexp.MustCompile(`^\/\/sys `).FindStringSubmatch(t) == nil && nonblock == nil {
- continue
- }
-
- // Line must be of the form
- // func Open(path string, mode int, perm int) (fd int, err error)
- // Split into name, in params, out params.
- f := regexp.MustCompile(`^\/\/sys(nb)? (\w+)\(([^()]*)\)\s*(?:\(([^()]+)\))?\s*(?:=\s*(?:(\w*)\.)?(\w*))?$`).FindStringSubmatch(t)
- if f == nil {
- fmt.Fprintf(os.Stderr, "%s:%s\nmalformed //sys declaration\n", path, t)
- os.Exit(1)
- }
- funct, inps, outps, modname, sysname := f[2], f[3], f[4], f[5], f[6]
-
- // Split argument lists on comma.
- in := parseParamList(inps)
- out := parseParamList(outps)
-
- inps = strings.Join(in, ", ")
- outps = strings.Join(out, ", ")
-
- // Try in vain to keep people from editing this file.
- // The theory is that they jump into the middle of the file
- // without reading the header.
- text += "// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n\n"
-
- // So file name.
- if modname == "" {
- modname = "libc"
- }
-
- // System call name.
- if sysname == "" {
- sysname = funct
- }
-
- // System call pointer variable name.
- sysvarname := fmt.Sprintf("proc%s", sysname)
-
- strconvfunc := "BytePtrFromString"
- strconvtype := "*byte"
-
- sysname = strings.ToLower(sysname) // All libc functions are lowercase.
-
- // Runtime import of function to allow cross-platform builds.
- dynimports += fmt.Sprintf("//go:cgo_import_dynamic libc_%s %s \"%s.so\"\n", sysname, sysname, modname)
- // Link symbol to proc address variable.
- linknames += fmt.Sprintf("//go:linkname %s libc_%s\n", sysvarname, sysname)
- // Library proc address variable.
- vars = append(vars, sysvarname)
-
- // Go function header.
- outlist := strings.Join(out, ", ")
- if outlist != "" {
- outlist = fmt.Sprintf(" (%s)", outlist)
- }
- if text != "" {
- text += "\n"
- }
- text += fmt.Sprintf("func %s(%s)%s {\n", funct, strings.Join(in, ", "), outlist)
-
- // Check if err return available
- errvar := ""
- for _, param := range out {
- p := parseParam(param)
- if p.Type == "error" {
- errvar = p.Name
- continue
- }
- }
-
- // Prepare arguments to Syscall.
- var args []string
- n := 0
- for _, param := range in {
- p := parseParam(param)
- if regexp.MustCompile(`^\*`).FindStringSubmatch(p.Type) != nil {
- args = append(args, "uintptr(unsafe.Pointer("+p.Name+"))")
- } else if p.Type == "string" && errvar != "" {
- text += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype)
- text += fmt.Sprintf("\t_p%d, %s = %s(%s)\n", n, errvar, strconvfunc, p.Name)
- text += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar)
- args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
- n++
- } else if p.Type == "string" {
- fmt.Fprintf(os.Stderr, path+":"+funct+" uses string arguments, but has no error return\n")
- text += fmt.Sprintf("\tvar _p%d %s\n", n, strconvtype)
- text += fmt.Sprintf("\t_p%d, _ = %s(%s)\n", n, strconvfunc, p.Name)
- args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
- n++
- } else if s := regexp.MustCompile(`^\[\](.*)`).FindStringSubmatch(p.Type); s != nil {
- // Convert slice into pointer, length.
- // Have to be careful not to take address of &a[0] if len == 0:
- // pass nil in that case.
- text += fmt.Sprintf("\tvar _p%d *%s\n", n, s[1])
- text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = &%s[0]\n\t}\n", p.Name, n, p.Name)
- args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n), fmt.Sprintf("uintptr(len(%s))", p.Name))
- n++
- } else if p.Type == "int64" && endianness != "" {
- if endianness == "big-endian" {
- args = append(args, fmt.Sprintf("uintptr(%s>>32)", p.Name), fmt.Sprintf("uintptr(%s)", p.Name))
- } else {
- args = append(args, fmt.Sprintf("uintptr(%s)", p.Name), fmt.Sprintf("uintptr(%s>>32)", p.Name))
- }
- } else if p.Type == "bool" {
- text += fmt.Sprintf("\tvar _p%d uint32\n", n)
- text += fmt.Sprintf("\tif %s {\n\t\t_p%d = 1\n\t} else {\n\t\t_p%d = 0\n\t}\n", p.Name, n, n)
- args = append(args, fmt.Sprintf("uintptr(_p%d)", n))
- n++
- } else {
- args = append(args, fmt.Sprintf("uintptr(%s)", p.Name))
- }
- }
- nargs := len(args)
-
- // Determine which form to use; pad args with zeros.
- asm := "sysvicall6"
- if nonblock != nil {
- asm = "rawSysvicall6"
- }
- if len(args) <= 6 {
- for len(args) < 6 {
- args = append(args, "0")
- }
- } else {
- fmt.Fprintf(os.Stderr, "%s: too many arguments to system call\n", path)
- os.Exit(1)
- }
-
- // Actual call.
- arglist := strings.Join(args, ", ")
- call := fmt.Sprintf("%s(uintptr(unsafe.Pointer(&%s)), %d, %s)", asm, sysvarname, nargs, arglist)
-
- // Assign return values.
- body := ""
- ret := []string{"_", "_", "_"}
- doErrno := false
- for i := 0; i < len(out); i++ {
- p := parseParam(out[i])
- reg := ""
- if p.Name == "err" {
- reg = "e1"
- ret[2] = reg
- doErrno = true
- } else {
- reg = fmt.Sprintf("r%d", i)
- ret[i] = reg
- }
- if p.Type == "bool" {
- reg = fmt.Sprintf("%d != 0", reg)
- }
- if p.Type == "int64" && endianness != "" {
- // 64-bit number in r1:r0 or r0:r1.
- if i+2 > len(out) {
- fmt.Fprintf(os.Stderr, "%s: not enough registers for int64 return\n", path)
- os.Exit(1)
- }
- if endianness == "big-endian" {
- reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i, i+1)
- } else {
- reg = fmt.Sprintf("int64(r%d)<<32 | int64(r%d)", i+1, i)
- }
- ret[i] = fmt.Sprintf("r%d", i)
- ret[i+1] = fmt.Sprintf("r%d", i+1)
- }
- if reg != "e1" {
- body += fmt.Sprintf("\t%s = %s(%s)\n", p.Name, p.Type, reg)
- }
- }
- if ret[0] == "_" && ret[1] == "_" && ret[2] == "_" {
- text += fmt.Sprintf("\t%s\n", call)
- } else {
- text += fmt.Sprintf("\t%s, %s, %s := %s\n", ret[0], ret[1], ret[2], call)
- }
- text += body
-
- if doErrno {
- text += "\tif e1 != 0 {\n"
- text += "\t\terr = e1\n"
- text += "\t}\n"
- }
- text += "\treturn\n"
- text += "}\n"
- }
- if err := s.Err(); err != nil {
- fmt.Fprintf(os.Stderr, err.Error())
- os.Exit(1)
- }
- file.Close()
- }
- imp := ""
- if pack != "unix" {
- imp = "import \"golang.org/x/sys/unix\"\n"
-
- }
- vardecls := "\t" + strings.Join(vars, ",\n\t")
- vardecls += " syscallFunc"
- fmt.Printf(srcTemplate, cmdLine(), buildTags(), pack, imp, dynimports, linknames, vardecls, text)
-}
-
-const srcTemplate = `// %s
-// Code generated by the command above; see README.md. DO NOT EDIT.
-
-// +build %s
-
-package %s
-
-import (
- "syscall"
- "unsafe"
-)
-%s
-%s
-%s
-var (
-%s
-)
-
-%s
-`
diff --git a/vendor/golang.org/x/sys/unix/mksysnum.go b/vendor/golang.org/x/sys/unix/mksysnum.go
deleted file mode 100644
index 07f8960..0000000
--- a/vendor/golang.org/x/sys/unix/mksysnum.go
+++ /dev/null
@@ -1,190 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-// Generate system call table for DragonFly, NetBSD,
-// FreeBSD, OpenBSD or Darwin from master list
-// (for example, /usr/src/sys/kern/syscalls.master or
-// sys/syscall.h).
-package main
-
-import (
- "bufio"
- "fmt"
- "io"
- "io/ioutil"
- "net/http"
- "os"
- "regexp"
- "strings"
-)
-
-var (
- goos, goarch string
-)
-
-// cmdLine returns this programs's commandline arguments
-func cmdLine() string {
- return "go run mksysnum.go " + strings.Join(os.Args[1:], " ")
-}
-
-// buildTags returns build tags
-func buildTags() string {
- return fmt.Sprintf("%s,%s", goarch, goos)
-}
-
-func checkErr(err error) {
- if err != nil {
- fmt.Fprintf(os.Stderr, "%v\n", err)
- os.Exit(1)
- }
-}
-
-// source string and substring slice for regexp
-type re struct {
- str string // source string
- sub []string // matched sub-string
-}
-
-// Match performs regular expression match
-func (r *re) Match(exp string) bool {
- r.sub = regexp.MustCompile(exp).FindStringSubmatch(r.str)
- if r.sub != nil {
- return true
- }
- return false
-}
-
-// fetchFile fetches a text file from URL
-func fetchFile(URL string) io.Reader {
- resp, err := http.Get(URL)
- checkErr(err)
- defer resp.Body.Close()
- body, err := ioutil.ReadAll(resp.Body)
- checkErr(err)
- return strings.NewReader(string(body))
-}
-
-// readFile reads a text file from path
-func readFile(path string) io.Reader {
- file, err := os.Open(os.Args[1])
- checkErr(err)
- return file
-}
-
-func format(name, num, proto string) string {
- name = strings.ToUpper(name)
- // There are multiple entries for enosys and nosys, so comment them out.
- nm := re{str: name}
- if nm.Match(`^SYS_E?NOSYS$`) {
- name = fmt.Sprintf("// %s", name)
- }
- if name == `SYS_SYS_EXIT` {
- name = `SYS_EXIT`
- }
- return fmt.Sprintf(" %s = %s; // %s\n", name, num, proto)
-}
-
-func main() {
- // Get the OS (using GOOS_TARGET if it exist)
- goos = os.Getenv("GOOS_TARGET")
- if goos == "" {
- goos = os.Getenv("GOOS")
- }
- // Get the architecture (using GOARCH_TARGET if it exists)
- goarch = os.Getenv("GOARCH_TARGET")
- if goarch == "" {
- goarch = os.Getenv("GOARCH")
- }
- // Check if GOOS and GOARCH environment variables are defined
- if goarch == "" || goos == "" {
- fmt.Fprintf(os.Stderr, "GOARCH or GOOS not defined in environment\n")
- os.Exit(1)
- }
-
- file := strings.TrimSpace(os.Args[1])
- var syscalls io.Reader
- if strings.HasPrefix(file, "https://") || strings.HasPrefix(file, "http://") {
- // Download syscalls.master file
- syscalls = fetchFile(file)
- } else {
- syscalls = readFile(file)
- }
-
- var text, line string
- s := bufio.NewScanner(syscalls)
- for s.Scan() {
- t := re{str: line}
- if t.Match(`^(.*)\\$`) {
- // Handle continuation
- line = t.sub[1]
- line += strings.TrimLeft(s.Text(), " \t")
- } else {
- // New line
- line = s.Text()
- }
- t = re{str: line}
- if t.Match(`\\$`) {
- continue
- }
- t = re{str: line}
-
- switch goos {
- case "dragonfly":
- if t.Match(`^([0-9]+)\s+STD\s+({ \S+\s+(\w+).*)$`) {
- num, proto := t.sub[1], t.sub[2]
- name := fmt.Sprintf("SYS_%s", t.sub[3])
- text += format(name, num, proto)
- }
- case "freebsd":
- if t.Match(`^([0-9]+)\s+\S+\s+(?:NO)?STD\s+({ \S+\s+(\w+).*)$`) {
- num, proto := t.sub[1], t.sub[2]
- name := fmt.Sprintf("SYS_%s", t.sub[3])
- text += format(name, num, proto)
- }
- case "openbsd":
- if t.Match(`^([0-9]+)\s+STD\s+(NOLOCK\s+)?({ \S+\s+\*?(\w+).*)$`) {
- num, proto, name := t.sub[1], t.sub[3], t.sub[4]
- text += format(name, num, proto)
- }
- case "netbsd":
- if t.Match(`^([0-9]+)\s+((STD)|(NOERR))\s+(RUMP\s+)?({\s+\S+\s*\*?\s*\|(\S+)\|(\S*)\|(\w+).*\s+})(\s+(\S+))?$`) {
- num, proto, compat := t.sub[1], t.sub[6], t.sub[8]
- name := t.sub[7] + "_" + t.sub[9]
- if t.sub[11] != "" {
- name = t.sub[7] + "_" + t.sub[11]
- }
- name = strings.ToUpper(name)
- if compat == "" || compat == "13" || compat == "30" || compat == "50" {
- text += fmt.Sprintf(" %s = %s; // %s\n", name, num, proto)
- }
- }
- case "darwin":
- if t.Match(`^#define\s+SYS_(\w+)\s+([0-9]+)`) {
- name, num := t.sub[1], t.sub[2]
- name = strings.ToUpper(name)
- text += fmt.Sprintf(" SYS_%s = %s;\n", name, num)
- }
- default:
- fmt.Fprintf(os.Stderr, "unrecognized GOOS=%s\n", goos)
- os.Exit(1)
-
- }
- }
- err := s.Err()
- checkErr(err)
-
- fmt.Printf(template, cmdLine(), buildTags(), text)
-}
-
-const template = `// %s
-// Code generated by the command above; see README.md. DO NOT EDIT.
-
-// +build %s
-
-package unix
-
-const(
-%s)`
diff --git a/vendor/golang.org/x/sys/unix/types_aix.go b/vendor/golang.org/x/sys/unix/types_aix.go
deleted file mode 100644
index 25e8349..0000000
--- a/vendor/golang.org/x/sys/unix/types_aix.go
+++ /dev/null
@@ -1,236 +0,0 @@
-// Copyright 2018 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-// +build aix
-
-/*
-Input to cgo -godefs. See also mkerrors.sh and mkall.sh
-*/
-
-// +godefs map struct_in_addr [4]byte /* in_addr */
-// +godefs map struct_in6_addr [16]byte /* in6_addr */
-
-package unix
-
-/*
-#include <sys/types.h>
-#include <sys/time.h>
-#include <sys/limits.h>
-#include <sys/un.h>
-#include <utime.h>
-#include <sys/utsname.h>
-#include <sys/poll.h>
-#include <sys/resource.h>
-#include <sys/stat.h>
-#include <sys/statfs.h>
-#include <sys/termio.h>
-#include <sys/ioctl.h>
-
-#include <termios.h>
-
-#include <net/if.h>
-#include <net/if_dl.h>
-#include <netinet/in.h>
-#include <netinet/icmp6.h>
-
-
-#include <dirent.h>
-#include <fcntl.h>
-
-enum {
- sizeofPtr = sizeof(void*),
-};
-
-union sockaddr_all {
- struct sockaddr s1; // this one gets used for fields
- struct sockaddr_in s2; // these pad it out
- struct sockaddr_in6 s3;
- struct sockaddr_un s4;
- struct sockaddr_dl s5;
-};
-
-struct sockaddr_any {
- struct sockaddr addr;
- char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)];
-};
-
-*/
-import "C"
-
-// Machine characteristics
-
-const (
- SizeofPtr = C.sizeofPtr
- SizeofShort = C.sizeof_short
- SizeofInt = C.sizeof_int
- SizeofLong = C.sizeof_long
- SizeofLongLong = C.sizeof_longlong
- PathMax = C.PATH_MAX
-)
-
-// Basic types
-
-type (
- _C_short C.short
- _C_int C.int
- _C_long C.long
- _C_long_long C.longlong
-)
-
-type off64 C.off64_t
-type off C.off_t
-type Mode_t C.mode_t
-
-// Time
-
-type Timespec C.struct_timespec
-
-type StTimespec C.struct_st_timespec
-
-type Timeval C.struct_timeval
-
-type Timeval32 C.struct_timeval32
-
-type Timex C.struct_timex
-
-type Time_t C.time_t
-
-type Tms C.struct_tms
-
-type Utimbuf C.struct_utimbuf
-
-type Timezone C.struct_timezone
-
-// Processes
-
-type Rusage C.struct_rusage
-
-type Rlimit C.struct_rlimit64
-
-type Pid_t C.pid_t
-
-type _Gid_t C.gid_t
-
-type dev_t C.dev_t
-
-// Files
-
-type Stat_t C.struct_stat
-
-type StatxTimestamp C.struct_statx_timestamp
-
-type Statx_t C.struct_statx
-
-type Dirent C.struct_dirent
-
-// Sockets
-
-type RawSockaddrInet4 C.struct_sockaddr_in
-
-type RawSockaddrInet6 C.struct_sockaddr_in6
-
-type RawSockaddrUnix C.struct_sockaddr_un
-
-type RawSockaddr C.struct_sockaddr
-
-type RawSockaddrAny C.struct_sockaddr_any
-
-type _Socklen C.socklen_t
-
-type Cmsghdr C.struct_cmsghdr
-
-type ICMPv6Filter C.struct_icmp6_filter
-
-type Iovec C.struct_iovec
-
-type IPMreq C.struct_ip_mreq
-
-type IPv6Mreq C.struct_ipv6_mreq
-
-type IPv6MTUInfo C.struct_ip6_mtuinfo
-
-type Linger C.struct_linger
-
-type Msghdr C.struct_msghdr
-
-const (
- SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in
- SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
- SizeofSockaddrAny = C.sizeof_struct_sockaddr_any
- SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un
- SizeofLinger = C.sizeof_struct_linger
- SizeofIPMreq = C.sizeof_struct_ip_mreq
- SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq
- SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo
- SizeofMsghdr = C.sizeof_struct_msghdr
- SizeofCmsghdr = C.sizeof_struct_cmsghdr
- SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter
-)
-
-// Routing and interface messages
-
-const (
- SizeofIfMsghdr = C.sizeof_struct_if_msghdr
-)
-
-type IfMsgHdr C.struct_if_msghdr
-
-// Misc
-
-type FdSet C.fd_set
-
-type Utsname C.struct_utsname
-
-type Ustat_t C.struct_ustat
-
-type Sigset_t C.sigset_t
-
-const (
- AT_FDCWD = C.AT_FDCWD
- AT_REMOVEDIR = C.AT_REMOVEDIR
- AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW
-)
-
-// Terminal handling
-
-type Termios C.struct_termios
-
-type Termio C.struct_termio
-
-type Winsize C.struct_winsize
-
-//poll
-
-type PollFd struct {
- Fd int32
- Events uint16
- Revents uint16
-}
-
-const (
- POLLERR = C.POLLERR
- POLLHUP = C.POLLHUP
- POLLIN = C.POLLIN
- POLLNVAL = C.POLLNVAL
- POLLOUT = C.POLLOUT
- POLLPRI = C.POLLPRI
- POLLRDBAND = C.POLLRDBAND
- POLLRDNORM = C.POLLRDNORM
- POLLWRBAND = C.POLLWRBAND
- POLLWRNORM = C.POLLWRNORM
-)
-
-//flock_t
-
-type Flock_t C.struct_flock64
-
-// Statfs
-
-type Fsid_t C.struct_fsid_t
-type Fsid64_t C.struct_fsid64_t
-
-type Statfs_t C.struct_statfs
-
-const RNDGETENTCNT = 0x80045200
diff --git a/vendor/golang.org/x/sys/unix/types_darwin.go b/vendor/golang.org/x/sys/unix/types_darwin.go
deleted file mode 100644
index 155c2e6..0000000
--- a/vendor/golang.org/x/sys/unix/types_darwin.go
+++ /dev/null
@@ -1,283 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-/*
-Input to cgo -godefs. See README.md
-*/
-
-// +godefs map struct_in_addr [4]byte /* in_addr */
-// +godefs map struct_in6_addr [16]byte /* in6_addr */
-
-package unix
-
-/*
-#define __DARWIN_UNIX03 0
-#define KERNEL
-#define _DARWIN_USE_64_BIT_INODE
-#include <dirent.h>
-#include <fcntl.h>
-#include <poll.h>
-#include <signal.h>
-#include <termios.h>
-#include <unistd.h>
-#include <mach/mach.h>
-#include <mach/message.h>
-#include <sys/event.h>
-#include <sys/mman.h>
-#include <sys/mount.h>
-#include <sys/param.h>
-#include <sys/ptrace.h>
-#include <sys/resource.h>
-#include <sys/select.h>
-#include <sys/signal.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <sys/uio.h>
-#include <sys/un.h>
-#include <sys/utsname.h>
-#include <sys/wait.h>
-#include <net/bpf.h>
-#include <net/if.h>
-#include <net/if_dl.h>
-#include <net/if_var.h>
-#include <net/route.h>
-#include <netinet/in.h>
-#include <netinet/icmp6.h>
-#include <netinet/tcp.h>
-
-enum {
- sizeofPtr = sizeof(void*),
-};
-
-union sockaddr_all {
- struct sockaddr s1; // this one gets used for fields
- struct sockaddr_in s2; // these pad it out
- struct sockaddr_in6 s3;
- struct sockaddr_un s4;
- struct sockaddr_dl s5;
-};
-
-struct sockaddr_any {
- struct sockaddr addr;
- char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)];
-};
-
-*/
-import "C"
-
-// Machine characteristics
-
-const (
- SizeofPtr = C.sizeofPtr
- SizeofShort = C.sizeof_short
- SizeofInt = C.sizeof_int
- SizeofLong = C.sizeof_long
- SizeofLongLong = C.sizeof_longlong
-)
-
-// Basic types
-
-type (
- _C_short C.short
- _C_int C.int
- _C_long C.long
- _C_long_long C.longlong
-)
-
-// Time
-
-type Timespec C.struct_timespec
-
-type Timeval C.struct_timeval
-
-type Timeval32 C.struct_timeval32
-
-// Processes
-
-type Rusage C.struct_rusage
-
-type Rlimit C.struct_rlimit
-
-type _Gid_t C.gid_t
-
-// Files
-
-type Stat_t C.struct_stat64
-
-type Statfs_t C.struct_statfs64
-
-type Flock_t C.struct_flock
-
-type Fstore_t C.struct_fstore
-
-type Radvisory_t C.struct_radvisory
-
-type Fbootstraptransfer_t C.struct_fbootstraptransfer
-
-type Log2phys_t C.struct_log2phys
-
-type Fsid C.struct_fsid
-
-type Dirent C.struct_dirent
-
-// Sockets
-
-type RawSockaddrInet4 C.struct_sockaddr_in
-
-type RawSockaddrInet6 C.struct_sockaddr_in6
-
-type RawSockaddrUnix C.struct_sockaddr_un
-
-type RawSockaddrDatalink C.struct_sockaddr_dl
-
-type RawSockaddr C.struct_sockaddr
-
-type RawSockaddrAny C.struct_sockaddr_any
-
-type _Socklen C.socklen_t
-
-type Linger C.struct_linger
-
-type Iovec C.struct_iovec
-
-type IPMreq C.struct_ip_mreq
-
-type IPv6Mreq C.struct_ipv6_mreq
-
-type Msghdr C.struct_msghdr
-
-type Cmsghdr C.struct_cmsghdr
-
-type Inet4Pktinfo C.struct_in_pktinfo
-
-type Inet6Pktinfo C.struct_in6_pktinfo
-
-type IPv6MTUInfo C.struct_ip6_mtuinfo
-
-type ICMPv6Filter C.struct_icmp6_filter
-
-const (
- SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in
- SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
- SizeofSockaddrAny = C.sizeof_struct_sockaddr_any
- SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un
- SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl
- SizeofLinger = C.sizeof_struct_linger
- SizeofIPMreq = C.sizeof_struct_ip_mreq
- SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq
- SizeofMsghdr = C.sizeof_struct_msghdr
- SizeofCmsghdr = C.sizeof_struct_cmsghdr
- SizeofInet4Pktinfo = C.sizeof_struct_in_pktinfo
- SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo
- SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo
- SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter
-)
-
-// Ptrace requests
-
-const (
- PTRACE_TRACEME = C.PT_TRACE_ME
- PTRACE_CONT = C.PT_CONTINUE
- PTRACE_KILL = C.PT_KILL
-)
-
-// Events (kqueue, kevent)
-
-type Kevent_t C.struct_kevent
-
-// Select
-
-type FdSet C.fd_set
-
-// Routing and interface messages
-
-const (
- SizeofIfMsghdr = C.sizeof_struct_if_msghdr
- SizeofIfData = C.sizeof_struct_if_data
- SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr
- SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr
- SizeofIfmaMsghdr2 = C.sizeof_struct_ifma_msghdr2
- SizeofRtMsghdr = C.sizeof_struct_rt_msghdr
- SizeofRtMetrics = C.sizeof_struct_rt_metrics
-)
-
-type IfMsghdr C.struct_if_msghdr
-
-type IfData C.struct_if_data
-
-type IfaMsghdr C.struct_ifa_msghdr
-
-type IfmaMsghdr C.struct_ifma_msghdr
-
-type IfmaMsghdr2 C.struct_ifma_msghdr2
-
-type RtMsghdr C.struct_rt_msghdr
-
-type RtMetrics C.struct_rt_metrics
-
-// Berkeley packet filter
-
-const (
- SizeofBpfVersion = C.sizeof_struct_bpf_version
- SizeofBpfStat = C.sizeof_struct_bpf_stat
- SizeofBpfProgram = C.sizeof_struct_bpf_program
- SizeofBpfInsn = C.sizeof_struct_bpf_insn
- SizeofBpfHdr = C.sizeof_struct_bpf_hdr
-)
-
-type BpfVersion C.struct_bpf_version
-
-type BpfStat C.struct_bpf_stat
-
-type BpfProgram C.struct_bpf_program
-
-type BpfInsn C.struct_bpf_insn
-
-type BpfHdr C.struct_bpf_hdr
-
-// Terminal handling
-
-type Termios C.struct_termios
-
-type Winsize C.struct_winsize
-
-// fchmodat-like syscalls.
-
-const (
- AT_FDCWD = C.AT_FDCWD
- AT_REMOVEDIR = C.AT_REMOVEDIR
- AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW
- AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW
-)
-
-// poll
-
-type PollFd C.struct_pollfd
-
-const (
- POLLERR = C.POLLERR
- POLLHUP = C.POLLHUP
- POLLIN = C.POLLIN
- POLLNVAL = C.POLLNVAL
- POLLOUT = C.POLLOUT
- POLLPRI = C.POLLPRI
- POLLRDBAND = C.POLLRDBAND
- POLLRDNORM = C.POLLRDNORM
- POLLWRBAND = C.POLLWRBAND
- POLLWRNORM = C.POLLWRNORM
-)
-
-// uname
-
-type Utsname C.struct_utsname
-
-// Clockinfo
-
-const SizeofClockinfo = C.sizeof_struct_clockinfo
-
-type Clockinfo C.struct_clockinfo
diff --git a/vendor/golang.org/x/sys/unix/types_dragonfly.go b/vendor/golang.org/x/sys/unix/types_dragonfly.go
deleted file mode 100644
index 3365dd7..0000000
--- a/vendor/golang.org/x/sys/unix/types_dragonfly.go
+++ /dev/null
@@ -1,263 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-/*
-Input to cgo -godefs. See README.md
-*/
-
-// +godefs map struct_in_addr [4]byte /* in_addr */
-// +godefs map struct_in6_addr [16]byte /* in6_addr */
-
-package unix
-
-/*
-#define KERNEL
-#include <dirent.h>
-#include <fcntl.h>
-#include <poll.h>
-#include <signal.h>
-#include <termios.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/event.h>
-#include <sys/mman.h>
-#include <sys/mount.h>
-#include <sys/param.h>
-#include <sys/ptrace.h>
-#include <sys/resource.h>
-#include <sys/select.h>
-#include <sys/signal.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <sys/un.h>
-#include <sys/utsname.h>
-#include <sys/wait.h>
-#include <net/bpf.h>
-#include <net/if.h>
-#include <net/if_dl.h>
-#include <net/route.h>
-#include <netinet/in.h>
-#include <netinet/icmp6.h>
-#include <netinet/tcp.h>
-
-enum {
- sizeofPtr = sizeof(void*),
-};
-
-union sockaddr_all {
- struct sockaddr s1; // this one gets used for fields
- struct sockaddr_in s2; // these pad it out
- struct sockaddr_in6 s3;
- struct sockaddr_un s4;
- struct sockaddr_dl s5;
-};
-
-struct sockaddr_any {
- struct sockaddr addr;
- char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)];
-};
-
-*/
-import "C"
-
-// Machine characteristics
-
-const (
- SizeofPtr = C.sizeofPtr
- SizeofShort = C.sizeof_short
- SizeofInt = C.sizeof_int
- SizeofLong = C.sizeof_long
- SizeofLongLong = C.sizeof_longlong
-)
-
-// Basic types
-
-type (
- _C_short C.short
- _C_int C.int
- _C_long C.long
- _C_long_long C.longlong
-)
-
-// Time
-
-type Timespec C.struct_timespec
-
-type Timeval C.struct_timeval
-
-// Processes
-
-type Rusage C.struct_rusage
-
-type Rlimit C.struct_rlimit
-
-type _Gid_t C.gid_t
-
-// Files
-
-type Stat_t C.struct_stat
-
-type Statfs_t C.struct_statfs
-
-type Flock_t C.struct_flock
-
-type Dirent C.struct_dirent
-
-type Fsid C.struct_fsid
-
-// File system limits
-
-const (
- PathMax = C.PATH_MAX
-)
-
-// Sockets
-
-type RawSockaddrInet4 C.struct_sockaddr_in
-
-type RawSockaddrInet6 C.struct_sockaddr_in6
-
-type RawSockaddrUnix C.struct_sockaddr_un
-
-type RawSockaddrDatalink C.struct_sockaddr_dl
-
-type RawSockaddr C.struct_sockaddr
-
-type RawSockaddrAny C.struct_sockaddr_any
-
-type _Socklen C.socklen_t
-
-type Linger C.struct_linger
-
-type Iovec C.struct_iovec
-
-type IPMreq C.struct_ip_mreq
-
-type IPv6Mreq C.struct_ipv6_mreq
-
-type Msghdr C.struct_msghdr
-
-type Cmsghdr C.struct_cmsghdr
-
-type Inet6Pktinfo C.struct_in6_pktinfo
-
-type IPv6MTUInfo C.struct_ip6_mtuinfo
-
-type ICMPv6Filter C.struct_icmp6_filter
-
-const (
- SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in
- SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
- SizeofSockaddrAny = C.sizeof_struct_sockaddr_any
- SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un
- SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl
- SizeofLinger = C.sizeof_struct_linger
- SizeofIPMreq = C.sizeof_struct_ip_mreq
- SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq
- SizeofMsghdr = C.sizeof_struct_msghdr
- SizeofCmsghdr = C.sizeof_struct_cmsghdr
- SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo
- SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo
- SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter
-)
-
-// Ptrace requests
-
-const (
- PTRACE_TRACEME = C.PT_TRACE_ME
- PTRACE_CONT = C.PT_CONTINUE
- PTRACE_KILL = C.PT_KILL
-)
-
-// Events (kqueue, kevent)
-
-type Kevent_t C.struct_kevent
-
-// Select
-
-type FdSet C.fd_set
-
-// Routing and interface messages
-
-const (
- SizeofIfMsghdr = C.sizeof_struct_if_msghdr
- SizeofIfData = C.sizeof_struct_if_data
- SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr
- SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr
- SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr
- SizeofRtMsghdr = C.sizeof_struct_rt_msghdr
- SizeofRtMetrics = C.sizeof_struct_rt_metrics
-)
-
-type IfMsghdr C.struct_if_msghdr
-
-type IfData C.struct_if_data
-
-type IfaMsghdr C.struct_ifa_msghdr
-
-type IfmaMsghdr C.struct_ifma_msghdr
-
-type IfAnnounceMsghdr C.struct_if_announcemsghdr
-
-type RtMsghdr C.struct_rt_msghdr
-
-type RtMetrics C.struct_rt_metrics
-
-// Berkeley packet filter
-
-const (
- SizeofBpfVersion = C.sizeof_struct_bpf_version
- SizeofBpfStat = C.sizeof_struct_bpf_stat
- SizeofBpfProgram = C.sizeof_struct_bpf_program
- SizeofBpfInsn = C.sizeof_struct_bpf_insn
- SizeofBpfHdr = C.sizeof_struct_bpf_hdr
-)
-
-type BpfVersion C.struct_bpf_version
-
-type BpfStat C.struct_bpf_stat
-
-type BpfProgram C.struct_bpf_program
-
-type BpfInsn C.struct_bpf_insn
-
-type BpfHdr C.struct_bpf_hdr
-
-// Terminal handling
-
-type Termios C.struct_termios
-
-type Winsize C.struct_winsize
-
-// fchmodat-like syscalls.
-
-const (
- AT_FDCWD = C.AT_FDCWD
- AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW
-)
-
-// poll
-
-type PollFd C.struct_pollfd
-
-const (
- POLLERR = C.POLLERR
- POLLHUP = C.POLLHUP
- POLLIN = C.POLLIN
- POLLNVAL = C.POLLNVAL
- POLLOUT = C.POLLOUT
- POLLPRI = C.POLLPRI
- POLLRDBAND = C.POLLRDBAND
- POLLRDNORM = C.POLLRDNORM
- POLLWRBAND = C.POLLWRBAND
- POLLWRNORM = C.POLLWRNORM
-)
-
-// Uname
-
-type Utsname C.struct_utsname
diff --git a/vendor/golang.org/x/sys/unix/types_freebsd.go b/vendor/golang.org/x/sys/unix/types_freebsd.go
deleted file mode 100644
index 7470798..0000000
--- a/vendor/golang.org/x/sys/unix/types_freebsd.go
+++ /dev/null
@@ -1,356 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-/*
-Input to cgo -godefs. See README.md
-*/
-
-// +godefs map struct_in_addr [4]byte /* in_addr */
-// +godefs map struct_in6_addr [16]byte /* in6_addr */
-
-package unix
-
-/*
-#define _WANT_FREEBSD11_STAT 1
-#define _WANT_FREEBSD11_STATFS 1
-#define _WANT_FREEBSD11_DIRENT 1
-#define _WANT_FREEBSD11_KEVENT 1
-
-#include <dirent.h>
-#include <fcntl.h>
-#include <poll.h>
-#include <signal.h>
-#include <termios.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/capsicum.h>
-#include <sys/event.h>
-#include <sys/mman.h>
-#include <sys/mount.h>
-#include <sys/param.h>
-#include <sys/ptrace.h>
-#include <sys/resource.h>
-#include <sys/select.h>
-#include <sys/signal.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <sys/un.h>
-#include <sys/utsname.h>
-#include <sys/wait.h>
-#include <net/bpf.h>
-#include <net/if.h>
-#include <net/if_dl.h>
-#include <net/route.h>
-#include <netinet/in.h>
-#include <netinet/icmp6.h>
-#include <netinet/tcp.h>
-
-enum {
- sizeofPtr = sizeof(void*),
-};
-
-union sockaddr_all {
- struct sockaddr s1; // this one gets used for fields
- struct sockaddr_in s2; // these pad it out
- struct sockaddr_in6 s3;
- struct sockaddr_un s4;
- struct sockaddr_dl s5;
-};
-
-struct sockaddr_any {
- struct sockaddr addr;
- char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)];
-};
-
-// This structure is a duplicate of if_data on FreeBSD 8-STABLE.
-// See /usr/include/net/if.h.
-struct if_data8 {
- u_char ifi_type;
- u_char ifi_physical;
- u_char ifi_addrlen;
- u_char ifi_hdrlen;
- u_char ifi_link_state;
- u_char ifi_spare_char1;
- u_char ifi_spare_char2;
- u_char ifi_datalen;
- u_long ifi_mtu;
- u_long ifi_metric;
- u_long ifi_baudrate;
- u_long ifi_ipackets;
- u_long ifi_ierrors;
- u_long ifi_opackets;
- u_long ifi_oerrors;
- u_long ifi_collisions;
- u_long ifi_ibytes;
- u_long ifi_obytes;
- u_long ifi_imcasts;
- u_long ifi_omcasts;
- u_long ifi_iqdrops;
- u_long ifi_noproto;
- u_long ifi_hwassist;
-// FIXME: these are now unions, so maybe need to change definitions?
-#undef ifi_epoch
- time_t ifi_epoch;
-#undef ifi_lastchange
- struct timeval ifi_lastchange;
-};
-
-// This structure is a duplicate of if_msghdr on FreeBSD 8-STABLE.
-// See /usr/include/net/if.h.
-struct if_msghdr8 {
- u_short ifm_msglen;
- u_char ifm_version;
- u_char ifm_type;
- int ifm_addrs;
- int ifm_flags;
- u_short ifm_index;
- struct if_data8 ifm_data;
-};
-*/
-import "C"
-
-// Machine characteristics
-
-const (
- SizeofPtr = C.sizeofPtr
- SizeofShort = C.sizeof_short
- SizeofInt = C.sizeof_int
- SizeofLong = C.sizeof_long
- SizeofLongLong = C.sizeof_longlong
-)
-
-// Basic types
-
-type (
- _C_short C.short
- _C_int C.int
- _C_long C.long
- _C_long_long C.longlong
-)
-
-// Time
-
-type Timespec C.struct_timespec
-
-type Timeval C.struct_timeval
-
-// Processes
-
-type Rusage C.struct_rusage
-
-type Rlimit C.struct_rlimit
-
-type _Gid_t C.gid_t
-
-// Files
-
-const (
- _statfsVersion = C.STATFS_VERSION
- _dirblksiz = C.DIRBLKSIZ
-)
-
-type Stat_t C.struct_stat
-
-type stat_freebsd11_t C.struct_freebsd11_stat
-
-type Statfs_t C.struct_statfs
-
-type statfs_freebsd11_t C.struct_freebsd11_statfs
-
-type Flock_t C.struct_flock
-
-type Dirent C.struct_dirent
-
-type dirent_freebsd11 C.struct_freebsd11_dirent
-
-type Fsid C.struct_fsid
-
-// File system limits
-
-const (
- PathMax = C.PATH_MAX
-)
-
-// Advice to Fadvise
-
-const (
- FADV_NORMAL = C.POSIX_FADV_NORMAL
- FADV_RANDOM = C.POSIX_FADV_RANDOM
- FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL
- FADV_WILLNEED = C.POSIX_FADV_WILLNEED
- FADV_DONTNEED = C.POSIX_FADV_DONTNEED
- FADV_NOREUSE = C.POSIX_FADV_NOREUSE
-)
-
-// Sockets
-
-type RawSockaddrInet4 C.struct_sockaddr_in
-
-type RawSockaddrInet6 C.struct_sockaddr_in6
-
-type RawSockaddrUnix C.struct_sockaddr_un
-
-type RawSockaddrDatalink C.struct_sockaddr_dl
-
-type RawSockaddr C.struct_sockaddr
-
-type RawSockaddrAny C.struct_sockaddr_any
-
-type _Socklen C.socklen_t
-
-type Linger C.struct_linger
-
-type Iovec C.struct_iovec
-
-type IPMreq C.struct_ip_mreq
-
-type IPMreqn C.struct_ip_mreqn
-
-type IPv6Mreq C.struct_ipv6_mreq
-
-type Msghdr C.struct_msghdr
-
-type Cmsghdr C.struct_cmsghdr
-
-type Inet6Pktinfo C.struct_in6_pktinfo
-
-type IPv6MTUInfo C.struct_ip6_mtuinfo
-
-type ICMPv6Filter C.struct_icmp6_filter
-
-const (
- SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in
- SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
- SizeofSockaddrAny = C.sizeof_struct_sockaddr_any
- SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un
- SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl
- SizeofLinger = C.sizeof_struct_linger
- SizeofIPMreq = C.sizeof_struct_ip_mreq
- SizeofIPMreqn = C.sizeof_struct_ip_mreqn
- SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq
- SizeofMsghdr = C.sizeof_struct_msghdr
- SizeofCmsghdr = C.sizeof_struct_cmsghdr
- SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo
- SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo
- SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter
-)
-
-// Ptrace requests
-
-const (
- PTRACE_TRACEME = C.PT_TRACE_ME
- PTRACE_CONT = C.PT_CONTINUE
- PTRACE_KILL = C.PT_KILL
-)
-
-// Events (kqueue, kevent)
-
-type Kevent_t C.struct_kevent_freebsd11
-
-// Select
-
-type FdSet C.fd_set
-
-// Routing and interface messages
-
-const (
- sizeofIfMsghdr = C.sizeof_struct_if_msghdr
- SizeofIfMsghdr = C.sizeof_struct_if_msghdr8
- sizeofIfData = C.sizeof_struct_if_data
- SizeofIfData = C.sizeof_struct_if_data8
- SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr
- SizeofIfmaMsghdr = C.sizeof_struct_ifma_msghdr
- SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr
- SizeofRtMsghdr = C.sizeof_struct_rt_msghdr
- SizeofRtMetrics = C.sizeof_struct_rt_metrics
-)
-
-type ifMsghdr C.struct_if_msghdr
-
-type IfMsghdr C.struct_if_msghdr8
-
-type ifData C.struct_if_data
-
-type IfData C.struct_if_data8
-
-type IfaMsghdr C.struct_ifa_msghdr
-
-type IfmaMsghdr C.struct_ifma_msghdr
-
-type IfAnnounceMsghdr C.struct_if_announcemsghdr
-
-type RtMsghdr C.struct_rt_msghdr
-
-type RtMetrics C.struct_rt_metrics
-
-// Berkeley packet filter
-
-const (
- SizeofBpfVersion = C.sizeof_struct_bpf_version
- SizeofBpfStat = C.sizeof_struct_bpf_stat
- SizeofBpfZbuf = C.sizeof_struct_bpf_zbuf
- SizeofBpfProgram = C.sizeof_struct_bpf_program
- SizeofBpfInsn = C.sizeof_struct_bpf_insn
- SizeofBpfHdr = C.sizeof_struct_bpf_hdr
- SizeofBpfZbufHeader = C.sizeof_struct_bpf_zbuf_header
-)
-
-type BpfVersion C.struct_bpf_version
-
-type BpfStat C.struct_bpf_stat
-
-type BpfZbuf C.struct_bpf_zbuf
-
-type BpfProgram C.struct_bpf_program
-
-type BpfInsn C.struct_bpf_insn
-
-type BpfHdr C.struct_bpf_hdr
-
-type BpfZbufHeader C.struct_bpf_zbuf_header
-
-// Terminal handling
-
-type Termios C.struct_termios
-
-type Winsize C.struct_winsize
-
-// fchmodat-like syscalls.
-
-const (
- AT_FDCWD = C.AT_FDCWD
- AT_REMOVEDIR = C.AT_REMOVEDIR
- AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW
- AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW
-)
-
-// poll
-
-type PollFd C.struct_pollfd
-
-const (
- POLLERR = C.POLLERR
- POLLHUP = C.POLLHUP
- POLLIN = C.POLLIN
- POLLINIGNEOF = C.POLLINIGNEOF
- POLLNVAL = C.POLLNVAL
- POLLOUT = C.POLLOUT
- POLLPRI = C.POLLPRI
- POLLRDBAND = C.POLLRDBAND
- POLLRDNORM = C.POLLRDNORM
- POLLWRBAND = C.POLLWRBAND
- POLLWRNORM = C.POLLWRNORM
-)
-
-// Capabilities
-
-type CapRights C.struct_cap_rights
-
-// Uname
-
-type Utsname C.struct_utsname
diff --git a/vendor/golang.org/x/sys/unix/types_netbsd.go b/vendor/golang.org/x/sys/unix/types_netbsd.go
deleted file mode 100644
index 2dd4f95..0000000
--- a/vendor/golang.org/x/sys/unix/types_netbsd.go
+++ /dev/null
@@ -1,289 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-/*
-Input to cgo -godefs. See README.md
-*/
-
-// +godefs map struct_in_addr [4]byte /* in_addr */
-// +godefs map struct_in6_addr [16]byte /* in6_addr */
-
-package unix
-
-/*
-#define KERNEL
-#include <dirent.h>
-#include <fcntl.h>
-#include <poll.h>
-#include <signal.h>
-#include <termios.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/event.h>
-#include <sys/mman.h>
-#include <sys/mount.h>
-#include <sys/ptrace.h>
-#include <sys/resource.h>
-#include <sys/select.h>
-#include <sys/signal.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/sysctl.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <sys/un.h>
-#include <sys/utsname.h>
-#include <sys/wait.h>
-#include <net/bpf.h>
-#include <net/if.h>
-#include <net/if_dl.h>
-#include <net/route.h>
-#include <netinet/in.h>
-#include <netinet/icmp6.h>
-#include <netinet/tcp.h>
-
-enum {
- sizeofPtr = sizeof(void*),
-};
-
-union sockaddr_all {
- struct sockaddr s1; // this one gets used for fields
- struct sockaddr_in s2; // these pad it out
- struct sockaddr_in6 s3;
- struct sockaddr_un s4;
- struct sockaddr_dl s5;
-};
-
-struct sockaddr_any {
- struct sockaddr addr;
- char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)];
-};
-
-*/
-import "C"
-
-// Machine characteristics
-
-const (
- SizeofPtr = C.sizeofPtr
- SizeofShort = C.sizeof_short
- SizeofInt = C.sizeof_int
- SizeofLong = C.sizeof_long
- SizeofLongLong = C.sizeof_longlong
-)
-
-// Basic types
-
-type (
- _C_short C.short
- _C_int C.int
- _C_long C.long
- _C_long_long C.longlong
-)
-
-// Time
-
-type Timespec C.struct_timespec
-
-type Timeval C.struct_timeval
-
-// Processes
-
-type Rusage C.struct_rusage
-
-type Rlimit C.struct_rlimit
-
-type _Gid_t C.gid_t
-
-// Files
-
-type Stat_t C.struct_stat
-
-type Statfs_t C.struct_statfs
-
-type Flock_t C.struct_flock
-
-type Dirent C.struct_dirent
-
-type Fsid C.fsid_t
-
-// File system limits
-
-const (
- PathMax = C.PATH_MAX
-)
-
-// Advice to Fadvise
-
-const (
- FADV_NORMAL = C.POSIX_FADV_NORMAL
- FADV_RANDOM = C.POSIX_FADV_RANDOM
- FADV_SEQUENTIAL = C.POSIX_FADV_SEQUENTIAL
- FADV_WILLNEED = C.POSIX_FADV_WILLNEED
- FADV_DONTNEED = C.POSIX_FADV_DONTNEED
- FADV_NOREUSE = C.POSIX_FADV_NOREUSE
-)
-
-// Sockets
-
-type RawSockaddrInet4 C.struct_sockaddr_in
-
-type RawSockaddrInet6 C.struct_sockaddr_in6
-
-type RawSockaddrUnix C.struct_sockaddr_un
-
-type RawSockaddrDatalink C.struct_sockaddr_dl
-
-type RawSockaddr C.struct_sockaddr
-
-type RawSockaddrAny C.struct_sockaddr_any
-
-type _Socklen C.socklen_t
-
-type Linger C.struct_linger
-
-type Iovec C.struct_iovec
-
-type IPMreq C.struct_ip_mreq
-
-type IPv6Mreq C.struct_ipv6_mreq
-
-type Msghdr C.struct_msghdr
-
-type Cmsghdr C.struct_cmsghdr
-
-type Inet6Pktinfo C.struct_in6_pktinfo
-
-type IPv6MTUInfo C.struct_ip6_mtuinfo
-
-type ICMPv6Filter C.struct_icmp6_filter
-
-const (
- SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in
- SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
- SizeofSockaddrAny = C.sizeof_struct_sockaddr_any
- SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un
- SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl
- SizeofLinger = C.sizeof_struct_linger
- SizeofIPMreq = C.sizeof_struct_ip_mreq
- SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq
- SizeofMsghdr = C.sizeof_struct_msghdr
- SizeofCmsghdr = C.sizeof_struct_cmsghdr
- SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo
- SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo
- SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter
-)
-
-// Ptrace requests
-
-const (
- PTRACE_TRACEME = C.PT_TRACE_ME
- PTRACE_CONT = C.PT_CONTINUE
- PTRACE_KILL = C.PT_KILL
-)
-
-// Events (kqueue, kevent)
-
-type Kevent_t C.struct_kevent
-
-// Select
-
-type FdSet C.fd_set
-
-// Routing and interface messages
-
-const (
- SizeofIfMsghdr = C.sizeof_struct_if_msghdr
- SizeofIfData = C.sizeof_struct_if_data
- SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr
- SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr
- SizeofRtMsghdr = C.sizeof_struct_rt_msghdr
- SizeofRtMetrics = C.sizeof_struct_rt_metrics
-)
-
-type IfMsghdr C.struct_if_msghdr
-
-type IfData C.struct_if_data
-
-type IfaMsghdr C.struct_ifa_msghdr
-
-type IfAnnounceMsghdr C.struct_if_announcemsghdr
-
-type RtMsghdr C.struct_rt_msghdr
-
-type RtMetrics C.struct_rt_metrics
-
-type Mclpool C.struct_mclpool
-
-// Berkeley packet filter
-
-const (
- SizeofBpfVersion = C.sizeof_struct_bpf_version
- SizeofBpfStat = C.sizeof_struct_bpf_stat
- SizeofBpfProgram = C.sizeof_struct_bpf_program
- SizeofBpfInsn = C.sizeof_struct_bpf_insn
- SizeofBpfHdr = C.sizeof_struct_bpf_hdr
-)
-
-type BpfVersion C.struct_bpf_version
-
-type BpfStat C.struct_bpf_stat
-
-type BpfProgram C.struct_bpf_program
-
-type BpfInsn C.struct_bpf_insn
-
-type BpfHdr C.struct_bpf_hdr
-
-type BpfTimeval C.struct_bpf_timeval
-
-// Terminal handling
-
-type Termios C.struct_termios
-
-type Winsize C.struct_winsize
-
-type Ptmget C.struct_ptmget
-
-// fchmodat-like syscalls.
-
-const (
- AT_FDCWD = C.AT_FDCWD
- AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW
-)
-
-// poll
-
-type PollFd C.struct_pollfd
-
-const (
- POLLERR = C.POLLERR
- POLLHUP = C.POLLHUP
- POLLIN = C.POLLIN
- POLLNVAL = C.POLLNVAL
- POLLOUT = C.POLLOUT
- POLLPRI = C.POLLPRI
- POLLRDBAND = C.POLLRDBAND
- POLLRDNORM = C.POLLRDNORM
- POLLWRBAND = C.POLLWRBAND
- POLLWRNORM = C.POLLWRNORM
-)
-
-// Sysctl
-
-type Sysctlnode C.struct_sysctlnode
-
-// Uname
-
-type Utsname C.struct_utsname
-
-// Clockinfo
-
-const SizeofClockinfo = C.sizeof_struct_clockinfo
-
-type Clockinfo C.struct_clockinfo
diff --git a/vendor/golang.org/x/sys/unix/types_openbsd.go b/vendor/golang.org/x/sys/unix/types_openbsd.go
deleted file mode 100644
index 8aafbe4..0000000
--- a/vendor/golang.org/x/sys/unix/types_openbsd.go
+++ /dev/null
@@ -1,282 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-/*
-Input to cgo -godefs. See README.md
-*/
-
-// +godefs map struct_in_addr [4]byte /* in_addr */
-// +godefs map struct_in6_addr [16]byte /* in6_addr */
-
-package unix
-
-/*
-#define KERNEL
-#include <dirent.h>
-#include <fcntl.h>
-#include <poll.h>
-#include <signal.h>
-#include <termios.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/param.h>
-#include <sys/types.h>
-#include <sys/event.h>
-#include <sys/mman.h>
-#include <sys/mount.h>
-#include <sys/ptrace.h>
-#include <sys/resource.h>
-#include <sys/select.h>
-#include <sys/signal.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/uio.h>
-#include <sys/un.h>
-#include <sys/utsname.h>
-#include <sys/wait.h>
-#include <uvm/uvmexp.h>
-#include <net/bpf.h>
-#include <net/if.h>
-#include <net/if_dl.h>
-#include <net/route.h>
-#include <netinet/in.h>
-#include <netinet/icmp6.h>
-#include <netinet/tcp.h>
-
-enum {
- sizeofPtr = sizeof(void*),
-};
-
-union sockaddr_all {
- struct sockaddr s1; // this one gets used for fields
- struct sockaddr_in s2; // these pad it out
- struct sockaddr_in6 s3;
- struct sockaddr_un s4;
- struct sockaddr_dl s5;
-};
-
-struct sockaddr_any {
- struct sockaddr addr;
- char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)];
-};
-
-*/
-import "C"
-
-// Machine characteristics
-
-const (
- SizeofPtr = C.sizeofPtr
- SizeofShort = C.sizeof_short
- SizeofInt = C.sizeof_int
- SizeofLong = C.sizeof_long
- SizeofLongLong = C.sizeof_longlong
-)
-
-// Basic types
-
-type (
- _C_short C.short
- _C_int C.int
- _C_long C.long
- _C_long_long C.longlong
-)
-
-// Time
-
-type Timespec C.struct_timespec
-
-type Timeval C.struct_timeval
-
-// Processes
-
-type Rusage C.struct_rusage
-
-type Rlimit C.struct_rlimit
-
-type _Gid_t C.gid_t
-
-// Files
-
-type Stat_t C.struct_stat
-
-type Statfs_t C.struct_statfs
-
-type Flock_t C.struct_flock
-
-type Dirent C.struct_dirent
-
-type Fsid C.fsid_t
-
-// File system limits
-
-const (
- PathMax = C.PATH_MAX
-)
-
-// Sockets
-
-type RawSockaddrInet4 C.struct_sockaddr_in
-
-type RawSockaddrInet6 C.struct_sockaddr_in6
-
-type RawSockaddrUnix C.struct_sockaddr_un
-
-type RawSockaddrDatalink C.struct_sockaddr_dl
-
-type RawSockaddr C.struct_sockaddr
-
-type RawSockaddrAny C.struct_sockaddr_any
-
-type _Socklen C.socklen_t
-
-type Linger C.struct_linger
-
-type Iovec C.struct_iovec
-
-type IPMreq C.struct_ip_mreq
-
-type IPv6Mreq C.struct_ipv6_mreq
-
-type Msghdr C.struct_msghdr
-
-type Cmsghdr C.struct_cmsghdr
-
-type Inet6Pktinfo C.struct_in6_pktinfo
-
-type IPv6MTUInfo C.struct_ip6_mtuinfo
-
-type ICMPv6Filter C.struct_icmp6_filter
-
-const (
- SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in
- SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
- SizeofSockaddrAny = C.sizeof_struct_sockaddr_any
- SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un
- SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl
- SizeofLinger = C.sizeof_struct_linger
- SizeofIPMreq = C.sizeof_struct_ip_mreq
- SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq
- SizeofMsghdr = C.sizeof_struct_msghdr
- SizeofCmsghdr = C.sizeof_struct_cmsghdr
- SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo
- SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo
- SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter
-)
-
-// Ptrace requests
-
-const (
- PTRACE_TRACEME = C.PT_TRACE_ME
- PTRACE_CONT = C.PT_CONTINUE
- PTRACE_KILL = C.PT_KILL
-)
-
-// Events (kqueue, kevent)
-
-type Kevent_t C.struct_kevent
-
-// Select
-
-type FdSet C.fd_set
-
-// Routing and interface messages
-
-const (
- SizeofIfMsghdr = C.sizeof_struct_if_msghdr
- SizeofIfData = C.sizeof_struct_if_data
- SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr
- SizeofIfAnnounceMsghdr = C.sizeof_struct_if_announcemsghdr
- SizeofRtMsghdr = C.sizeof_struct_rt_msghdr
- SizeofRtMetrics = C.sizeof_struct_rt_metrics
-)
-
-type IfMsghdr C.struct_if_msghdr
-
-type IfData C.struct_if_data
-
-type IfaMsghdr C.struct_ifa_msghdr
-
-type IfAnnounceMsghdr C.struct_if_announcemsghdr
-
-type RtMsghdr C.struct_rt_msghdr
-
-type RtMetrics C.struct_rt_metrics
-
-type Mclpool C.struct_mclpool
-
-// Berkeley packet filter
-
-const (
- SizeofBpfVersion = C.sizeof_struct_bpf_version
- SizeofBpfStat = C.sizeof_struct_bpf_stat
- SizeofBpfProgram = C.sizeof_struct_bpf_program
- SizeofBpfInsn = C.sizeof_struct_bpf_insn
- SizeofBpfHdr = C.sizeof_struct_bpf_hdr
-)
-
-type BpfVersion C.struct_bpf_version
-
-type BpfStat C.struct_bpf_stat
-
-type BpfProgram C.struct_bpf_program
-
-type BpfInsn C.struct_bpf_insn
-
-type BpfHdr C.struct_bpf_hdr
-
-type BpfTimeval C.struct_bpf_timeval
-
-// Terminal handling
-
-type Termios C.struct_termios
-
-type Winsize C.struct_winsize
-
-// fchmodat-like syscalls.
-
-const (
- AT_FDCWD = C.AT_FDCWD
- AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW
-)
-
-// poll
-
-type PollFd C.struct_pollfd
-
-const (
- POLLERR = C.POLLERR
- POLLHUP = C.POLLHUP
- POLLIN = C.POLLIN
- POLLNVAL = C.POLLNVAL
- POLLOUT = C.POLLOUT
- POLLPRI = C.POLLPRI
- POLLRDBAND = C.POLLRDBAND
- POLLRDNORM = C.POLLRDNORM
- POLLWRBAND = C.POLLWRBAND
- POLLWRNORM = C.POLLWRNORM
-)
-
-// Signal Sets
-
-type Sigset_t C.sigset_t
-
-// Uname
-
-type Utsname C.struct_utsname
-
-// Uvmexp
-
-const SizeofUvmexp = C.sizeof_struct_uvmexp
-
-type Uvmexp C.struct_uvmexp
-
-// Clockinfo
-
-const SizeofClockinfo = C.sizeof_struct_clockinfo
-
-type Clockinfo C.struct_clockinfo
diff --git a/vendor/golang.org/x/sys/unix/types_solaris.go b/vendor/golang.org/x/sys/unix/types_solaris.go
deleted file mode 100644
index 2b716f9..0000000
--- a/vendor/golang.org/x/sys/unix/types_solaris.go
+++ /dev/null
@@ -1,266 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-/*
-Input to cgo -godefs. See README.md
-*/
-
-// +godefs map struct_in_addr [4]byte /* in_addr */
-// +godefs map struct_in6_addr [16]byte /* in6_addr */
-
-package unix
-
-/*
-#define KERNEL
-// These defines ensure that builds done on newer versions of Solaris are
-// backwards-compatible with older versions of Solaris and
-// OpenSolaris-based derivatives.
-#define __USE_SUNOS_SOCKETS__ // msghdr
-#define __USE_LEGACY_PROTOTYPES__ // iovec
-#include <dirent.h>
-#include <fcntl.h>
-#include <netdb.h>
-#include <limits.h>
-#include <poll.h>
-#include <signal.h>
-#include <termios.h>
-#include <termio.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <sys/mman.h>
-#include <sys/mount.h>
-#include <sys/param.h>
-#include <sys/resource.h>
-#include <sys/select.h>
-#include <sys/signal.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include <sys/statvfs.h>
-#include <sys/time.h>
-#include <sys/times.h>
-#include <sys/types.h>
-#include <sys/utsname.h>
-#include <sys/un.h>
-#include <sys/wait.h>
-#include <net/bpf.h>
-#include <net/if.h>
-#include <net/if_dl.h>
-#include <net/route.h>
-#include <netinet/in.h>
-#include <netinet/icmp6.h>
-#include <netinet/tcp.h>
-#include <ustat.h>
-#include <utime.h>
-
-enum {
- sizeofPtr = sizeof(void*),
-};
-
-union sockaddr_all {
- struct sockaddr s1; // this one gets used for fields
- struct sockaddr_in s2; // these pad it out
- struct sockaddr_in6 s3;
- struct sockaddr_un s4;
- struct sockaddr_dl s5;
-};
-
-struct sockaddr_any {
- struct sockaddr addr;
- char pad[sizeof(union sockaddr_all) - sizeof(struct sockaddr)];
-};
-
-*/
-import "C"
-
-// Machine characteristics
-
-const (
- SizeofPtr = C.sizeofPtr
- SizeofShort = C.sizeof_short
- SizeofInt = C.sizeof_int
- SizeofLong = C.sizeof_long
- SizeofLongLong = C.sizeof_longlong
- PathMax = C.PATH_MAX
- MaxHostNameLen = C.MAXHOSTNAMELEN
-)
-
-// Basic types
-
-type (
- _C_short C.short
- _C_int C.int
- _C_long C.long
- _C_long_long C.longlong
-)
-
-// Time
-
-type Timespec C.struct_timespec
-
-type Timeval C.struct_timeval
-
-type Timeval32 C.struct_timeval32
-
-type Tms C.struct_tms
-
-type Utimbuf C.struct_utimbuf
-
-// Processes
-
-type Rusage C.struct_rusage
-
-type Rlimit C.struct_rlimit
-
-type _Gid_t C.gid_t
-
-// Files
-
-type Stat_t C.struct_stat
-
-type Flock_t C.struct_flock
-
-type Dirent C.struct_dirent
-
-// Filesystems
-
-type _Fsblkcnt_t C.fsblkcnt_t
-
-type Statvfs_t C.struct_statvfs
-
-// Sockets
-
-type RawSockaddrInet4 C.struct_sockaddr_in
-
-type RawSockaddrInet6 C.struct_sockaddr_in6
-
-type RawSockaddrUnix C.struct_sockaddr_un
-
-type RawSockaddrDatalink C.struct_sockaddr_dl
-
-type RawSockaddr C.struct_sockaddr
-
-type RawSockaddrAny C.struct_sockaddr_any
-
-type _Socklen C.socklen_t
-
-type Linger C.struct_linger
-
-type Iovec C.struct_iovec
-
-type IPMreq C.struct_ip_mreq
-
-type IPv6Mreq C.struct_ipv6_mreq
-
-type Msghdr C.struct_msghdr
-
-type Cmsghdr C.struct_cmsghdr
-
-type Inet6Pktinfo C.struct_in6_pktinfo
-
-type IPv6MTUInfo C.struct_ip6_mtuinfo
-
-type ICMPv6Filter C.struct_icmp6_filter
-
-const (
- SizeofSockaddrInet4 = C.sizeof_struct_sockaddr_in
- SizeofSockaddrInet6 = C.sizeof_struct_sockaddr_in6
- SizeofSockaddrAny = C.sizeof_struct_sockaddr_any
- SizeofSockaddrUnix = C.sizeof_struct_sockaddr_un
- SizeofSockaddrDatalink = C.sizeof_struct_sockaddr_dl
- SizeofLinger = C.sizeof_struct_linger
- SizeofIPMreq = C.sizeof_struct_ip_mreq
- SizeofIPv6Mreq = C.sizeof_struct_ipv6_mreq
- SizeofMsghdr = C.sizeof_struct_msghdr
- SizeofCmsghdr = C.sizeof_struct_cmsghdr
- SizeofInet6Pktinfo = C.sizeof_struct_in6_pktinfo
- SizeofIPv6MTUInfo = C.sizeof_struct_ip6_mtuinfo
- SizeofICMPv6Filter = C.sizeof_struct_icmp6_filter
-)
-
-// Select
-
-type FdSet C.fd_set
-
-// Misc
-
-type Utsname C.struct_utsname
-
-type Ustat_t C.struct_ustat
-
-const (
- AT_FDCWD = C.AT_FDCWD
- AT_SYMLINK_NOFOLLOW = C.AT_SYMLINK_NOFOLLOW
- AT_SYMLINK_FOLLOW = C.AT_SYMLINK_FOLLOW
- AT_REMOVEDIR = C.AT_REMOVEDIR
- AT_EACCESS = C.AT_EACCESS
-)
-
-// Routing and interface messages
-
-const (
- SizeofIfMsghdr = C.sizeof_struct_if_msghdr
- SizeofIfData = C.sizeof_struct_if_data
- SizeofIfaMsghdr = C.sizeof_struct_ifa_msghdr
- SizeofRtMsghdr = C.sizeof_struct_rt_msghdr
- SizeofRtMetrics = C.sizeof_struct_rt_metrics
-)
-
-type IfMsghdr C.struct_if_msghdr
-
-type IfData C.struct_if_data
-
-type IfaMsghdr C.struct_ifa_msghdr
-
-type RtMsghdr C.struct_rt_msghdr
-
-type RtMetrics C.struct_rt_metrics
-
-// Berkeley packet filter
-
-const (
- SizeofBpfVersion = C.sizeof_struct_bpf_version
- SizeofBpfStat = C.sizeof_struct_bpf_stat
- SizeofBpfProgram = C.sizeof_struct_bpf_program
- SizeofBpfInsn = C.sizeof_struct_bpf_insn
- SizeofBpfHdr = C.sizeof_struct_bpf_hdr
-)
-
-type BpfVersion C.struct_bpf_version
-
-type BpfStat C.struct_bpf_stat
-
-type BpfProgram C.struct_bpf_program
-
-type BpfInsn C.struct_bpf_insn
-
-type BpfTimeval C.struct_bpf_timeval
-
-type BpfHdr C.struct_bpf_hdr
-
-// Terminal handling
-
-type Termios C.struct_termios
-
-type Termio C.struct_termio
-
-type Winsize C.struct_winsize
-
-// poll
-
-type PollFd C.struct_pollfd
-
-const (
- POLLERR = C.POLLERR
- POLLHUP = C.POLLHUP
- POLLIN = C.POLLIN
- POLLNVAL = C.POLLNVAL
- POLLOUT = C.POLLOUT
- POLLPRI = C.POLLPRI
- POLLRDBAND = C.POLLRDBAND
- POLLRDNORM = C.POLLRDNORM
- POLLWRBAND = C.POLLWRBAND
- POLLWRNORM = C.POLLWRNORM
-)
diff --git a/vendor/golang.org/x/text/unicode/bidi/gen.go b/vendor/golang.org/x/text/unicode/bidi/gen.go
deleted file mode 100644
index 987fc16..0000000
--- a/vendor/golang.org/x/text/unicode/bidi/gen.go
+++ /dev/null
@@ -1,133 +0,0 @@
-// Copyright 2015 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-package main
-
-import (
- "flag"
- "log"
-
- "golang.org/x/text/internal/gen"
- "golang.org/x/text/internal/triegen"
- "golang.org/x/text/internal/ucd"
-)
-
-var outputFile = flag.String("out", "tables.go", "output file")
-
-func main() {
- gen.Init()
- gen.Repackage("gen_trieval.go", "trieval.go", "bidi")
- gen.Repackage("gen_ranges.go", "ranges_test.go", "bidi")
-
- genTables()
-}
-
-// bidiClass names and codes taken from class "bc" in
-// https://www.unicode.org/Public/8.0.0/ucd/PropertyValueAliases.txt
-var bidiClass = map[string]Class{
- "AL": AL, // ArabicLetter
- "AN": AN, // ArabicNumber
- "B": B, // ParagraphSeparator
- "BN": BN, // BoundaryNeutral
- "CS": CS, // CommonSeparator
- "EN": EN, // EuropeanNumber
- "ES": ES, // EuropeanSeparator
- "ET": ET, // EuropeanTerminator
- "L": L, // LeftToRight
- "NSM": NSM, // NonspacingMark
- "ON": ON, // OtherNeutral
- "R": R, // RightToLeft
- "S": S, // SegmentSeparator
- "WS": WS, // WhiteSpace
-
- "FSI": Control,
- "PDF": Control,
- "PDI": Control,
- "LRE": Control,
- "LRI": Control,
- "LRO": Control,
- "RLE": Control,
- "RLI": Control,
- "RLO": Control,
-}
-
-func genTables() {
- if numClass > 0x0F {
- log.Fatalf("Too many Class constants (%#x > 0x0F).", numClass)
- }
- w := gen.NewCodeWriter()
- defer w.WriteVersionedGoFile(*outputFile, "bidi")
-
- gen.WriteUnicodeVersion(w)
-
- t := triegen.NewTrie("bidi")
-
- // Build data about bracket mapping. These bits need to be or-ed with
- // any other bits.
- orMask := map[rune]uint64{}
-
- xorMap := map[rune]int{}
- xorMasks := []rune{0} // First value is no-op.
-
- ucd.Parse(gen.OpenUCDFile("BidiBrackets.txt"), func(p *ucd.Parser) {
- r1 := p.Rune(0)
- r2 := p.Rune(1)
- xor := r1 ^ r2
- if _, ok := xorMap[xor]; !ok {
- xorMap[xor] = len(xorMasks)
- xorMasks = append(xorMasks, xor)
- }
- entry := uint64(xorMap[xor]) << xorMaskShift
- switch p.String(2) {
- case "o":
- entry |= openMask
- case "c", "n":
- default:
- log.Fatalf("Unknown bracket class %q.", p.String(2))
- }
- orMask[r1] = entry
- })
-
- w.WriteComment(`
- xorMasks contains masks to be xor-ed with brackets to get the reverse
- version.`)
- w.WriteVar("xorMasks", xorMasks)
-
- done := map[rune]bool{}
-
- insert := func(r rune, c Class) {
- if !done[r] {
- t.Insert(r, orMask[r]|uint64(c))
- done[r] = true
- }
- }
-
- // Insert the derived BiDi properties.
- ucd.Parse(gen.OpenUCDFile("extracted/DerivedBidiClass.txt"), func(p *ucd.Parser) {
- r := p.Rune(0)
- class, ok := bidiClass[p.String(1)]
- if !ok {
- log.Fatalf("%U: Unknown BiDi class %q", r, p.String(1))
- }
- insert(r, class)
- })
- visitDefaults(insert)
-
- // TODO: use sparse blocks. This would reduce table size considerably
- // from the looks of it.
-
- sz, err := t.Gen(w)
- if err != nil {
- log.Fatal(err)
- }
- w.Size += sz
-}
-
-// dummy values to make methods in gen_common compile. The real versions
-// will be generated by this file to tables.go.
-var (
- xorMasks []rune
-)
diff --git a/vendor/golang.org/x/text/unicode/bidi/gen_ranges.go b/vendor/golang.org/x/text/unicode/bidi/gen_ranges.go
deleted file mode 100644
index 02c3b50..0000000
--- a/vendor/golang.org/x/text/unicode/bidi/gen_ranges.go
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright 2015 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-package main
-
-import (
- "unicode"
-
- "golang.org/x/text/internal/gen"
- "golang.org/x/text/internal/ucd"
- "golang.org/x/text/unicode/rangetable"
-)
-
-// These tables are hand-extracted from:
-// https://www.unicode.org/Public/8.0.0/ucd/extracted/DerivedBidiClass.txt
-func visitDefaults(fn func(r rune, c Class)) {
- // first write default values for ranges listed above.
- visitRunes(fn, AL, []rune{
- 0x0600, 0x07BF, // Arabic
- 0x08A0, 0x08FF, // Arabic Extended-A
- 0xFB50, 0xFDCF, // Arabic Presentation Forms
- 0xFDF0, 0xFDFF,
- 0xFE70, 0xFEFF,
- 0x0001EE00, 0x0001EEFF, // Arabic Mathematical Alpha Symbols
- })
- visitRunes(fn, R, []rune{
- 0x0590, 0x05FF, // Hebrew
- 0x07C0, 0x089F, // Nko et al.
- 0xFB1D, 0xFB4F,
- 0x00010800, 0x00010FFF, // Cypriot Syllabary et. al.
- 0x0001E800, 0x0001EDFF,
- 0x0001EF00, 0x0001EFFF,
- })
- visitRunes(fn, ET, []rune{ // European Terminator
- 0x20A0, 0x20Cf, // Currency symbols
- })
- rangetable.Visit(unicode.Noncharacter_Code_Point, func(r rune) {
- fn(r, BN) // Boundary Neutral
- })
- ucd.Parse(gen.OpenUCDFile("DerivedCoreProperties.txt"), func(p *ucd.Parser) {
- if p.String(1) == "Default_Ignorable_Code_Point" {
- fn(p.Rune(0), BN) // Boundary Neutral
- }
- })
-}
-
-func visitRunes(fn func(r rune, c Class), c Class, runes []rune) {
- for i := 0; i < len(runes); i += 2 {
- lo, hi := runes[i], runes[i+1]
- for j := lo; j <= hi; j++ {
- fn(j, c)
- }
- }
-}
diff --git a/vendor/golang.org/x/text/unicode/bidi/gen_trieval.go b/vendor/golang.org/x/text/unicode/bidi/gen_trieval.go
deleted file mode 100644
index 9cb9942..0000000
--- a/vendor/golang.org/x/text/unicode/bidi/gen_trieval.go
+++ /dev/null
@@ -1,64 +0,0 @@
-// Copyright 2015 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-package main
-
-// Class is the Unicode BiDi class. Each rune has a single class.
-type Class uint
-
-const (
- L Class = iota // LeftToRight
- R // RightToLeft
- EN // EuropeanNumber
- ES // EuropeanSeparator
- ET // EuropeanTerminator
- AN // ArabicNumber
- CS // CommonSeparator
- B // ParagraphSeparator
- S // SegmentSeparator
- WS // WhiteSpace
- ON // OtherNeutral
- BN // BoundaryNeutral
- NSM // NonspacingMark
- AL // ArabicLetter
- Control // Control LRO - PDI
-
- numClass
-
- LRO // LeftToRightOverride
- RLO // RightToLeftOverride
- LRE // LeftToRightEmbedding
- RLE // RightToLeftEmbedding
- PDF // PopDirectionalFormat
- LRI // LeftToRightIsolate
- RLI // RightToLeftIsolate
- FSI // FirstStrongIsolate
- PDI // PopDirectionalIsolate
-
- unknownClass = ^Class(0)
-)
-
-var controlToClass = map[rune]Class{
- 0x202D: LRO, // LeftToRightOverride,
- 0x202E: RLO, // RightToLeftOverride,
- 0x202A: LRE, // LeftToRightEmbedding,
- 0x202B: RLE, // RightToLeftEmbedding,
- 0x202C: PDF, // PopDirectionalFormat,
- 0x2066: LRI, // LeftToRightIsolate,
- 0x2067: RLI, // RightToLeftIsolate,
- 0x2068: FSI, // FirstStrongIsolate,
- 0x2069: PDI, // PopDirectionalIsolate,
-}
-
-// A trie entry has the following bits:
-// 7..5 XOR mask for brackets
-// 4 1: Bracket open, 0: Bracket close
-// 3..0 Class type
-
-const (
- openMask = 0x10
- xorMaskShift = 5
-)
diff --git a/vendor/golang.org/x/text/unicode/norm/maketables.go b/vendor/golang.org/x/text/unicode/norm/maketables.go
deleted file mode 100644
index 30a3aa9..0000000
--- a/vendor/golang.org/x/text/unicode/norm/maketables.go
+++ /dev/null
@@ -1,986 +0,0 @@
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-// Normalization table generator.
-// Data read from the web.
-// See forminfo.go for a description of the trie values associated with each rune.
-
-package main
-
-import (
- "bytes"
- "encoding/binary"
- "flag"
- "fmt"
- "io"
- "log"
- "sort"
- "strconv"
- "strings"
-
- "golang.org/x/text/internal/gen"
- "golang.org/x/text/internal/triegen"
- "golang.org/x/text/internal/ucd"
-)
-
-func main() {
- gen.Init()
- loadUnicodeData()
- compactCCC()
- loadCompositionExclusions()
- completeCharFields(FCanonical)
- completeCharFields(FCompatibility)
- computeNonStarterCounts()
- verifyComputed()
- printChars()
- testDerived()
- printTestdata()
- makeTables()
-}
-
-var (
- tablelist = flag.String("tables",
- "all",
- "comma-separated list of which tables to generate; "+
- "can be 'decomp', 'recomp', 'info' and 'all'")
- test = flag.Bool("test",
- false,
- "test existing tables against DerivedNormalizationProps and generate test data for regression testing")
- verbose = flag.Bool("verbose",
- false,
- "write data to stdout as it is parsed")
-)
-
-const MaxChar = 0x10FFFF // anything above this shouldn't exist
-
-// Quick Check properties of runes allow us to quickly
-// determine whether a rune may occur in a normal form.
-// For a given normal form, a rune may be guaranteed to occur
-// verbatim (QC=Yes), may or may not combine with another
-// rune (QC=Maybe), or may not occur (QC=No).
-type QCResult int
-
-const (
- QCUnknown QCResult = iota
- QCYes
- QCNo
- QCMaybe
-)
-
-func (r QCResult) String() string {
- switch r {
- case QCYes:
- return "Yes"
- case QCNo:
- return "No"
- case QCMaybe:
- return "Maybe"
- }
- return "***UNKNOWN***"
-}
-
-const (
- FCanonical = iota // NFC or NFD
- FCompatibility // NFKC or NFKD
- FNumberOfFormTypes
-)
-
-const (
- MComposed = iota // NFC or NFKC
- MDecomposed // NFD or NFKD
- MNumberOfModes
-)
-
-// This contains only the properties we're interested in.
-type Char struct {
- name string
- codePoint rune // if zero, this index is not a valid code point.
- ccc uint8 // canonical combining class
- origCCC uint8
- excludeInComp bool // from CompositionExclusions.txt
- compatDecomp bool // it has a compatibility expansion
-
- nTrailingNonStarters uint8
- nLeadingNonStarters uint8 // must be equal to trailing if non-zero
-
- forms [FNumberOfFormTypes]FormInfo // For FCanonical and FCompatibility
-
- state State
-}
-
-var chars = make([]Char, MaxChar+1)
-var cccMap = make(map[uint8]uint8)
-
-func (c Char) String() string {
- buf := new(bytes.Buffer)
-
- fmt.Fprintf(buf, "%U [%s]:\n", c.codePoint, c.name)
- fmt.Fprintf(buf, " ccc: %v\n", c.ccc)
- fmt.Fprintf(buf, " excludeInComp: %v\n", c.excludeInComp)
- fmt.Fprintf(buf, " compatDecomp: %v\n", c.compatDecomp)
- fmt.Fprintf(buf, " state: %v\n", c.state)
- fmt.Fprintf(buf, " NFC:\n")
- fmt.Fprint(buf, c.forms[FCanonical])
- fmt.Fprintf(buf, " NFKC:\n")
- fmt.Fprint(buf, c.forms[FCompatibility])
-
- return buf.String()
-}
-
-// In UnicodeData.txt, some ranges are marked like this:
-// 3400;<CJK Ideograph Extension A, First>;Lo;0;L;;;;;N;;;;;
-// 4DB5;<CJK Ideograph Extension A, Last>;Lo;0;L;;;;;N;;;;;
-// parseCharacter keeps a state variable indicating the weirdness.
-type State int
-
-const (
- SNormal State = iota // known to be zero for the type
- SFirst
- SLast
- SMissing
-)
-
-var lastChar = rune('\u0000')
-
-func (c Char) isValid() bool {
- return c.codePoint != 0 && c.state != SMissing
-}
-
-type FormInfo struct {
- quickCheck [MNumberOfModes]QCResult // index: MComposed or MDecomposed
- verified [MNumberOfModes]bool // index: MComposed or MDecomposed
-
- combinesForward bool // May combine with rune on the right
- combinesBackward bool // May combine with rune on the left
- isOneWay bool // Never appears in result
- inDecomp bool // Some decompositions result in this char.
- decomp Decomposition
- expandedDecomp Decomposition
-}
-
-func (f FormInfo) String() string {
- buf := bytes.NewBuffer(make([]byte, 0))
-
- fmt.Fprintf(buf, " quickCheck[C]: %v\n", f.quickCheck[MComposed])
- fmt.Fprintf(buf, " quickCheck[D]: %v\n", f.quickCheck[MDecomposed])
- fmt.Fprintf(buf, " cmbForward: %v\n", f.combinesForward)
- fmt.Fprintf(buf, " cmbBackward: %v\n", f.combinesBackward)
- fmt.Fprintf(buf, " isOneWay: %v\n", f.isOneWay)
- fmt.Fprintf(buf, " inDecomp: %v\n", f.inDecomp)
- fmt.Fprintf(buf, " decomposition: %X\n", f.decomp)
- fmt.Fprintf(buf, " expandedDecomp: %X\n", f.expandedDecomp)
-
- return buf.String()
-}
-
-type Decomposition []rune
-
-func parseDecomposition(s string, skipfirst bool) (a []rune, err error) {
- decomp := strings.Split(s, " ")
- if len(decomp) > 0 && skipfirst {
- decomp = decomp[1:]
- }
- for _, d := range decomp {
- point, err := strconv.ParseUint(d, 16, 64)
- if err != nil {
- return a, err
- }
- a = append(a, rune(point))
- }
- return a, nil
-}
-
-func loadUnicodeData() {
- f := gen.OpenUCDFile("UnicodeData.txt")
- defer f.Close()
- p := ucd.New(f)
- for p.Next() {
- r := p.Rune(ucd.CodePoint)
- char := &chars[r]
-
- char.ccc = uint8(p.Uint(ucd.CanonicalCombiningClass))
- decmap := p.String(ucd.DecompMapping)
-
- exp, err := parseDecomposition(decmap, false)
- isCompat := false
- if err != nil {
- if len(decmap) > 0 {
- exp, err = parseDecomposition(decmap, true)
- if err != nil {
- log.Fatalf(`%U: bad decomp |%v|: "%s"`, r, decmap, err)
- }
- isCompat = true
- }
- }
-
- char.name = p.String(ucd.Name)
- char.codePoint = r
- char.forms[FCompatibility].decomp = exp
- if !isCompat {
- char.forms[FCanonical].decomp = exp
- } else {
- char.compatDecomp = true
- }
- if len(decmap) > 0 {
- char.forms[FCompatibility].decomp = exp
- }
- }
- if err := p.Err(); err != nil {
- log.Fatal(err)
- }
-}
-
-// compactCCC converts the sparse set of CCC values to a continguous one,
-// reducing the number of bits needed from 8 to 6.
-func compactCCC() {
- m := make(map[uint8]uint8)
- for i := range chars {
- c := &chars[i]
- m[c.ccc] = 0
- }
- cccs := []int{}
- for v, _ := range m {
- cccs = append(cccs, int(v))
- }
- sort.Ints(cccs)
- for i, c := range cccs {
- cccMap[uint8(i)] = uint8(c)
- m[uint8(c)] = uint8(i)
- }
- for i := range chars {
- c := &chars[i]
- c.origCCC = c.ccc
- c.ccc = m[c.ccc]
- }
- if len(m) >= 1<<6 {
- log.Fatalf("too many difference CCC values: %d >= 64", len(m))
- }
-}
-
-// CompositionExclusions.txt has form:
-// 0958 # ...
-// See https://unicode.org/reports/tr44/ for full explanation
-func loadCompositionExclusions() {
- f := gen.OpenUCDFile("CompositionExclusions.txt")
- defer f.Close()
- p := ucd.New(f)
- for p.Next() {
- c := &chars[p.Rune(0)]
- if c.excludeInComp {
- log.Fatalf("%U: Duplicate entry in exclusions.", c.codePoint)
- }
- c.excludeInComp = true
- }
- if e := p.Err(); e != nil {
- log.Fatal(e)
- }
-}
-
-// hasCompatDecomp returns true if any of the recursive
-// decompositions contains a compatibility expansion.
-// In this case, the character may not occur in NFK*.
-func hasCompatDecomp(r rune) bool {
- c := &chars[r]
- if c.compatDecomp {
- return true
- }
- for _, d := range c.forms[FCompatibility].decomp {
- if hasCompatDecomp(d) {
- return true
- }
- }
- return false
-}
-
-// Hangul related constants.
-const (
- HangulBase = 0xAC00
- HangulEnd = 0xD7A4 // hangulBase + Jamo combinations (19 * 21 * 28)
-
- JamoLBase = 0x1100
- JamoLEnd = 0x1113
- JamoVBase = 0x1161
- JamoVEnd = 0x1176
- JamoTBase = 0x11A8
- JamoTEnd = 0x11C3
-
- JamoLVTCount = 19 * 21 * 28
- JamoTCount = 28
-)
-
-func isHangul(r rune) bool {
- return HangulBase <= r && r < HangulEnd
-}
-
-func isHangulWithoutJamoT(r rune) bool {
- if !isHangul(r) {
- return false
- }
- r -= HangulBase
- return r < JamoLVTCount && r%JamoTCount == 0
-}
-
-func ccc(r rune) uint8 {
- return chars[r].ccc
-}
-
-// Insert a rune in a buffer, ordered by Canonical Combining Class.
-func insertOrdered(b Decomposition, r rune) Decomposition {
- n := len(b)
- b = append(b, 0)
- cc := ccc(r)
- if cc > 0 {
- // Use bubble sort.
- for ; n > 0; n-- {
- if ccc(b[n-1]) <= cc {
- break
- }
- b[n] = b[n-1]
- }
- }
- b[n] = r
- return b
-}
-
-// Recursively decompose.
-func decomposeRecursive(form int, r rune, d Decomposition) Decomposition {
- dcomp := chars[r].forms[form].decomp
- if len(dcomp) == 0 {
- return insertOrdered(d, r)
- }
- for _, c := range dcomp {
- d = decomposeRecursive(form, c, d)
- }
- return d
-}
-
-func completeCharFields(form int) {
- // Phase 0: pre-expand decomposition.
- for i := range chars {
- f := &chars[i].forms[form]
- if len(f.decomp) == 0 {
- continue
- }
- exp := make(Decomposition, 0)
- for _, c := range f.decomp {
- exp = decomposeRecursive(form, c, exp)
- }
- f.expandedDecomp = exp
- }
-
- // Phase 1: composition exclusion, mark decomposition.
- for i := range chars {
- c := &chars[i]
- f := &c.forms[form]
-
- // Marks script-specific exclusions and version restricted.
- f.isOneWay = c.excludeInComp
-
- // Singletons
- f.isOneWay = f.isOneWay || len(f.decomp) == 1
-
- // Non-starter decompositions
- if len(f.decomp) > 1 {
- chk := c.ccc != 0 || chars[f.decomp[0]].ccc != 0
- f.isOneWay = f.isOneWay || chk
- }
-
- // Runes that decompose into more than two runes.
- f.isOneWay = f.isOneWay || len(f.decomp) > 2
-
- if form == FCompatibility {
- f.isOneWay = f.isOneWay || hasCompatDecomp(c.codePoint)
- }
-
- for _, r := range f.decomp {
- chars[r].forms[form].inDecomp = true
- }
- }
-
- // Phase 2: forward and backward combining.
- for i := range chars {
- c := &chars[i]
- f := &c.forms[form]
-
- if !f.isOneWay && len(f.decomp) == 2 {
- f0 := &chars[f.decomp[0]].forms[form]
- f1 := &chars[f.decomp[1]].forms[form]
- if !f0.isOneWay {
- f0.combinesForward = true
- }
- if !f1.isOneWay {
- f1.combinesBackward = true
- }
- }
- if isHangulWithoutJamoT(rune(i)) {
- f.combinesForward = true
- }
- }
-
- // Phase 3: quick check values.
- for i := range chars {
- c := &chars[i]
- f := &c.forms[form]
-
- switch {
- case len(f.decomp) > 0:
- f.quickCheck[MDecomposed] = QCNo
- case isHangul(rune(i)):
- f.quickCheck[MDecomposed] = QCNo
- default:
- f.quickCheck[MDecomposed] = QCYes
- }
- switch {
- case f.isOneWay:
- f.quickCheck[MComposed] = QCNo
- case (i & 0xffff00) == JamoLBase:
- f.quickCheck[MComposed] = QCYes
- if JamoLBase <= i && i < JamoLEnd {
- f.combinesForward = true
- }
- if JamoVBase <= i && i < JamoVEnd {
- f.quickCheck[MComposed] = QCMaybe
- f.combinesBackward = true
- f.combinesForward = true
- }
- if JamoTBase <= i && i < JamoTEnd {
- f.quickCheck[MComposed] = QCMaybe
- f.combinesBackward = true
- }
- case !f.combinesBackward:
- f.quickCheck[MComposed] = QCYes
- default:
- f.quickCheck[MComposed] = QCMaybe
- }
- }
-}
-
-func computeNonStarterCounts() {
- // Phase 4: leading and trailing non-starter count
- for i := range chars {
- c := &chars[i]
-
- runes := []rune{rune(i)}
- // We always use FCompatibility so that the CGJ insertion points do not
- // change for repeated normalizations with different forms.
- if exp := c.forms[FCompatibility].expandedDecomp; len(exp) > 0 {
- runes = exp
- }
- // We consider runes that combine backwards to be non-starters for the
- // purpose of Stream-Safe Text Processing.
- for _, r := range runes {
- if cr := &chars[r]; cr.ccc == 0 && !cr.forms[FCompatibility].combinesBackward {
- break
- }
- c.nLeadingNonStarters++
- }
- for i := len(runes) - 1; i >= 0; i-- {
- if cr := &chars[runes[i]]; cr.ccc == 0 && !cr.forms[FCompatibility].combinesBackward {
- break
- }
- c.nTrailingNonStarters++
- }
- if c.nTrailingNonStarters > 3 {
- log.Fatalf("%U: Decomposition with more than 3 (%d) trailing modifiers (%U)", i, c.nTrailingNonStarters, runes)
- }
-
- if isHangul(rune(i)) {
- c.nTrailingNonStarters = 2
- if isHangulWithoutJamoT(rune(i)) {
- c.nTrailingNonStarters = 1
- }
- }
-
- if l, t := c.nLeadingNonStarters, c.nTrailingNonStarters; l > 0 && l != t {
- log.Fatalf("%U: number of leading and trailing non-starters should be equal (%d vs %d)", i, l, t)
- }
- if t := c.nTrailingNonStarters; t > 3 {
- log.Fatalf("%U: number of trailing non-starters is %d > 3", t)
- }
- }
-}
-
-func printBytes(w io.Writer, b []byte, name string) {
- fmt.Fprintf(w, "// %s: %d bytes\n", name, len(b))
- fmt.Fprintf(w, "var %s = [...]byte {", name)
- for i, c := range b {
- switch {
- case i%64 == 0:
- fmt.Fprintf(w, "\n// Bytes %x - %x\n", i, i+63)
- case i%8 == 0:
- fmt.Fprintf(w, "\n")
- }
- fmt.Fprintf(w, "0x%.2X, ", c)
- }
- fmt.Fprint(w, "\n}\n\n")
-}
-
-// See forminfo.go for format.
-func makeEntry(f *FormInfo, c *Char) uint16 {
- e := uint16(0)
- if r := c.codePoint; HangulBase <= r && r < HangulEnd {
- e |= 0x40
- }
- if f.combinesForward {
- e |= 0x20
- }
- if f.quickCheck[MDecomposed] == QCNo {
- e |= 0x4
- }
- switch f.quickCheck[MComposed] {
- case QCYes:
- case QCNo:
- e |= 0x10
- case QCMaybe:
- e |= 0x18
- default:
- log.Fatalf("Illegal quickcheck value %v.", f.quickCheck[MComposed])
- }
- e |= uint16(c.nTrailingNonStarters)
- return e
-}
-
-// decompSet keeps track of unique decompositions, grouped by whether
-// the decomposition is followed by a trailing and/or leading CCC.
-type decompSet [7]map[string]bool
-
-const (
- normalDecomp = iota
- firstMulti
- firstCCC
- endMulti
- firstLeadingCCC
- firstCCCZeroExcept
- firstStarterWithNLead
- lastDecomp
-)
-
-var cname = []string{"firstMulti", "firstCCC", "endMulti", "firstLeadingCCC", "firstCCCZeroExcept", "firstStarterWithNLead", "lastDecomp"}
-
-func makeDecompSet() decompSet {
- m := decompSet{}
- for i := range m {
- m[i] = make(map[string]bool)
- }
- return m
-}
-func (m *decompSet) insert(key int, s string) {
- m[key][s] = true
-}
-
-func printCharInfoTables(w io.Writer) int {
- mkstr := func(r rune, f *FormInfo) (int, string) {
- d := f.expandedDecomp
- s := string([]rune(d))
- if max := 1 << 6; len(s) >= max {
- const msg = "%U: too many bytes in decomposition: %d >= %d"
- log.Fatalf(msg, r, len(s), max)
- }
- head := uint8(len(s))
- if f.quickCheck[MComposed] != QCYes {
- head |= 0x40
- }
- if f.combinesForward {
- head |= 0x80
- }
- s = string([]byte{head}) + s
-
- lccc := ccc(d[0])
- tccc := ccc(d[len(d)-1])
- cc := ccc(r)
- if cc != 0 && lccc == 0 && tccc == 0 {
- log.Fatalf("%U: trailing and leading ccc are 0 for non-zero ccc %d", r, cc)
- }
- if tccc < lccc && lccc != 0 {
- const msg = "%U: lccc (%d) must be <= tcc (%d)"
- log.Fatalf(msg, r, lccc, tccc)
- }
- index := normalDecomp
- nTrail := chars[r].nTrailingNonStarters
- nLead := chars[r].nLeadingNonStarters
- if tccc > 0 || lccc > 0 || nTrail > 0 {
- tccc <<= 2
- tccc |= nTrail
- s += string([]byte{tccc})
- index = endMulti
- for _, r := range d[1:] {
- if ccc(r) == 0 {
- index = firstCCC
- }
- }
- if lccc > 0 || nLead > 0 {
- s += string([]byte{lccc})
- if index == firstCCC {
- log.Fatalf("%U: multi-segment decomposition not supported for decompositions with leading CCC != 0", r)
- }
- index = firstLeadingCCC
- }
- if cc != lccc {
- if cc != 0 {
- log.Fatalf("%U: for lccc != ccc, expected ccc to be 0; was %d", r, cc)
- }
- index = firstCCCZeroExcept
- }
- } else if len(d) > 1 {
- index = firstMulti
- }
- return index, s
- }
-
- decompSet := makeDecompSet()
- const nLeadStr = "\x00\x01" // 0-byte length and tccc with nTrail.
- decompSet.insert(firstStarterWithNLead, nLeadStr)
-
- // Store the uniqued decompositions in a byte buffer,
- // preceded by their byte length.
- for _, c := range chars {
- for _, f := range c.forms {
- if len(f.expandedDecomp) == 0 {
- continue
- }
- if f.combinesBackward {
- log.Fatalf("%U: combinesBackward and decompose", c.codePoint)
- }
- index, s := mkstr(c.codePoint, &f)
- decompSet.insert(index, s)
- }
- }
-
- decompositions := bytes.NewBuffer(make([]byte, 0, 10000))
- size := 0
- positionMap := make(map[string]uint16)
- decompositions.WriteString("\000")
- fmt.Fprintln(w, "const (")
- for i, m := range decompSet {
- sa := []string{}
- for s := range m {
- sa = append(sa, s)
- }
- sort.Strings(sa)
- for _, s := range sa {
- p := decompositions.Len()
- decompositions.WriteString(s)
- positionMap[s] = uint16(p)
- }
- if cname[i] != "" {
- fmt.Fprintf(w, "%s = 0x%X\n", cname[i], decompositions.Len())
- }
- }
- fmt.Fprintln(w, "maxDecomp = 0x8000")
- fmt.Fprintln(w, ")")
- b := decompositions.Bytes()
- printBytes(w, b, "decomps")
- size += len(b)
-
- varnames := []string{"nfc", "nfkc"}
- for i := 0; i < FNumberOfFormTypes; i++ {
- trie := triegen.NewTrie(varnames[i])
-
- for r, c := range chars {
- f := c.forms[i]
- d := f.expandedDecomp
- if len(d) != 0 {
- _, key := mkstr(c.codePoint, &f)
- trie.Insert(rune(r), uint64(positionMap[key]))
- if c.ccc != ccc(d[0]) {
- // We assume the lead ccc of a decomposition !=0 in this case.
- if ccc(d[0]) == 0 {
- log.Fatalf("Expected leading CCC to be non-zero; ccc is %d", c.ccc)
- }
- }
- } else if c.nLeadingNonStarters > 0 && len(f.expandedDecomp) == 0 && c.ccc == 0 && !f.combinesBackward {
- // Handle cases where it can't be detected that the nLead should be equal
- // to nTrail.
- trie.Insert(c.codePoint, uint64(positionMap[nLeadStr]))
- } else if v := makeEntry(&f, &c)<<8 | uint16(c.ccc); v != 0 {
- trie.Insert(c.codePoint, uint64(0x8000|v))
- }
- }
- sz, err := trie.Gen(w, triegen.Compact(&normCompacter{name: varnames[i]}))
- if err != nil {
- log.Fatal(err)
- }
- size += sz
- }
- return size
-}
-
-func contains(sa []string, s string) bool {
- for _, a := range sa {
- if a == s {
- return true
- }
- }
- return false
-}
-
-func makeTables() {
- w := &bytes.Buffer{}
-
- size := 0
- if *tablelist == "" {
- return
- }
- list := strings.Split(*tablelist, ",")
- if *tablelist == "all" {
- list = []string{"recomp", "info"}
- }
-
- // Compute maximum decomposition size.
- max := 0
- for _, c := range chars {
- if n := len(string(c.forms[FCompatibility].expandedDecomp)); n > max {
- max = n
- }
- }
- fmt.Fprintln(w, `import "sync"`)
- fmt.Fprintln(w)
-
- fmt.Fprintln(w, "const (")
- fmt.Fprintln(w, "\t// Version is the Unicode edition from which the tables are derived.")
- fmt.Fprintf(w, "\tVersion = %q\n", gen.UnicodeVersion())
- fmt.Fprintln(w)
- fmt.Fprintln(w, "\t// MaxTransformChunkSize indicates the maximum number of bytes that Transform")
- fmt.Fprintln(w, "\t// may need to write atomically for any Form. Making a destination buffer at")
- fmt.Fprintln(w, "\t// least this size ensures that Transform can always make progress and that")
- fmt.Fprintln(w, "\t// the user does not need to grow the buffer on an ErrShortDst.")
- fmt.Fprintf(w, "\tMaxTransformChunkSize = %d+maxNonStarters*4\n", len(string(0x034F))+max)
- fmt.Fprintln(w, ")\n")
-
- // Print the CCC remap table.
- size += len(cccMap)
- fmt.Fprintf(w, "var ccc = [%d]uint8{", len(cccMap))
- for i := 0; i < len(cccMap); i++ {
- if i%8 == 0 {
- fmt.Fprintln(w)
- }
- fmt.Fprintf(w, "%3d, ", cccMap[uint8(i)])
- }
- fmt.Fprintln(w, "\n}\n")
-
- if contains(list, "info") {
- size += printCharInfoTables(w)
- }
-
- if contains(list, "recomp") {
- // Note that we use 32 bit keys, instead of 64 bit.
- // This clips the bits of three entries, but we know
- // this won't cause a collision. The compiler will catch
- // any changes made to UnicodeData.txt that introduces
- // a collision.
- // Note that the recomposition map for NFC and NFKC
- // are identical.
-
- // Recomposition map
- nrentries := 0
- for _, c := range chars {
- f := c.forms[FCanonical]
- if !f.isOneWay && len(f.decomp) > 0 {
- nrentries++
- }
- }
- sz := nrentries * 8
- size += sz
- fmt.Fprintf(w, "// recompMap: %d bytes (entries only)\n", sz)
- fmt.Fprintln(w, "var recompMap map[uint32]rune")
- fmt.Fprintln(w, "var recompMapOnce sync.Once\n")
- fmt.Fprintln(w, `const recompMapPacked = "" +`)
- var buf [8]byte
- for i, c := range chars {
- f := c.forms[FCanonical]
- d := f.decomp
- if !f.isOneWay && len(d) > 0 {
- key := uint32(uint16(d[0]))<<16 + uint32(uint16(d[1]))
- binary.BigEndian.PutUint32(buf[:4], key)
- binary.BigEndian.PutUint32(buf[4:], uint32(i))
- fmt.Fprintf(w, "\t\t%q + // 0x%.8X: 0x%.8X\n", string(buf[:]), key, uint32(i))
- }
- }
- // hack so we don't have to special case the trailing plus sign
- fmt.Fprintf(w, ` ""`)
- fmt.Fprintln(w)
- }
-
- fmt.Fprintf(w, "// Total size of tables: %dKB (%d bytes)\n", (size+512)/1024, size)
- gen.WriteVersionedGoFile("tables.go", "norm", w.Bytes())
-}
-
-func printChars() {
- if *verbose {
- for _, c := range chars {
- if !c.isValid() || c.state == SMissing {
- continue
- }
- fmt.Println(c)
- }
- }
-}
-
-// verifyComputed does various consistency tests.
-func verifyComputed() {
- for i, c := range chars {
- for _, f := range c.forms {
- isNo := (f.quickCheck[MDecomposed] == QCNo)
- if (len(f.decomp) > 0) != isNo && !isHangul(rune(i)) {
- log.Fatalf("%U: NF*D QC must be No if rune decomposes", i)
- }
-
- isMaybe := f.quickCheck[MComposed] == QCMaybe
- if f.combinesBackward != isMaybe {
- log.Fatalf("%U: NF*C QC must be Maybe if combinesBackward", i)
- }
- if len(f.decomp) > 0 && f.combinesForward && isMaybe {
- log.Fatalf("%U: NF*C QC must be Yes or No if combinesForward and decomposes", i)
- }
-
- if len(f.expandedDecomp) != 0 {
- continue
- }
- if a, b := c.nLeadingNonStarters > 0, (c.ccc > 0 || f.combinesBackward); a != b {
- // We accept these runes to be treated differently (it only affects
- // segment breaking in iteration, most likely on improper use), but
- // reconsider if more characters are added.
- // U+FF9E HALFWIDTH KATAKANA VOICED SOUND MARK;Lm;0;L;<narrow> 3099;;;;N;;;;;
- // U+FF9F HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK;Lm;0;L;<narrow> 309A;;;;N;;;;;
- // U+3133 HANGUL LETTER KIYEOK-SIOS;Lo;0;L;<compat> 11AA;;;;N;HANGUL LETTER GIYEOG SIOS;;;;
- // U+318E HANGUL LETTER ARAEAE;Lo;0;L;<compat> 11A1;;;;N;HANGUL LETTER ALAE AE;;;;
- // U+FFA3 HALFWIDTH HANGUL LETTER KIYEOK-SIOS;Lo;0;L;<narrow> 3133;;;;N;HALFWIDTH HANGUL LETTER GIYEOG SIOS;;;;
- // U+FFDC HALFWIDTH HANGUL LETTER I;Lo;0;L;<narrow> 3163;;;;N;;;;;
- if i != 0xFF9E && i != 0xFF9F && !(0x3133 <= i && i <= 0x318E) && !(0xFFA3 <= i && i <= 0xFFDC) {
- log.Fatalf("%U: nLead was %v; want %v", i, a, b)
- }
- }
- }
- nfc := c.forms[FCanonical]
- nfkc := c.forms[FCompatibility]
- if nfc.combinesBackward != nfkc.combinesBackward {
- log.Fatalf("%U: Cannot combine combinesBackward\n", c.codePoint)
- }
- }
-}
-
-// Use values in DerivedNormalizationProps.txt to compare against the
-// values we computed.
-// DerivedNormalizationProps.txt has form:
-// 00C0..00C5 ; NFD_QC; N # ...
-// 0374 ; NFD_QC; N # ...
-// See https://unicode.org/reports/tr44/ for full explanation
-func testDerived() {
- f := gen.OpenUCDFile("DerivedNormalizationProps.txt")
- defer f.Close()
- p := ucd.New(f)
- for p.Next() {
- r := p.Rune(0)
- c := &chars[r]
-
- var ftype, mode int
- qt := p.String(1)
- switch qt {
- case "NFC_QC":
- ftype, mode = FCanonical, MComposed
- case "NFD_QC":
- ftype, mode = FCanonical, MDecomposed
- case "NFKC_QC":
- ftype, mode = FCompatibility, MComposed
- case "NFKD_QC":
- ftype, mode = FCompatibility, MDecomposed
- default:
- continue
- }
- var qr QCResult
- switch p.String(2) {
- case "Y":
- qr = QCYes
- case "N":
- qr = QCNo
- case "M":
- qr = QCMaybe
- default:
- log.Fatalf(`Unexpected quick check value "%s"`, p.String(2))
- }
- if got := c.forms[ftype].quickCheck[mode]; got != qr {
- log.Printf("%U: FAILED %s (was %v need %v)\n", r, qt, got, qr)
- }
- c.forms[ftype].verified[mode] = true
- }
- if err := p.Err(); err != nil {
- log.Fatal(err)
- }
- // Any unspecified value must be QCYes. Verify this.
- for i, c := range chars {
- for j, fd := range c.forms {
- for k, qr := range fd.quickCheck {
- if !fd.verified[k] && qr != QCYes {
- m := "%U: FAIL F:%d M:%d (was %v need Yes) %s\n"
- log.Printf(m, i, j, k, qr, c.name)
- }
- }
- }
- }
-}
-
-var testHeader = `const (
- Yes = iota
- No
- Maybe
-)
-
-type formData struct {
- qc uint8
- combinesForward bool
- decomposition string
-}
-
-type runeData struct {
- r rune
- ccc uint8
- nLead uint8
- nTrail uint8
- f [2]formData // 0: canonical; 1: compatibility
-}
-
-func f(qc uint8, cf bool, dec string) [2]formData {
- return [2]formData{{qc, cf, dec}, {qc, cf, dec}}
-}
-
-func g(qc, qck uint8, cf, cfk bool, d, dk string) [2]formData {
- return [2]formData{{qc, cf, d}, {qck, cfk, dk}}
-}
-
-var testData = []runeData{
-`
-
-func printTestdata() {
- type lastInfo struct {
- ccc uint8
- nLead uint8
- nTrail uint8
- f string
- }
-
- last := lastInfo{}
- w := &bytes.Buffer{}
- fmt.Fprintf(w, testHeader)
- for r, c := range chars {
- f := c.forms[FCanonical]
- qc, cf, d := f.quickCheck[MComposed], f.combinesForward, string(f.expandedDecomp)
- f = c.forms[FCompatibility]
- qck, cfk, dk := f.quickCheck[MComposed], f.combinesForward, string(f.expandedDecomp)
- s := ""
- if d == dk && qc == qck && cf == cfk {
- s = fmt.Sprintf("f(%s, %v, %q)", qc, cf, d)
- } else {
- s = fmt.Sprintf("g(%s, %s, %v, %v, %q, %q)", qc, qck, cf, cfk, d, dk)
- }
- current := lastInfo{c.ccc, c.nLeadingNonStarters, c.nTrailingNonStarters, s}
- if last != current {
- fmt.Fprintf(w, "\t{0x%x, %d, %d, %d, %s},\n", r, c.origCCC, c.nLeadingNonStarters, c.nTrailingNonStarters, s)
- last = current
- }
- }
- fmt.Fprintln(w, "}")
- gen.WriteVersionedGoFile("data_test.go", "norm", w.Bytes())
-}
diff --git a/vendor/golang.org/x/text/unicode/norm/triegen.go b/vendor/golang.org/x/text/unicode/norm/triegen.go
deleted file mode 100644
index 45d7119..0000000
--- a/vendor/golang.org/x/text/unicode/norm/triegen.go
+++ /dev/null
@@ -1,117 +0,0 @@
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build ignore
-
-// Trie table generator.
-// Used by make*tables tools to generate a go file with trie data structures
-// for mapping UTF-8 to a 16-bit value. All but the last byte in a UTF-8 byte
-// sequence are used to lookup offsets in the index table to be used for the
-// next byte. The last byte is used to index into a table with 16-bit values.
-
-package main
-
-import (
- "fmt"
- "io"
-)
-
-const maxSparseEntries = 16
-
-type normCompacter struct {
- sparseBlocks [][]uint64
- sparseOffset []uint16
- sparseCount int
- name string
-}
-
-func mostFrequentStride(a []uint64) int {
- counts := make(map[int]int)
- var v int
- for _, x := range a {
- if stride := int(x) - v; v != 0 && stride >= 0 {
- counts[stride]++
- }
- v = int(x)
- }
- var maxs, maxc int
- for stride, cnt := range counts {
- if cnt > maxc || (cnt == maxc && stride < maxs) {
- maxs, maxc = stride, cnt
- }
- }
- return maxs
-}
-
-func countSparseEntries(a []uint64) int {
- stride := mostFrequentStride(a)
- var v, count int
- for _, tv := range a {
- if int(tv)-v != stride {
- if tv != 0 {
- count++
- }
- }
- v = int(tv)
- }
- return count
-}
-
-func (c *normCompacter) Size(v []uint64) (sz int, ok bool) {
- if n := countSparseEntries(v); n <= maxSparseEntries {
- return (n+1)*4 + 2, true
- }
- return 0, false
-}
-
-func (c *normCompacter) Store(v []uint64) uint32 {
- h := uint32(len(c.sparseOffset))
- c.sparseBlocks = append(c.sparseBlocks, v)
- c.sparseOffset = append(c.sparseOffset, uint16(c.sparseCount))
- c.sparseCount += countSparseEntries(v) + 1
- return h
-}
-
-func (c *normCompacter) Handler() string {
- return c.name + "Sparse.lookup"
-}
-
-func (c *normCompacter) Print(w io.Writer) (retErr error) {
- p := func(f string, x ...interface{}) {
- if _, err := fmt.Fprintf(w, f, x...); retErr == nil && err != nil {
- retErr = err
- }
- }
-
- ls := len(c.sparseBlocks)
- p("// %sSparseOffset: %d entries, %d bytes\n", c.name, ls, ls*2)
- p("var %sSparseOffset = %#v\n\n", c.name, c.sparseOffset)
-
- ns := c.sparseCount
- p("// %sSparseValues: %d entries, %d bytes\n", c.name, ns, ns*4)
- p("var %sSparseValues = [%d]valueRange {", c.name, ns)
- for i, b := range c.sparseBlocks {
- p("\n// Block %#x, offset %#x", i, c.sparseOffset[i])
- var v int
- stride := mostFrequentStride(b)
- n := countSparseEntries(b)
- p("\n{value:%#04x,lo:%#02x},", stride, uint8(n))
- for i, nv := range b {
- if int(nv)-v != stride {
- if v != 0 {
- p(",hi:%#02x},", 0x80+i-1)
- }
- if nv != 0 {
- p("\n{value:%#04x,lo:%#02x", nv, 0x80+i)
- }
- }
- v = int(nv)
- }
- if v != 0 {
- p(",hi:%#02x},", 0x80+len(b)-1)
- }
- }
- p("\n}\n\n")
- return
-}
diff --git a/vendor/modules.txt b/vendor/modules.txt
index e8f4969..408ba12 100644
--- a/vendor/modules.txt
+++ b/vendor/modules.txt
@@ -1,8 +1,8 @@
# github.com/Shopify/sarama v1.26.1
github.com/Shopify/sarama
# github.com/aead/cmac v0.0.0-20160719120800-7af84192f0b1
-github.com/aead/cmac/aes
github.com/aead/cmac
+github.com/aead/cmac/aes
# github.com/cboling/omci v0.1.0
github.com/cboling/omci
github.com/cboling/omci/generated
@@ -16,27 +16,18 @@
github.com/eapache/go-xerial-snappy
# github.com/eapache/queue v1.1.0
github.com/eapache/queue
-# github.com/ghodss/yaml v1.0.0
-github.com/ghodss/yaml
-# github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b
-github.com/golang/glog
# github.com/golang/protobuf v1.3.2
github.com/golang/protobuf/descriptor
-github.com/golang/protobuf/proto
-github.com/golang/protobuf/protoc-gen-go
-github.com/golang/protobuf/protoc-gen-go/descriptor
github.com/golang/protobuf/jsonpb
+github.com/golang/protobuf/proto
+github.com/golang/protobuf/protoc-gen-go/descriptor
+github.com/golang/protobuf/ptypes
github.com/golang/protobuf/ptypes/any
github.com/golang/protobuf/ptypes/duration
+github.com/golang/protobuf/ptypes/empty
+github.com/golang/protobuf/ptypes/struct
github.com/golang/protobuf/ptypes/timestamp
github.com/golang/protobuf/ptypes/wrappers
-github.com/golang/protobuf/ptypes
-github.com/golang/protobuf/ptypes/struct
-github.com/golang/protobuf/ptypes/empty
-github.com/golang/protobuf/protoc-gen-go/generator
-github.com/golang/protobuf/protoc-gen-go/grpc
-github.com/golang/protobuf/protoc-gen-go/plugin
-github.com/golang/protobuf/protoc-gen-go/generator/internal/remap
# github.com/golang/snappy v0.0.1
github.com/golang/snappy
# github.com/google/go-cmp v0.4.0
@@ -52,18 +43,10 @@
# github.com/gorilla/mux v1.7.3
github.com/gorilla/mux
# github.com/grpc-ecosystem/grpc-gateway v1.12.2
+github.com/grpc-ecosystem/grpc-gateway/internal
+github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options
github.com/grpc-ecosystem/grpc-gateway/runtime
github.com/grpc-ecosystem/grpc-gateway/utilities
-github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/options
-github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway
-github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger
-github.com/grpc-ecosystem/grpc-gateway/internal
-github.com/grpc-ecosystem/grpc-gateway/codegenerator
-github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/descriptor
-github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/gengateway
-github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger/genswagger
-github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/httprule
-github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway/generator
# github.com/hashicorp/go-uuid v1.0.2
github.com/hashicorp/go-uuid
# github.com/jcmturner/gofork v1.0.0
@@ -72,17 +55,17 @@
# github.com/jessevdk/go-flags v1.4.0
github.com/jessevdk/go-flags
# github.com/jhump/protoreflect v1.5.0
-github.com/jhump/protoreflect/desc
-github.com/jhump/protoreflect/dynamic
-github.com/jhump/protoreflect/desc/internal
-github.com/jhump/protoreflect/internal
github.com/jhump/protoreflect/codec
+github.com/jhump/protoreflect/desc
+github.com/jhump/protoreflect/desc/internal
+github.com/jhump/protoreflect/dynamic
+github.com/jhump/protoreflect/internal
# github.com/klauspost/compress v1.9.8
-github.com/klauspost/compress/zstd
+github.com/klauspost/compress/fse
github.com/klauspost/compress/huff0
github.com/klauspost/compress/snappy
+github.com/klauspost/compress/zstd
github.com/klauspost/compress/zstd/internal/xxhash
-github.com/klauspost/compress/fse
# github.com/konsorten/go-windows-terminal-sequences v1.0.1
github.com/konsorten/go-windows-terminal-sequences
# github.com/looplab/fsm v0.1.0
@@ -111,41 +94,41 @@
golang.org/x/crypto/md4
golang.org/x/crypto/pbkdf2
# golang.org/x/net v0.0.0-20200202094626-16171245cfb2
-golang.org/x/net/trace
-golang.org/x/net/proxy
-golang.org/x/net/internal/timeseries
+golang.org/x/net/http/httpguts
golang.org/x/net/http2
golang.org/x/net/http2/hpack
-golang.org/x/net/internal/socks
-golang.org/x/net/http/httpguts
golang.org/x/net/idna
+golang.org/x/net/internal/socks
+golang.org/x/net/internal/timeseries
+golang.org/x/net/proxy
+golang.org/x/net/trace
# golang.org/x/sys v0.0.0-20190422165155-953cdadca894
golang.org/x/sys/unix
# golang.org/x/text v0.3.2
golang.org/x/text/secure/bidirule
+golang.org/x/text/transform
golang.org/x/text/unicode/bidi
golang.org/x/text/unicode/norm
-golang.org/x/text/transform
# google.golang.org/genproto v0.0.0-20190927181202-20e1ac93f88c
google.golang.org/genproto/googleapis/api/annotations
google.golang.org/genproto/googleapis/api/httpbody
-google.golang.org/genproto/protobuf/field_mask
google.golang.org/genproto/googleapis/rpc/status
+google.golang.org/genproto/protobuf/field_mask
# google.golang.org/grpc v1.27.0
google.golang.org/grpc
-google.golang.org/grpc/codes
-google.golang.org/grpc/grpclog
-google.golang.org/grpc/status
-google.golang.org/grpc/reflection
-google.golang.org/grpc/metadata
+google.golang.org/grpc/attributes
google.golang.org/grpc/backoff
google.golang.org/grpc/balancer
google.golang.org/grpc/balancer/base
google.golang.org/grpc/balancer/roundrobin
+google.golang.org/grpc/binarylog/grpc_binarylog_v1
+google.golang.org/grpc/codes
google.golang.org/grpc/connectivity
google.golang.org/grpc/credentials
+google.golang.org/grpc/credentials/internal
google.golang.org/grpc/encoding
google.golang.org/grpc/encoding/proto
+google.golang.org/grpc/grpclog
google.golang.org/grpc/internal
google.golang.org/grpc/internal/backoff
google.golang.org/grpc/internal/balancerload
@@ -157,19 +140,19 @@
google.golang.org/grpc/internal/grpcsync
google.golang.org/grpc/internal/resolver/dns
google.golang.org/grpc/internal/resolver/passthrough
+google.golang.org/grpc/internal/syscall
google.golang.org/grpc/internal/transport
google.golang.org/grpc/keepalive
+google.golang.org/grpc/metadata
google.golang.org/grpc/naming
google.golang.org/grpc/peer
+google.golang.org/grpc/reflection
+google.golang.org/grpc/reflection/grpc_reflection_v1alpha
google.golang.org/grpc/resolver
google.golang.org/grpc/serviceconfig
google.golang.org/grpc/stats
+google.golang.org/grpc/status
google.golang.org/grpc/tap
-google.golang.org/grpc/reflection/grpc_reflection_v1alpha
-google.golang.org/grpc/credentials/internal
-google.golang.org/grpc/binarylog/grpc_binarylog_v1
-google.golang.org/grpc/internal/syscall
-google.golang.org/grpc/attributes
# gopkg.in/jcmturner/aescts.v1 v1.0.1
gopkg.in/jcmturner/aescts.v1
# gopkg.in/jcmturner/dnsutils.v1 v1.0.1
@@ -179,32 +162,32 @@
gopkg.in/jcmturner/gokrb5.v7/client
gopkg.in/jcmturner/gokrb5.v7/config
gopkg.in/jcmturner/gokrb5.v7/credentials
-gopkg.in/jcmturner/gokrb5.v7/gssapi
-gopkg.in/jcmturner/gokrb5.v7/iana/chksumtype
-gopkg.in/jcmturner/gokrb5.v7/iana/keyusage
-gopkg.in/jcmturner/gokrb5.v7/keytab
-gopkg.in/jcmturner/gokrb5.v7/messages
-gopkg.in/jcmturner/gokrb5.v7/types
gopkg.in/jcmturner/gokrb5.v7/crypto
-gopkg.in/jcmturner/gokrb5.v7/crypto/etype
-gopkg.in/jcmturner/gokrb5.v7/iana/errorcode
-gopkg.in/jcmturner/gokrb5.v7/iana/flags
-gopkg.in/jcmturner/gokrb5.v7/iana/nametype
-gopkg.in/jcmturner/gokrb5.v7/iana/patype
-gopkg.in/jcmturner/gokrb5.v7/kadmin
-gopkg.in/jcmturner/gokrb5.v7/krberror
-gopkg.in/jcmturner/gokrb5.v7/iana/etypeID
-gopkg.in/jcmturner/gokrb5.v7/iana
-gopkg.in/jcmturner/gokrb5.v7/iana/adtype
-gopkg.in/jcmturner/gokrb5.v7/iana/asnAppTag
-gopkg.in/jcmturner/gokrb5.v7/iana/msgtype
-gopkg.in/jcmturner/gokrb5.v7/pac
-gopkg.in/jcmturner/gokrb5.v7/iana/addrtype
gopkg.in/jcmturner/gokrb5.v7/crypto/common
+gopkg.in/jcmturner/gokrb5.v7/crypto/etype
gopkg.in/jcmturner/gokrb5.v7/crypto/rfc3961
gopkg.in/jcmturner/gokrb5.v7/crypto/rfc3962
gopkg.in/jcmturner/gokrb5.v7/crypto/rfc4757
gopkg.in/jcmturner/gokrb5.v7/crypto/rfc8009
+gopkg.in/jcmturner/gokrb5.v7/gssapi
+gopkg.in/jcmturner/gokrb5.v7/iana
+gopkg.in/jcmturner/gokrb5.v7/iana/addrtype
+gopkg.in/jcmturner/gokrb5.v7/iana/adtype
+gopkg.in/jcmturner/gokrb5.v7/iana/asnAppTag
+gopkg.in/jcmturner/gokrb5.v7/iana/chksumtype
+gopkg.in/jcmturner/gokrb5.v7/iana/errorcode
+gopkg.in/jcmturner/gokrb5.v7/iana/etypeID
+gopkg.in/jcmturner/gokrb5.v7/iana/flags
+gopkg.in/jcmturner/gokrb5.v7/iana/keyusage
+gopkg.in/jcmturner/gokrb5.v7/iana/msgtype
+gopkg.in/jcmturner/gokrb5.v7/iana/nametype
+gopkg.in/jcmturner/gokrb5.v7/iana/patype
+gopkg.in/jcmturner/gokrb5.v7/kadmin
+gopkg.in/jcmturner/gokrb5.v7/keytab
+gopkg.in/jcmturner/gokrb5.v7/krberror
+gopkg.in/jcmturner/gokrb5.v7/messages
+gopkg.in/jcmturner/gokrb5.v7/pac
+gopkg.in/jcmturner/gokrb5.v7/types
# gopkg.in/jcmturner/rpc.v1 v1.1.0
gopkg.in/jcmturner/rpc.v1/mstypes
gopkg.in/jcmturner/rpc.v1/ndr
@@ -213,6 +196,6 @@
# gotest.tools v2.2.0+incompatible
gotest.tools/assert
gotest.tools/assert/cmp
+gotest.tools/internal/difflib
gotest.tools/internal/format
gotest.tools/internal/source
-gotest.tools/internal/difflib