diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json
deleted file mode 100644
index 7505375..0000000
--- a/Godeps/Godeps.json
+++ /dev/null
@@ -1,83 +0,0 @@
-{
- "ImportPath": "github.com/Luzifer/promcertcheck",
- "GoVersion": "go1.7",
- "GodepVersion": "v79",
- "Deps": [
- {
- "ImportPath": "bitbucket.org/ww/goautoneg",
- "Comment": "null-5",
- "Rev": "75cd24fc2f2c2a2088577d12123ddee5f54e0675"
- },
- {
- "ImportPath": "github.com/Luzifer/rconfig",
- "Comment": "v1.2.0",
- "Rev": "7aef1d393c1e2d0758901853b59981c7adc67c7e"
- },
- {
- "ImportPath": "github.com/beorn7/perks/quantile",
- "Rev": "b965b613227fddccbfffe13eae360ed3fa822f8d"
- },
- {
- "ImportPath": "github.com/flosch/pongo2",
- "Comment": "v1.0-rc1-174-gf5d79aa",
- "Rev": "f5d79aa0a914c08eb7f51a96cd7b2dbbe46fca46"
- },
- {
- "ImportPath": "github.com/golang/protobuf/proto",
- "Rev": "aece6fb931241ad332956db4f62798dfbea944b3"
- },
- {
- "ImportPath": "github.com/gorilla/context",
- "Rev": "215affda49addc4c8ef7e2534915df2c8c35c6cd"
- },
- {
- "ImportPath": "github.com/gorilla/mux",
- "Rev": "8096f47503459bcc74d1f4c487b7e6e42e5746b5"
- },
- {
- "ImportPath": "github.com/matttproud/golang_protobuf_extensions/pbutil",
- "Rev": "fc2b8d3a73c4867e51861bbdd5ae3c1f0869dd6a"
- },
- {
- "ImportPath": "github.com/prometheus/client_golang/model",
- "Comment": "0.6.0-17-g3b16b46",
- "Rev": "3b16b46a713f181888e5e9a1205ccc34d6917fb9"
- },
- {
- "ImportPath": "github.com/prometheus/client_golang/prometheus",
- "Comment": "0.6.0-17-g3b16b46",
- "Rev": "3b16b46a713f181888e5e9a1205ccc34d6917fb9"
- },
- {
- "ImportPath": "github.com/prometheus/client_golang/text",
- "Comment": "0.6.0-17-g3b16b46",
- "Rev": "3b16b46a713f181888e5e9a1205ccc34d6917fb9"
- },
- {
- "ImportPath": "github.com/prometheus/client_model/go",
- "Comment": "model-0.0.2-12-gfa8ad6f",
- "Rev": "fa8ad6fec33561be4280a8f0514318c79d7f6cb6"
- },
- {
- "ImportPath": "github.com/prometheus/procfs",
- "Rev": "c91d8eefde16bd047416409eb56353ea84a186e4"
- },
- {
- "ImportPath": "github.com/robfig/cron",
- "Comment": "v1-2-g67823cd",
- "Rev": "67823cd24dece1b04cced3a0a0b3ca2bc84d875e"
- },
- {
- "ImportPath": "github.com/spf13/pflag",
- "Rev": "8e7dc108ab3a1ab6ce6d922bbaff5657b88e8e49"
- },
- {
- "ImportPath": "gopkg.in/validator.v2",
- "Rev": "07ffaad256c8e957050ad83d6472eb97d785013d"
- },
- {
- "ImportPath": "gopkg.in/yaml.v2",
- "Rev": "31c299268d302dd0aa9a0dcf765a3d58971ac83f"
- }
- ]
-}
diff --git a/Godeps/Readme b/Godeps/Readme
deleted file mode 100644
index 4cdaa53..0000000
--- a/Godeps/Readme
+++ /dev/null
@@ -1,5 +0,0 @@
-This directory tree is generated automatically by godep.
-
-Please do not edit.
-
-See https://github.com/tools/godep for more information.
diff --git a/Gopkg.lock b/Gopkg.lock
new file mode 100644
index 0000000..d24da23
--- /dev/null
+++ b/Gopkg.lock
@@ -0,0 +1,117 @@
+# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
+
+
+[[projects]]
+ name = "github.com/Luzifer/rconfig"
+ packages = ["."]
+ revision = "7aef1d393c1e2d0758901853b59981c7adc67c7e"
+ version = "v1.2.0"
+
+[[projects]]
+ branch = "master"
+ name = "github.com/beorn7/perks"
+ packages = ["quantile"]
+ revision = "4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9"
+
+[[projects]]
+ name = "github.com/flosch/pongo2"
+ packages = ["."]
+ revision = "5e81b817a0c48c1c57cdf1a9056cf76bdee02ca9"
+ version = "v3.0"
+
+[[projects]]
+ branch = "master"
+ name = "github.com/golang/protobuf"
+ packages = ["proto"]
+ revision = "1643683e1b54a9e88ad26d98f81400c8c9d9f4f9"
+
+[[projects]]
+ name = "github.com/gorilla/context"
+ packages = ["."]
+ revision = "1ea25387ff6f684839d82767c1733ff4d4d15d0a"
+ version = "v1.1"
+
+[[projects]]
+ name = "github.com/gorilla/mux"
+ packages = ["."]
+ revision = "24fca303ac6da784b9e8269f724ddeb0b2eea5e7"
+ version = "v1.5.0"
+
+[[projects]]
+ name = "github.com/matttproud/golang_protobuf_extensions"
+ packages = ["pbutil"]
+ revision = "3247c84500bff8d9fb6d579d800f20b3e091582c"
+ version = "v1.0.0"
+
+[[projects]]
+ name = "github.com/prometheus/client_golang"
+ packages = ["prometheus"]
+ revision = "c5b7fccd204277076155f10851dad72b76a49317"
+ version = "v0.8.0"
+
+[[projects]]
+ branch = "master"
+ name = "github.com/prometheus/client_model"
+ packages = ["go"]
+ revision = "6f3806018612930941127f2a7c6c453ba2c527d2"
+
+[[projects]]
+ branch = "master"
+ name = "github.com/prometheus/common"
+ packages = ["expfmt","internal/bitbucket.org/ww/goautoneg","model"]
+ revision = "e3fb1a1acd7605367a2b378bc2e2f893c05174b7"
+
+[[projects]]
+ branch = "master"
+ name = "github.com/prometheus/procfs"
+ packages = [".","xfs"]
+ revision = "a6e9df898b1336106c743392c48ee0b71f5c4efa"
+
+[[projects]]
+ name = "github.com/robfig/cron"
+ packages = ["."]
+ revision = "b024fc5ea0e34bc3f83d9941c8d60b0622bfaca4"
+ version = "v1"
+
+[[projects]]
+ name = "github.com/sirupsen/logrus"
+ packages = ["."]
+ revision = "f006c2ac4710855cf0f916dd6b77acf6b048dc6e"
+ version = "v1.0.3"
+
+[[projects]]
+ name = "github.com/spf13/pflag"
+ packages = ["."]
+ revision = "e57e3eeb33f795204c1ca35f56c44f83227c6e66"
+ version = "v1.0.0"
+
+[[projects]]
+ branch = "master"
+ name = "golang.org/x/crypto"
+ packages = ["ssh/terminal"]
+ revision = "bd6f299fb381e4c3393d1c4b1f0b94f5e77650c8"
+
+[[projects]]
+ branch = "master"
+ name = "golang.org/x/sys"
+ packages = ["unix","windows"]
+ revision = "8eb05f94d449fdf134ec24630ce69ada5b469c1c"
+
+[[projects]]
+ branch = "v2"
+ name = "gopkg.in/validator.v2"
+ packages = ["."]
+ revision = "460c83432a98c35224a6fe352acf8b23e067ad06"
+
+[[projects]]
+ branch = "v2"
+ name = "gopkg.in/yaml.v2"
+ packages = ["."]
+ revision = "eb3733d160e74a9c7e442f435eb3bea458e1d19f"
+
+[solve-meta]
+ analyzer-name = "dep"
+ analyzer-version = 1
+ inputs-digest = "d0a90698569f49d4e7ef58586b857a1c7c60e48eaca07f1585d02e7ce91ca092"
+ solver-name = "gps-cdcl"
+ solver-version = 1
diff --git a/Gopkg.toml b/Gopkg.toml
new file mode 100644
index 0000000..d4dd19b
--- /dev/null
+++ b/Gopkg.toml
@@ -0,0 +1,42 @@
+
+# Gopkg.toml example
+#
+# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md
+# for detailed Gopkg.toml documentation.
+#
+# required = ["github.com/user/thing/cmd/thing"]
+# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"]
+#
+# [[constraint]]
+# name = "github.com/user/project"
+# version = "1.0.0"
+#
+# [[constraint]]
+# name = "github.com/user/project2"
+# branch = "dev"
+# source = "github.com/myfork/project2"
+#
+# [[override]]
+# name = "github.com/x/y"
+# version = "2.4.0"
+
+
+[[constraint]]
+ name = "github.com/Luzifer/rconfig"
+ version = "1.2.0"
+
+[[constraint]]
+ name = "github.com/flosch/pongo2"
+
+[[constraint]]
+ name = "github.com/gorilla/mux"
+
+[[constraint]]
+ name = "github.com/prometheus/client_golang"
+
+[[constraint]]
+ name = "github.com/robfig/cron"
+
+[[constraint]]
+ name = "github.com/sirupsen/logrus"
+ version = "1.0.3"
diff --git a/promcertcheck b/promcertcheck
index e5db544..5f64e3e 100755
Binary files a/promcertcheck and b/promcertcheck differ
diff --git a/vendor/bitbucket.org/ww/goautoneg/Makefile b/vendor/bitbucket.org/ww/goautoneg/Makefile
deleted file mode 100644
index e33ee17..0000000
--- a/vendor/bitbucket.org/ww/goautoneg/Makefile
+++ /dev/null
@@ -1,13 +0,0 @@
-include $(GOROOT)/src/Make.inc
-
-TARG=bitbucket.org/ww/goautoneg
-GOFILES=autoneg.go
-
-include $(GOROOT)/src/Make.pkg
-
-format:
- gofmt -w *.go
-
-docs:
- gomake clean
- godoc ${TARG} > README.txt
diff --git a/vendor/github.com/Luzifer/rconfig/bool_test.go b/vendor/github.com/Luzifer/rconfig/bool_test.go
new file mode 100644
index 0000000..11a6f4b
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/bool_test.go
@@ -0,0 +1,70 @@
+package rconfig
+
+import (
+ "os"
+
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Testing bool parsing", func() {
+ type t struct {
+ Test1 bool `default:"true"`
+ Test2 bool `default:"false" flag:"test2"`
+ Test3 bool `default:"true" flag:"test3,t"`
+ Test4 bool `flag:"test4"`
+ }
+
+ var (
+ err error
+ args []string
+ cfg t
+ )
+
+ BeforeEach(func() {
+ cfg = t{}
+ args = []string{
+ "--test2",
+ "-t",
+ }
+ })
+
+ JustBeforeEach(func() {
+ err = parse(&cfg, args)
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values", func() {
+ Expect(cfg.Test1).To(Equal(true))
+ Expect(cfg.Test2).To(Equal(true))
+ Expect(cfg.Test3).To(Equal(true))
+ Expect(cfg.Test4).To(Equal(false))
+ })
+})
+
+var _ = Describe("Testing to set bool from ENV with default", func() {
+ type t struct {
+ Test1 bool `default:"true" env:"TEST1"`
+ }
+
+ var (
+ err error
+ args []string
+ cfg t
+ )
+
+ BeforeEach(func() {
+ cfg = t{}
+ args = []string{}
+ })
+
+ JustBeforeEach(func() {
+ os.Unsetenv("TEST1")
+ err = parse(&cfg, args)
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values", func() {
+ Expect(cfg.Test1).To(Equal(true))
+ })
+})
diff --git a/vendor/github.com/Luzifer/rconfig/duration_test.go b/vendor/github.com/Luzifer/rconfig/duration_test.go
new file mode 100644
index 0000000..1ca95dc
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/duration_test.go
@@ -0,0 +1,41 @@
+package rconfig
+
+import (
+ "time"
+
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Duration", func() {
+ type t struct {
+ Test time.Duration `flag:"duration"`
+ TestS time.Duration `flag:"other-duration,o"`
+ TestDef time.Duration `default:"30h"`
+ }
+
+ var (
+ err error
+ args []string
+ cfg t
+ )
+
+ BeforeEach(func() {
+ cfg = t{}
+ args = []string{
+ "--duration=23s", "-o", "45m",
+ }
+ })
+
+ JustBeforeEach(func() {
+ err = parse(&cfg, args)
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values", func() {
+ Expect(cfg.Test).To(Equal(23 * time.Second))
+ Expect(cfg.TestS).To(Equal(45 * time.Minute))
+
+ Expect(cfg.TestDef).To(Equal(30 * time.Hour))
+ })
+})
diff --git a/vendor/github.com/Luzifer/rconfig/errors_test.go b/vendor/github.com/Luzifer/rconfig/errors_test.go
new file mode 100644
index 0000000..46db039
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/errors_test.go
@@ -0,0 +1,56 @@
+package rconfig
+
+import (
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Testing errors", func() {
+
+ It("should not accept string as int", func() {
+ Expect(parse(&struct {
+ A int `default:"a"`
+ }{}, []string{})).To(HaveOccurred())
+ })
+
+ It("should not accept string as float", func() {
+ Expect(parse(&struct {
+ A float32 `default:"a"`
+ }{}, []string{})).To(HaveOccurred())
+ })
+
+ It("should not accept string as uint", func() {
+ Expect(parse(&struct {
+ A uint `default:"a"`
+ }{}, []string{})).To(HaveOccurred())
+ })
+
+ It("should not accept string as uint in sub-struct", func() {
+ Expect(parse(&struct {
+ B struct {
+ A uint `default:"a"`
+ }
+ }{}, []string{})).To(HaveOccurred())
+ })
+
+ It("should not accept string slice as int slice", func() {
+ Expect(parse(&struct {
+ A []int `default:"a,bn"`
+ }{}, []string{})).To(HaveOccurred())
+ })
+
+ It("should not accept variables not being pointers", func() {
+ cfg := struct {
+ A string `default:"a"`
+ }{}
+
+ Expect(parse(cfg, []string{})).To(HaveOccurred())
+ })
+
+ It("should not accept variables not being pointers to structs", func() {
+ cfg := "test"
+
+ Expect(parse(cfg, []string{})).To(HaveOccurred())
+ })
+
+})
diff --git a/vendor/github.com/Luzifer/rconfig/example_test.go b/vendor/github.com/Luzifer/rconfig/example_test.go
new file mode 100644
index 0000000..0a65b2f
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/example_test.go
@@ -0,0 +1,37 @@
+package rconfig
+
+import (
+ "fmt"
+ "os"
+)
+
+func ExampleParse() {
+ // We're building an example configuration with a sub-struct to be filled
+ // by the Parse command.
+ config := struct {
+ Username string `default:"unknown" flag:"user,u" description:"Your name"`
+ Details struct {
+ Age int `default:"25" flag:"age" description:"Your age"`
+ }
+ }{}
+
+ // To have more relieable results we're setting os.Args to a known value.
+ // In real-life use cases you wouldn't do this but parse the original
+ // commandline arguments.
+ os.Args = []string{
+ "example",
+ "--user=Luzifer",
+ }
+
+ Parse(&config)
+
+ fmt.Printf("Hello %s, happy birthday for your %dth birthday.",
+ config.Username,
+ config.Details.Age)
+
+ // You can also show an usage message for your user
+ Usage()
+
+ // Output:
+ // Hello Luzifer, happy birthday for your 25th birthday.
+}
diff --git a/vendor/github.com/Luzifer/rconfig/float_test.go b/vendor/github.com/Luzifer/rconfig/float_test.go
new file mode 100644
index 0000000..4ec8a1e
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/float_test.go
@@ -0,0 +1,44 @@
+package rconfig
+
+import (
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Testing float parsing", func() {
+ type t struct {
+ Test32 float32 `flag:"float32"`
+ Test32P float32 `flag:"float32p,3"`
+ Test64 float64 `flag:"float64"`
+ Test64P float64 `flag:"float64p,6"`
+ TestDef float32 `default:"66.256"`
+ }
+
+ var (
+ err error
+ args []string
+ cfg t
+ )
+
+ BeforeEach(func() {
+ cfg = t{}
+ args = []string{
+ "--float32=5.5", "-3", "6.6",
+ "--float64=7.7", "-6", "8.8",
+ }
+ })
+
+ JustBeforeEach(func() {
+ err = parse(&cfg, args)
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values", func() {
+ Expect(cfg.Test32).To(Equal(float32(5.5)))
+ Expect(cfg.Test32P).To(Equal(float32(6.6)))
+ Expect(cfg.Test64).To(Equal(float64(7.7)))
+ Expect(cfg.Test64P).To(Equal(float64(8.8)))
+
+ Expect(cfg.TestDef).To(Equal(float32(66.256)))
+ })
+})
diff --git a/vendor/github.com/Luzifer/rconfig/general_test.go b/vendor/github.com/Luzifer/rconfig/general_test.go
new file mode 100644
index 0000000..e7f29b7
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/general_test.go
@@ -0,0 +1,128 @@
+package rconfig
+
+import (
+ "os"
+
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Testing general parsing", func() {
+ type t struct {
+ Test string `default:"foo" env:"shell" flag:"shell" description:"Test"`
+ Test2 string `default:"blub" env:"testvar" flag:"testvar,t" description:"Test"`
+ DefaultFlag string `default:"goo"`
+ SadFlag string
+ }
+
+ type tValidated struct {
+ Test string `flag:"test" default:"" validate:"nonzero"`
+ }
+
+ var (
+ err error
+ args []string
+ cfg t
+ )
+
+ Context("with defined arguments", func() {
+ BeforeEach(func() {
+ cfg = t{}
+ args = []string{
+ "--shell=test23",
+ "-t", "bla",
+ }
+ })
+
+ JustBeforeEach(func() {
+ err = parse(&cfg, args)
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have parsed the expected values", func() {
+ Expect(cfg.Test).To(Equal("test23"))
+ Expect(cfg.Test2).To(Equal("bla"))
+ Expect(cfg.SadFlag).To(Equal(""))
+ Expect(cfg.DefaultFlag).To(Equal("goo"))
+ })
+ })
+
+ Context("with no arguments", func() {
+ BeforeEach(func() {
+ cfg = t{}
+ args = []string{}
+ })
+
+ JustBeforeEach(func() {
+ err = parse(&cfg, args)
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have used the default value", func() {
+ Expect(cfg.Test).To(Equal("foo"))
+ })
+ })
+
+ Context("with no arguments and set env", func() {
+ BeforeEach(func() {
+ cfg = t{}
+ args = []string{}
+ os.Setenv("shell", "test546")
+ })
+
+ AfterEach(func() {
+ os.Unsetenv("shell")
+ })
+
+ JustBeforeEach(func() {
+ err = parse(&cfg, args)
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have used the value from env", func() {
+ Expect(cfg.Test).To(Equal("test546"))
+ })
+ })
+
+ Context("with additional arguments", func() {
+ BeforeEach(func() {
+ cfg = t{}
+ args = []string{
+ "--shell=test23",
+ "-t", "bla",
+ "positional1", "positional2",
+ }
+ })
+
+ JustBeforeEach(func() {
+ err = parse(&cfg, args)
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have parsed the expected values", func() {
+ Expect(cfg.Test).To(Equal("test23"))
+ Expect(cfg.Test2).To(Equal("bla"))
+ Expect(cfg.SadFlag).To(Equal(""))
+ Expect(cfg.DefaultFlag).To(Equal("goo"))
+ })
+ It("should have detected the positional arguments", func() {
+ Expect(Args()).To(Equal([]string{"positional1", "positional2"}))
+ })
+ })
+
+ Context("making use of the validator package", func() {
+ var cfgValidated tValidated
+
+ BeforeEach(func() {
+ cfgValidated = tValidated{}
+ args = []string{}
+ })
+
+ JustBeforeEach(func() {
+ err = parseAndValidate(&cfgValidated, args)
+ })
+
+ It("should have errored", func() { Expect(err).To(HaveOccurred()) })
+ })
+
+})
diff --git a/vendor/github.com/Luzifer/rconfig/int_test.go b/vendor/github.com/Luzifer/rconfig/int_test.go
new file mode 100644
index 0000000..2cc0022
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/int_test.go
@@ -0,0 +1,54 @@
+package rconfig
+
+import (
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Testing int parsing", func() {
+ type t struct {
+ Test int `flag:"int"`
+ TestP int `flag:"intp,i"`
+ Test8 int8 `flag:"int8"`
+ Test8P int8 `flag:"int8p,8"`
+ Test32 int32 `flag:"int32"`
+ Test32P int32 `flag:"int32p,3"`
+ Test64 int64 `flag:"int64"`
+ Test64P int64 `flag:"int64p,6"`
+ TestDef int8 `default:"66"`
+ }
+
+ var (
+ err error
+ args []string
+ cfg t
+ )
+
+ BeforeEach(func() {
+ cfg = t{}
+ args = []string{
+ "--int=1", "-i", "2",
+ "--int8=3", "-8", "4",
+ "--int32=5", "-3", "6",
+ "--int64=7", "-6", "8",
+ }
+ })
+
+ JustBeforeEach(func() {
+ err = parse(&cfg, args)
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values", func() {
+ Expect(cfg.Test).To(Equal(1))
+ Expect(cfg.TestP).To(Equal(2))
+ Expect(cfg.Test8).To(Equal(int8(3)))
+ Expect(cfg.Test8P).To(Equal(int8(4)))
+ Expect(cfg.Test32).To(Equal(int32(5)))
+ Expect(cfg.Test32P).To(Equal(int32(6)))
+ Expect(cfg.Test64).To(Equal(int64(7)))
+ Expect(cfg.Test64P).To(Equal(int64(8)))
+
+ Expect(cfg.TestDef).To(Equal(int8(66)))
+ })
+})
diff --git a/vendor/github.com/Luzifer/rconfig/os-args_test.go b/vendor/github.com/Luzifer/rconfig/os-args_test.go
new file mode 100644
index 0000000..eacee71
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/os-args_test.go
@@ -0,0 +1,40 @@
+package rconfig_test
+
+import (
+ "os"
+
+ . "github.com/Luzifer/rconfig"
+
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Testing os.Args", func() {
+ type t struct {
+ A string `default:"a" flag:"a"`
+ }
+
+ var (
+ err error
+ cfg t
+ )
+
+ JustBeforeEach(func() {
+ err = Parse(&cfg)
+ })
+
+ Context("With only valid arguments", func() {
+
+ BeforeEach(func() {
+ cfg = t{}
+ os.Args = []string{"--a=bar"}
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values", func() {
+ Expect(cfg.A).To(Equal("bar"))
+ })
+
+ })
+
+})
diff --git a/vendor/github.com/Luzifer/rconfig/precedence_test.go b/vendor/github.com/Luzifer/rconfig/precedence_test.go
new file mode 100644
index 0000000..6d87ca0
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/precedence_test.go
@@ -0,0 +1,87 @@
+package rconfig
+
+import (
+ "os"
+
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Precedence", func() {
+
+ type t struct {
+ A int `default:"1" vardefault:"a" env:"a" flag:"avar,a" description:"a"`
+ }
+
+ var (
+ err error
+ cfg t
+ args []string
+ vardefaults map[string]string
+ )
+
+ JustBeforeEach(func() {
+ cfg = t{}
+ SetVariableDefaults(vardefaults)
+ err = parse(&cfg, args)
+ })
+
+ Context("Provided: Flag, Env, Default, VarDefault", func() {
+ BeforeEach(func() {
+ args = []string{"-a", "5"}
+ os.Setenv("a", "8")
+ vardefaults = map[string]string{
+ "a": "3",
+ }
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have used the flag value", func() {
+ Expect(cfg.A).To(Equal(5))
+ })
+ })
+
+ Context("Provided: Env, Default, VarDefault", func() {
+ BeforeEach(func() {
+ args = []string{}
+ os.Setenv("a", "8")
+ vardefaults = map[string]string{
+ "a": "3",
+ }
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have used the env value", func() {
+ Expect(cfg.A).To(Equal(8))
+ })
+ })
+
+ Context("Provided: Default, VarDefault", func() {
+ BeforeEach(func() {
+ args = []string{}
+ os.Unsetenv("a")
+ vardefaults = map[string]string{
+ "a": "3",
+ }
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have used the vardefault value", func() {
+ Expect(cfg.A).To(Equal(3))
+ })
+ })
+
+ Context("Provided: Default", func() {
+ BeforeEach(func() {
+ args = []string{}
+ os.Unsetenv("a")
+ vardefaults = map[string]string{}
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have used the default value", func() {
+ Expect(cfg.A).To(Equal(1))
+ })
+ })
+
+})
diff --git a/vendor/github.com/Luzifer/rconfig/rconfig_suite_test.go b/vendor/github.com/Luzifer/rconfig/rconfig_suite_test.go
new file mode 100644
index 0000000..72c9ce4
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/rconfig_suite_test.go
@@ -0,0 +1,13 @@
+package rconfig_test
+
+import (
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+
+ "testing"
+)
+
+func TestRconfig(t *testing.T) {
+ RegisterFailHandler(Fail)
+ RunSpecs(t, "Rconfig Suite")
+}
diff --git a/vendor/github.com/Luzifer/rconfig/slice_test.go b/vendor/github.com/Luzifer/rconfig/slice_test.go
new file mode 100644
index 0000000..7d9524e
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/slice_test.go
@@ -0,0 +1,51 @@
+package rconfig
+
+import (
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Testing slices", func() {
+ type t struct {
+ Int []int `default:"1,2,3" flag:"int"`
+ String []string `default:"a,b,c" flag:"string"`
+ IntP []int `default:"1,2,3" flag:"intp,i"`
+ StringP []string `default:"a,b,c" flag:"stringp,s"`
+ }
+
+ var (
+ err error
+ args []string
+ cfg t
+ )
+
+ BeforeEach(func() {
+ cfg = t{}
+ args = []string{
+ "--int=4,5", "-s", "hallo,welt",
+ }
+ })
+
+ JustBeforeEach(func() {
+ err = parse(&cfg, args)
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values for int-slice", func() {
+ Expect(len(cfg.Int)).To(Equal(2))
+ Expect(cfg.Int).To(Equal([]int{4, 5}))
+ Expect(cfg.Int).NotTo(Equal([]int{5, 4}))
+ })
+ It("should have the expected values for int-shorthand-slice", func() {
+ Expect(len(cfg.IntP)).To(Equal(3))
+ Expect(cfg.IntP).To(Equal([]int{1, 2, 3}))
+ })
+ It("should have the expected values for string-slice", func() {
+ Expect(len(cfg.String)).To(Equal(3))
+ Expect(cfg.String).To(Equal([]string{"a", "b", "c"}))
+ })
+ It("should have the expected values for string-shorthand-slice", func() {
+ Expect(len(cfg.StringP)).To(Equal(2))
+ Expect(cfg.StringP).To(Equal([]string{"hallo", "welt"}))
+ })
+})
diff --git a/vendor/github.com/Luzifer/rconfig/sub-struct_test.go b/vendor/github.com/Luzifer/rconfig/sub-struct_test.go
new file mode 100644
index 0000000..cfbfbc2
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/sub-struct_test.go
@@ -0,0 +1,36 @@
+package rconfig
+
+import (
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Testing sub-structs", func() {
+ type t struct {
+ Test string `default:"blubb"`
+ Sub struct {
+ Test string `default:"Hallo"`
+ }
+ }
+
+ var (
+ err error
+ args []string
+ cfg t
+ )
+
+ BeforeEach(func() {
+ cfg = t{}
+ args = []string{}
+ })
+
+ JustBeforeEach(func() {
+ err = parse(&cfg, args)
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values", func() {
+ Expect(cfg.Test).To(Equal("blubb"))
+ Expect(cfg.Sub.Test).To(Equal("Hallo"))
+ })
+})
diff --git a/vendor/github.com/Luzifer/rconfig/uint_test.go b/vendor/github.com/Luzifer/rconfig/uint_test.go
new file mode 100644
index 0000000..886db1d
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/uint_test.go
@@ -0,0 +1,59 @@
+package rconfig
+
+import (
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Testing uint parsing", func() {
+ type t struct {
+ Test uint `flag:"int"`
+ TestP uint `flag:"intp,i"`
+ Test8 uint8 `flag:"int8"`
+ Test8P uint8 `flag:"int8p,8"`
+ Test16 uint16 `flag:"int16"`
+ Test16P uint16 `flag:"int16p,1"`
+ Test32 uint32 `flag:"int32"`
+ Test32P uint32 `flag:"int32p,3"`
+ Test64 uint64 `flag:"int64"`
+ Test64P uint64 `flag:"int64p,6"`
+ TestDef uint8 `default:"66"`
+ }
+
+ var (
+ err error
+ args []string
+ cfg t
+ )
+
+ BeforeEach(func() {
+ cfg = t{}
+ args = []string{
+ "--int=1", "-i", "2",
+ "--int8=3", "-8", "4",
+ "--int32=5", "-3", "6",
+ "--int64=7", "-6", "8",
+ "--int16=9", "-1", "10",
+ }
+ })
+
+ JustBeforeEach(func() {
+ err = parse(&cfg, args)
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values", func() {
+ Expect(cfg.Test).To(Equal(uint(1)))
+ Expect(cfg.TestP).To(Equal(uint(2)))
+ Expect(cfg.Test8).To(Equal(uint8(3)))
+ Expect(cfg.Test8P).To(Equal(uint8(4)))
+ Expect(cfg.Test32).To(Equal(uint32(5)))
+ Expect(cfg.Test32P).To(Equal(uint32(6)))
+ Expect(cfg.Test64).To(Equal(uint64(7)))
+ Expect(cfg.Test64P).To(Equal(uint64(8)))
+ Expect(cfg.Test16).To(Equal(uint16(9)))
+ Expect(cfg.Test16P).To(Equal(uint16(10)))
+
+ Expect(cfg.TestDef).To(Equal(uint8(66)))
+ })
+})
diff --git a/vendor/github.com/Luzifer/rconfig/vardefault_test.go b/vendor/github.com/Luzifer/rconfig/vardefault_test.go
new file mode 100644
index 0000000..8328919
--- /dev/null
+++ b/vendor/github.com/Luzifer/rconfig/vardefault_test.go
@@ -0,0 +1,122 @@
+package rconfig
+
+import (
+ "io/ioutil"
+ "os"
+
+ . "github.com/onsi/ginkgo"
+ . "github.com/onsi/gomega"
+)
+
+var _ = Describe("Testing variable defaults", func() {
+
+ type t struct {
+ MySecretValue string `default:"secret" env:"foo" vardefault:"my_secret_value"`
+ MyUsername string `default:"luzifer" vardefault:"username"`
+ SomeVar string `flag:"var" description:"some variable"`
+ IntVar int64 `vardefault:"int_var" default:"23"`
+ }
+
+ var (
+ err error
+ cfg t
+ args = []string{}
+ vardefaults = map[string]string{
+ "my_secret_value": "veryverysecretkey",
+ "unkownkey": "hi there",
+ "int_var": "42",
+ }
+ )
+
+ BeforeEach(func() {
+ cfg = t{}
+ })
+
+ JustBeforeEach(func() {
+ err = parse(&cfg, args)
+ })
+
+ Context("With manually provided variables", func() {
+ BeforeEach(func() {
+ SetVariableDefaults(vardefaults)
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values", func() {
+ Expect(cfg.IntVar).To(Equal(int64(42)))
+ Expect(cfg.MySecretValue).To(Equal("veryverysecretkey"))
+ Expect(cfg.MyUsername).To(Equal("luzifer"))
+ Expect(cfg.SomeVar).To(Equal(""))
+ })
+ })
+
+ Context("With defaults from YAML data", func() {
+ BeforeEach(func() {
+ yamlData := []byte("---\nmy_secret_value: veryverysecretkey\nunknownkey: hi there\nint_var: 42\n")
+ SetVariableDefaults(VarDefaultsFromYAML(yamlData))
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values", func() {
+ Expect(cfg.IntVar).To(Equal(int64(42)))
+ Expect(cfg.MySecretValue).To(Equal("veryverysecretkey"))
+ Expect(cfg.MyUsername).To(Equal("luzifer"))
+ Expect(cfg.SomeVar).To(Equal(""))
+ })
+ })
+
+ Context("With defaults from YAML file", func() {
+ var tmp *os.File
+
+ BeforeEach(func() {
+ tmp, _ = ioutil.TempFile("", "")
+ yamlData := "---\nmy_secret_value: veryverysecretkey\nunknownkey: hi there\nint_var: 42\n"
+ tmp.WriteString(yamlData)
+ SetVariableDefaults(VarDefaultsFromYAMLFile(tmp.Name()))
+ })
+
+ AfterEach(func() {
+ tmp.Close()
+ os.Remove(tmp.Name())
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values", func() {
+ Expect(cfg.IntVar).To(Equal(int64(42)))
+ Expect(cfg.MySecretValue).To(Equal("veryverysecretkey"))
+ Expect(cfg.MyUsername).To(Equal("luzifer"))
+ Expect(cfg.SomeVar).To(Equal(""))
+ })
+ })
+
+ Context("With defaults from invalid YAML data", func() {
+ BeforeEach(func() {
+ yamlData := []byte("---\nmy_secret_value = veryverysecretkey\nunknownkey = hi there\nint_var = 42\n")
+ SetVariableDefaults(VarDefaultsFromYAML(yamlData))
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values", func() {
+ Expect(cfg.IntVar).To(Equal(int64(23)))
+ Expect(cfg.MySecretValue).To(Equal("secret"))
+ Expect(cfg.MyUsername).To(Equal("luzifer"))
+ Expect(cfg.SomeVar).To(Equal(""))
+ })
+ })
+
+ Context("With defaults from non existent YAML file", func() {
+ BeforeEach(func() {
+ file := "/tmp/this_file_should_not_exist_146e26723r"
+ SetVariableDefaults(VarDefaultsFromYAMLFile(file))
+ })
+
+ It("should not have errored", func() { Expect(err).NotTo(HaveOccurred()) })
+ It("should have the expected values", func() {
+ Expect(cfg.IntVar).To(Equal(int64(23)))
+ Expect(cfg.MySecretValue).To(Equal("secret"))
+ Expect(cfg.MyUsername).To(Equal("luzifer"))
+ Expect(cfg.SomeVar).To(Equal(""))
+ })
+ })
+
+})
diff --git a/vendor/github.com/beorn7/perks/.gitignore b/vendor/github.com/beorn7/perks/.gitignore
new file mode 100644
index 0000000..1bd9209
--- /dev/null
+++ b/vendor/github.com/beorn7/perks/.gitignore
@@ -0,0 +1,2 @@
+*.test
+*.prof
diff --git a/vendor/github.com/beorn7/perks/LICENSE b/vendor/github.com/beorn7/perks/LICENSE
new file mode 100644
index 0000000..339177b
--- /dev/null
+++ b/vendor/github.com/beorn7/perks/LICENSE
@@ -0,0 +1,20 @@
+Copyright (C) 2013 Blake Mizerany
+
+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.
diff --git a/vendor/github.com/beorn7/perks/README.md b/vendor/github.com/beorn7/perks/README.md
new file mode 100644
index 0000000..fc05777
--- /dev/null
+++ b/vendor/github.com/beorn7/perks/README.md
@@ -0,0 +1,31 @@
+# Perks for Go (golang.org)
+
+Perks contains the Go package quantile that computes approximate quantiles over
+an unbounded data stream within low memory and CPU bounds.
+
+For more information and examples, see:
+http://godoc.org/github.com/bmizerany/perks
+
+A very special thank you and shout out to Graham Cormode (Rutgers University),
+Flip Korn (AT&T Labs–Research), S. Muthukrishnan (Rutgers University), and
+Divesh Srivastava (AT&T Labs–Research) for their research and publication of
+[Effective Computation of Biased Quantiles over Data Streams](http://www.cs.rutgers.edu/~muthu/bquant.pdf)
+
+Thank you, also:
+* Armon Dadgar (@armon)
+* Andrew Gerrand (@nf)
+* Brad Fitzpatrick (@bradfitz)
+* Keith Rarick (@kr)
+
+FAQ:
+
+Q: Why not move the quantile package into the project root?
+A: I want to add more packages to perks later.
+
+Copyright (C) 2013 Blake Mizerany
+
+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.
diff --git a/vendor/github.com/beorn7/perks/histogram/bench_test.go b/vendor/github.com/beorn7/perks/histogram/bench_test.go
new file mode 100644
index 0000000..56c7e55
--- /dev/null
+++ b/vendor/github.com/beorn7/perks/histogram/bench_test.go
@@ -0,0 +1,26 @@
+package histogram
+
+import (
+ "math/rand"
+ "testing"
+)
+
+func BenchmarkInsert10Bins(b *testing.B) {
+ b.StopTimer()
+ h := New(10)
+ b.StartTimer()
+ for i := 0; i < b.N; i++ {
+ f := rand.ExpFloat64()
+ h.Insert(f)
+ }
+}
+
+func BenchmarkInsert100Bins(b *testing.B) {
+ b.StopTimer()
+ h := New(100)
+ b.StartTimer()
+ for i := 0; i < b.N; i++ {
+ f := rand.ExpFloat64()
+ h.Insert(f)
+ }
+}
diff --git a/vendor/github.com/beorn7/perks/histogram/histogram.go b/vendor/github.com/beorn7/perks/histogram/histogram.go
new file mode 100644
index 0000000..bef05c7
--- /dev/null
+++ b/vendor/github.com/beorn7/perks/histogram/histogram.go
@@ -0,0 +1,108 @@
+// Package histogram provides a Go implementation of BigML's histogram package
+// for Clojure/Java. It is currently experimental.
+package histogram
+
+import (
+ "container/heap"
+ "math"
+ "sort"
+)
+
+type Bin struct {
+ Count int
+ Sum float64
+}
+
+func (b *Bin) Update(x *Bin) {
+ b.Count += x.Count
+ b.Sum += x.Sum
+}
+
+func (b *Bin) Mean() float64 {
+ return b.Sum / float64(b.Count)
+}
+
+type Bins []*Bin
+
+func (bs Bins) Len() int { return len(bs) }
+func (bs Bins) Less(i, j int) bool { return bs[i].Mean() < bs[j].Mean() }
+func (bs Bins) Swap(i, j int) { bs[i], bs[j] = bs[j], bs[i] }
+
+func (bs *Bins) Push(x interface{}) {
+ *bs = append(*bs, x.(*Bin))
+}
+
+func (bs *Bins) Pop() interface{} {
+ return bs.remove(len(*bs) - 1)
+}
+
+func (bs *Bins) remove(n int) *Bin {
+ if n < 0 || len(*bs) < n {
+ return nil
+ }
+ x := (*bs)[n]
+ *bs = append((*bs)[:n], (*bs)[n+1:]...)
+ return x
+}
+
+type Histogram struct {
+ res *reservoir
+}
+
+func New(maxBins int) *Histogram {
+ return &Histogram{res: newReservoir(maxBins)}
+}
+
+func (h *Histogram) Insert(f float64) {
+ h.res.insert(&Bin{1, f})
+ h.res.compress()
+}
+
+func (h *Histogram) Bins() Bins {
+ return h.res.bins
+}
+
+type reservoir struct {
+ n int
+ maxBins int
+ bins Bins
+}
+
+func newReservoir(maxBins int) *reservoir {
+ return &reservoir{maxBins: maxBins}
+}
+
+func (r *reservoir) insert(bin *Bin) {
+ r.n += bin.Count
+ i := sort.Search(len(r.bins), func(i int) bool {
+ return r.bins[i].Mean() >= bin.Mean()
+ })
+ if i < 0 || i == r.bins.Len() {
+ // TODO(blake): Maybe use an .insert(i, bin) instead of
+ // performing the extra work of a heap.Push.
+ heap.Push(&r.bins, bin)
+ return
+ }
+ r.bins[i].Update(bin)
+}
+
+func (r *reservoir) compress() {
+ for r.bins.Len() > r.maxBins {
+ minGapIndex := -1
+ minGap := math.MaxFloat64
+ for i := 0; i < r.bins.Len()-1; i++ {
+ gap := gapWeight(r.bins[i], r.bins[i+1])
+ if minGap > gap {
+ minGap = gap
+ minGapIndex = i
+ }
+ }
+ prev := r.bins[minGapIndex]
+ next := r.bins.remove(minGapIndex + 1)
+ prev.Update(next)
+ }
+}
+
+func gapWeight(prev, next *Bin) float64 {
+ return next.Mean() - prev.Mean()
+}
diff --git a/vendor/github.com/beorn7/perks/histogram/histogram_test.go b/vendor/github.com/beorn7/perks/histogram/histogram_test.go
new file mode 100644
index 0000000..0575ebe
--- /dev/null
+++ b/vendor/github.com/beorn7/perks/histogram/histogram_test.go
@@ -0,0 +1,38 @@
+package histogram
+
+import (
+ "math/rand"
+ "testing"
+)
+
+func TestHistogram(t *testing.T) {
+ const numPoints = 1e6
+ const maxBins = 3
+
+ h := New(maxBins)
+ for i := 0; i < numPoints; i++ {
+ f := rand.ExpFloat64()
+ h.Insert(f)
+ }
+
+ bins := h.Bins()
+ if g := len(bins); g > maxBins {
+ t.Fatalf("got %d bins, wanted <= %d", g, maxBins)
+ }
+
+ for _, b := range bins {
+ t.Logf("%+v", b)
+ }
+
+ if g := count(h.Bins()); g != numPoints {
+ t.Fatalf("binned %d points, wanted %d", g, numPoints)
+ }
+}
+
+func count(bins Bins) int {
+ binCounts := 0
+ for _, b := range bins {
+ binCounts += b.Count
+ }
+ return binCounts
+}
diff --git a/vendor/github.com/beorn7/perks/quantile/stream.go b/vendor/github.com/beorn7/perks/quantile/stream.go
index 587b1fc..f4cabd6 100644
--- a/vendor/github.com/beorn7/perks/quantile/stream.go
+++ b/vendor/github.com/beorn7/perks/quantile/stream.go
@@ -133,7 +133,7 @@ func (s *Stream) Query(q float64) float64 {
if l == 0 {
return 0
}
- i := int(float64(l) * q)
+ i := int(math.Ceil(float64(l) * q))
if i > 0 {
i -= 1
}
diff --git a/vendor/github.com/beorn7/perks/quantile/stream_test.go b/vendor/github.com/beorn7/perks/quantile/stream_test.go
index 4dba054..8551950 100644
--- a/vendor/github.com/beorn7/perks/quantile/stream_test.go
+++ b/vendor/github.com/beorn7/perks/quantile/stream_test.go
@@ -33,6 +33,9 @@ func verifyPercsWithAbsoluteEpsilon(t *testing.T, a []float64, s *Stream) {
for quantile, epsilon := range Targets {
n := float64(len(a))
k := int(quantile * n)
+ if k < 1 {
+ k = 1
+ }
lower := int((quantile - epsilon) * n)
if lower < 1 {
lower = 1
@@ -99,6 +102,30 @@ func TestTargetedQuery(t *testing.T) {
verifyPercsWithAbsoluteEpsilon(t, a, s)
}
+func TestTargetedQuerySmallSampleSize(t *testing.T) {
+ rand.Seed(42)
+ s := NewTargeted(TargetsSmallEpsilon)
+ a := []float64{1, 2, 3, 4, 5}
+ for _, v := range a {
+ s.Insert(v)
+ }
+ verifyPercsWithAbsoluteEpsilon(t, a, s)
+ // If not yet flushed, results should be precise:
+ if !s.flushed() {
+ for φ, want := range map[float64]float64{
+ 0.01: 1,
+ 0.10: 1,
+ 0.50: 3,
+ 0.90: 5,
+ 0.99: 5,
+ } {
+ if got := s.Query(φ); got != want {
+ t.Errorf("want %f for φ=%f, got %f", want, φ, got)
+ }
+ }
+ }
+}
+
func TestLowBiasedQuery(t *testing.T) {
rand.Seed(42)
s := NewLowBiased(RelativeEpsilon)
diff --git a/vendor/github.com/beorn7/perks/topk/topk.go b/vendor/github.com/beorn7/perks/topk/topk.go
new file mode 100644
index 0000000..5ac3d99
--- /dev/null
+++ b/vendor/github.com/beorn7/perks/topk/topk.go
@@ -0,0 +1,90 @@
+package topk
+
+import (
+ "sort"
+)
+
+// http://www.cs.ucsb.edu/research/tech_reports/reports/2005-23.pdf
+
+type Element struct {
+ Value string
+ Count int
+}
+
+type Samples []*Element
+
+func (sm Samples) Len() int {
+ return len(sm)
+}
+
+func (sm Samples) Less(i, j int) bool {
+ return sm[i].Count < sm[j].Count
+}
+
+func (sm Samples) Swap(i, j int) {
+ sm[i], sm[j] = sm[j], sm[i]
+}
+
+type Stream struct {
+ k int
+ mon map[string]*Element
+
+ // the minimum Element
+ min *Element
+}
+
+func New(k int) *Stream {
+ s := new(Stream)
+ s.k = k
+ s.mon = make(map[string]*Element)
+ s.min = &Element{}
+
+ // Track k+1 so that less frequenet items contended for that spot,
+ // resulting in k being more accurate.
+ return s
+}
+
+func (s *Stream) Insert(x string) {
+ s.insert(&Element{x, 1})
+}
+
+func (s *Stream) Merge(sm Samples) {
+ for _, e := range sm {
+ s.insert(e)
+ }
+}
+
+func (s *Stream) insert(in *Element) {
+ e := s.mon[in.Value]
+ if e != nil {
+ e.Count++
+ } else {
+ if len(s.mon) < s.k+1 {
+ e = &Element{in.Value, in.Count}
+ s.mon[in.Value] = e
+ } else {
+ e = s.min
+ delete(s.mon, e.Value)
+ e.Value = in.Value
+ e.Count += in.Count
+ s.min = e
+ }
+ }
+ if e.Count < s.min.Count {
+ s.min = e
+ }
+}
+
+func (s *Stream) Query() Samples {
+ var sm Samples
+ for _, e := range s.mon {
+ sm = append(sm, e)
+ }
+ sort.Sort(sort.Reverse(sm))
+
+ if len(sm) < s.k {
+ return sm
+ }
+
+ return sm[:s.k]
+}
diff --git a/vendor/github.com/beorn7/perks/topk/topk_test.go b/vendor/github.com/beorn7/perks/topk/topk_test.go
new file mode 100644
index 0000000..c24f0f7
--- /dev/null
+++ b/vendor/github.com/beorn7/perks/topk/topk_test.go
@@ -0,0 +1,57 @@
+package topk
+
+import (
+ "fmt"
+ "math/rand"
+ "sort"
+ "testing"
+)
+
+func TestTopK(t *testing.T) {
+ stream := New(10)
+ ss := []*Stream{New(10), New(10), New(10)}
+ m := make(map[string]int)
+ for _, s := range ss {
+ for i := 0; i < 1e6; i++ {
+ v := fmt.Sprintf("%x", int8(rand.ExpFloat64()))
+ s.Insert(v)
+ m[v]++
+ }
+ stream.Merge(s.Query())
+ }
+
+ var sm Samples
+ for x, s := range m {
+ sm = append(sm, &Element{x, s})
+ }
+ sort.Sort(sort.Reverse(sm))
+
+ g := stream.Query()
+ if len(g) != 10 {
+ t.Fatalf("got %d, want 10", len(g))
+ }
+ for i, e := range g {
+ if sm[i].Value != e.Value {
+ t.Errorf("at %d: want %q, got %q", i, sm[i].Value, e.Value)
+ }
+ }
+}
+
+func TestQuery(t *testing.T) {
+ queryTests := []struct {
+ value string
+ expected int
+ }{
+ {"a", 1},
+ {"b", 2},
+ {"c", 2},
+ }
+
+ stream := New(2)
+ for _, tt := range queryTests {
+ stream.Insert(tt.value)
+ if n := len(stream.Query()); n != tt.expected {
+ t.Errorf("want %d, got %d", tt.expected, n)
+ }
+ }
+}
diff --git a/vendor/github.com/flosch/pongo2/.travis.yml b/vendor/github.com/flosch/pongo2/.travis.yml
index 18971e1..a22ad21 100644
--- a/vendor/github.com/flosch/pongo2/.travis.yml
+++ b/vendor/github.com/flosch/pongo2/.travis.yml
@@ -1,10 +1,10 @@
language: go
go:
- - 1.4
+ - 1.3
- tip
install:
- - go get golang.org/x/tools/cmd/cover
+ - go get code.google.com/p/go.tools/cmd/cover
- go get github.com/mattn/goveralls
- go get gopkg.in/check.v1
script:
diff --git a/vendor/github.com/flosch/pongo2/README.md b/vendor/github.com/flosch/pongo2/README.md
index 9c26041..7c61e9e 100644
--- a/vendor/github.com/flosch/pongo2/README.md
+++ b/vendor/github.com/flosch/pongo2/README.md
@@ -1,6 +1,5 @@
# [pongo](https://en.wikipedia.org/wiki/Pongo_%28genus%29)2
-[![Join the chat at https://gitter.im/flosch/pongo2](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/flosch/pongo2)
[![GoDoc](https://godoc.org/github.com/flosch/pongo2?status.png)](https://godoc.org/github.com/flosch/pongo2)
[![Build Status](https://travis-ci.org/flosch/pongo2.svg?branch=master)](https://travis-ci.org/flosch/pongo2)
[![Coverage Status](https://coveralls.io/repos/flosch/pongo2/badge.png?branch=master)](https://coveralls.io/r/flosch/pongo2?branch=master)
@@ -96,7 +95,6 @@ Please also have a look on the [caveats](https://github.com/flosch/pongo2#caveat
If you're using the `master`-branch of pongo2, you might be interested in this section. Since pongo2 is still in development (even though there is a first stable release!), there could be (backwards-incompatible) API changes over time. To keep track of these and therefore make it painless for you to adapt your codebase, I'll list them here.
- * Function signature for tag execution changed: not taking a `bytes.Buffer` anymore; instead `Execute()`-functions are now taking a `TemplateWriter` interface.
* Function signature for tag and filter parsing/execution changed (`error` return type changed to `*Error`).
* `INodeEvaluator` has been removed and got replaced by `IEvaluator`. You can change your existing tags/filters by simply replacing the interface.
* Two new helper functions: [`RenderTemplateFile()`](https://godoc.org/github.com/flosch/pongo2#RenderTemplateFile) and [`RenderTemplateString()`](https://godoc.org/github.com/flosch/pongo2#RenderTemplateString).
@@ -106,7 +104,7 @@ If you're using the `master`-branch of pongo2, you might be interested in this s
## How you can help
* Write [filters](https://github.com/flosch/pongo2/blob/master/filters_builtin.go#L3) / [tags](https://github.com/flosch/pongo2/blob/master/tags.go#L4) (see [tutorial](https://www.florian-schlachter.de/post/pongo2/)) by forking pongo2 and sending pull requests
- * Write/improve code tests (use the following command to see what tests are missing: `go test -v -cover -covermode=count -coverprofile=cover.out && go tool cover -html=cover.out` or have a look on [gocover.io/github.com/flosch/pongo2](http://gocover.io/github.com/flosch/pongo2))
+ * Write/improve code tests (use the following command to see what tests are missing: `go test -v -cover -covermode=count -coverprofile=cover.out && go tool cover -html=cover.out`)
* Write/improve template tests (see the `template_tests/` directory)
* Write middleware, libraries and websites using pongo2. :-)
@@ -117,8 +115,7 @@ For a documentation on how the templating language works you can [head over to t
You can access pongo2's API documentation on [godoc](https://godoc.org/github.com/flosch/pongo2).
## Blog post series
-
- * [pongo2 v3 released](https://www.florian-schlachter.de/post/pongo2-v3/)
+
* [pongo2 v2 released](https://www.florian-schlachter.de/post/pongo2-v2/)
* [pongo2 1.0 released](https://www.florian-schlachter.de/post/pongo2-10/) [August 8th 2014]
* [pongo2 playground](https://www.florian-schlachter.de/post/pongo2-playground/) [August 1st 2014]
@@ -158,7 +155,6 @@ You can access pongo2's API documentation on [godoc](https://godoc.org/github.co
* [macaron-pongo2](https://github.com/macaron-contrib/pongo2) - pongo2 support for [Macaron](https://github.com/Unknwon/macaron), a modular web framework.
* [ginpongo2](https://github.com/ngerakines/ginpongo2) - middleware for [gin](github.com/gin-gonic/gin) to use pongo2 templates
* [pongo2-trans](https://github.com/fromYukki/pongo2trans) - `trans`-tag implementation for internationalization
- * [tpongo2](https://github.com/tango-contrib/tpongo2) - pongo2 support for [Tango](https://github.com/lunny/tango), a micro-kernel & pluggable web framework.
Please add your project to this list and send me a pull request when you've developed something nice for pongo2.
diff --git a/vendor/github.com/flosch/pongo2/context.go b/vendor/github.com/flosch/pongo2/context.go
index 7b728ec..df587c8 100644
--- a/vendor/github.com/flosch/pongo2/context.go
+++ b/vendor/github.com/flosch/pongo2/context.go
@@ -7,7 +7,7 @@ import (
var reIdentifiers = regexp.MustCompile("^[a-zA-Z0-9_]+$")
-// A Context type provides constants, variables, instances or functions to a template.
+// Use this Context type to provide constants, variables, instances or functions to your template.
//
// pongo2 automatically provides meta-information or functions through the "pongo2"-key.
// Currently, context["pongo2"] contains the following keys:
@@ -32,7 +32,6 @@ func (c Context) checkForValidIdentifiers() *Error {
return nil
}
-// Update updates this context with the key/value-pairs from another context.
func (c Context) Update(other Context) Context {
for k, v := range other {
c[k] = v
@@ -40,8 +39,6 @@ func (c Context) Update(other Context) Context {
return c
}
-// ExecutionContext contains all data important for the current rendering state.
-//
// If you're writing a custom tag, your tag's Execute()-function will
// have access to the ExecutionContext. This struct stores anything
// about the current rendering process's Context including
diff --git a/vendor/github.com/flosch/pongo2/error.go b/vendor/github.com/flosch/pongo2/error.go
index 80d1147..c1ee86e 100644
--- a/vendor/github.com/flosch/pongo2/error.go
+++ b/vendor/github.com/flosch/pongo2/error.go
@@ -6,7 +6,7 @@ import (
"os"
)
-// The Error type is being used to address an error during lexing, parsing or
+// This Error type is being used to address an error during lexing, parsing or
// execution. If you want to return an error object (for example in your own
// tag or filter) fill this object with as much information as you have.
// Make sure "Sender" is always given (if you're returning an error within
@@ -58,7 +58,7 @@ func (e *Error) Error() string {
return s
}
-// RawLine returns the affected line from the original template, if available.
+// Returns the affected line from the original template, if available.
func (e *Error) RawLine() (line string, available bool) {
if e.Line <= 0 || e.Filename == "" {
return "", false
@@ -72,12 +72,7 @@ func (e *Error) RawLine() (line string, available bool) {
if err != nil {
panic(err)
}
- defer func() {
- err := file.Close()
- if err != nil {
- panic(err)
- }
- }()
+ defer file.Close()
scanner := bufio.NewScanner(file)
l := 0
diff --git a/vendor/github.com/flosch/pongo2/filters.go b/vendor/github.com/flosch/pongo2/filters.go
index 13061f3..229f7fe 100644
--- a/vendor/github.com/flosch/pongo2/filters.go
+++ b/vendor/github.com/flosch/pongo2/filters.go
@@ -86,31 +86,31 @@ func (fc *filterCall) Execute(v *Value, ctx *ExecutionContext) (*Value, *Error)
param = AsValue(nil)
}
- filteredValue, err := fc.filterFunc(v, param)
+ filtered_value, err := fc.filterFunc(v, param)
if err != nil {
return nil, err.updateFromTokenIfNeeded(ctx.template, fc.token)
}
- return filteredValue, nil
+ return filtered_value, nil
}
// Filter = IDENT | IDENT ":" FilterArg | IDENT "|" Filter
func (p *Parser) parseFilter() (*filterCall, *Error) {
- identToken := p.MatchType(TokenIdentifier)
+ ident_token := p.MatchType(TokenIdentifier)
// Check filter ident
- if identToken == nil {
+ if ident_token == nil {
return nil, p.Error("Filter name must be an identifier.", nil)
}
filter := &filterCall{
- token: identToken,
- name: identToken.Val,
+ token: ident_token,
+ name: ident_token.Val,
}
// Get the appropriate filter function and bind it
- filterFn, exists := filters[identToken.Val]
+ filterFn, exists := filters[ident_token.Val]
if !exists {
- return nil, p.Error(fmt.Sprintf("Filter '%s' does not exist.", identToken.Val), identToken)
+ return nil, p.Error(fmt.Sprintf("Filter '%s' does not exist.", ident_token.Val), ident_token)
}
filter.filterFunc = filterFn
diff --git a/vendor/github.com/flosch/pongo2/filters_builtin.go b/vendor/github.com/flosch/pongo2/filters_builtin.go
index a267fa2..aaa68b1 100644
--- a/vendor/github.com/flosch/pongo2/filters_builtin.go
+++ b/vendor/github.com/flosch/pongo2/filters_builtin.go
@@ -78,9 +78,9 @@ func init() {
RegisterFilter("time", filterDate) // time uses filterDate (same golang-format)
RegisterFilter("title", filterTitle)
RegisterFilter("truncatechars", filterTruncatechars)
- RegisterFilter("truncatechars_html", filterTruncatecharsHTML)
+ RegisterFilter("truncatechars_html", filterTruncatecharsHtml)
RegisterFilter("truncatewords", filterTruncatewords)
- RegisterFilter("truncatewords_html", filterTruncatewordsHTML)
+ RegisterFilter("truncatewords_html", filterTruncatewordsHtml)
RegisterFilter("upper", filterUpper)
RegisterFilter("urlencode", filterUrlencode)
RegisterFilter("urlize", filterUrlize)
@@ -105,9 +105,9 @@ func filterTruncatecharsHelper(s string, newLen int) string {
return string(runes)
}
-func filterTruncateHTMLHelper(value string, newOutput *bytes.Buffer, cond func() bool, fn func(c rune, s int, idx int) int, finalize func()) {
+func filterTruncateHtmlHelper(value string, new_output *bytes.Buffer, cond func() bool, fn func(c rune, s int, idx int) int, finalize func()) {
vLen := len(value)
- var tagStack []string
+ tag_stack := make([]string, 0)
idx := 0
for idx < vLen && !cond() {
@@ -118,17 +118,17 @@ func filterTruncateHTMLHelper(value string, newOutput *bytes.Buffer, cond func()
}
if c == '<' {
- newOutput.WriteRune(c)
+ new_output.WriteRune(c)
idx += s // consume "<"
if idx+1 < vLen {
if value[idx] == '/' {
// Close tag
- newOutput.WriteString("/")
+ new_output.WriteString("/")
tag := ""
- idx++ // consume "/"
+ idx += 1 // consume "/"
for idx < vLen {
c2, size2 := utf8.DecodeRuneInString(value[idx:])
@@ -146,21 +146,21 @@ func filterTruncateHTMLHelper(value string, newOutput *bytes.Buffer, cond func()
idx += size2
}
- if len(tagStack) > 0 {
+ if len(tag_stack) > 0 {
// Ideally, the close tag is TOP of tag stack
// In malformed HTML, it must not be, so iterate through the stack and remove the tag
- for i := len(tagStack) - 1; i >= 0; i-- {
- if tagStack[i] == tag {
+ for i := len(tag_stack) - 1; i >= 0; i-- {
+ if tag_stack[i] == tag {
// Found the tag
- tagStack[i] = tagStack[len(tagStack)-1]
- tagStack = tagStack[:len(tagStack)-1]
+ tag_stack[i] = tag_stack[len(tag_stack)-1]
+ tag_stack = tag_stack[:len(tag_stack)-1]
break
}
}
}
- newOutput.WriteString(tag)
- newOutput.WriteString(">")
+ new_output.WriteString(tag)
+ new_output.WriteString(">")
} else {
// Open tag
@@ -174,7 +174,7 @@ func filterTruncateHTMLHelper(value string, newOutput *bytes.Buffer, cond func()
continue
}
- newOutput.WriteRune(c2)
+ new_output.WriteRune(c2)
// End of tag found
if c2 == '>' {
@@ -194,7 +194,7 @@ func filterTruncateHTMLHelper(value string, newOutput *bytes.Buffer, cond func()
}
// Add tag to stack
- tagStack = append(tagStack, tag)
+ tag_stack = append(tag_stack, tag)
}
}
} else {
@@ -204,10 +204,10 @@ func filterTruncateHTMLHelper(value string, newOutput *bytes.Buffer, cond func()
finalize()
- for i := len(tagStack) - 1; i >= 0; i-- {
- tag := tagStack[i]
+ for i := len(tag_stack) - 1; i >= 0; i-- {
+ tag := tag_stack[i]
// Close everything from the regular tag stack
- newOutput.WriteString(fmt.Sprintf("%s>", tag))
+ new_output.WriteString(fmt.Sprintf("%s>", tag))
}
}
@@ -217,28 +217,28 @@ func filterTruncatechars(in *Value, param *Value) (*Value, *Error) {
return AsValue(filterTruncatecharsHelper(s, newLen)), nil
}
-func filterTruncatecharsHTML(in *Value, param *Value) (*Value, *Error) {
+func filterTruncatecharsHtml(in *Value, param *Value) (*Value, *Error) {
value := in.String()
newLen := max(param.Integer()-3, 0)
- newOutput := bytes.NewBuffer(nil)
+ new_output := bytes.NewBuffer(nil)
textcounter := 0
- filterTruncateHTMLHelper(value, newOutput, func() bool {
+ filterTruncateHtmlHelper(value, new_output, func() bool {
return textcounter >= newLen
}, func(c rune, s int, idx int) int {
textcounter++
- newOutput.WriteRune(c)
+ new_output.WriteRune(c)
return idx + s
}, func() {
if textcounter >= newLen && textcounter < len(value) {
- newOutput.WriteString("...")
+ new_output.WriteString("...")
}
})
- return AsSafeValue(newOutput.String()), nil
+ return AsSafeValue(new_output.String()), nil
}
func filterTruncatewords(in *Value, param *Value) (*Value, *Error) {
@@ -260,19 +260,19 @@ func filterTruncatewords(in *Value, param *Value) (*Value, *Error) {
return AsValue(strings.Join(out, " ")), nil
}
-func filterTruncatewordsHTML(in *Value, param *Value) (*Value, *Error) {
+func filterTruncatewordsHtml(in *Value, param *Value) (*Value, *Error) {
value := in.String()
newLen := max(param.Integer(), 0)
- newOutput := bytes.NewBuffer(nil)
+ new_output := bytes.NewBuffer(nil)
wordcounter := 0
- filterTruncateHTMLHelper(value, newOutput, func() bool {
+ filterTruncateHtmlHelper(value, new_output, func() bool {
return wordcounter >= newLen
}, func(_ rune, _ int, idx int) int {
// Get next word
- wordFound := false
+ word_found := false
for idx < len(value) {
c2, size2 := utf8.DecodeRuneInString(value[idx:])
@@ -286,29 +286,29 @@ func filterTruncatewordsHTML(in *Value, param *Value) (*Value, *Error) {
return idx
}
- newOutput.WriteRune(c2)
+ new_output.WriteRune(c2)
idx += size2
if c2 == ' ' || c2 == '.' || c2 == ',' || c2 == ';' {
// Word ends here, stop capturing it now
break
} else {
- wordFound = true
+ word_found = true
}
}
- if wordFound {
+ if word_found {
wordcounter++
}
return idx
}, func() {
if wordcounter >= newLen {
- newOutput.WriteString("...")
+ new_output.WriteString("...")
}
})
- return AsSafeValue(newOutput.String()), nil
+ return AsSafeValue(new_output.String()), nil
}
func filterEscape(in *Value, param *Value) (*Value, *Error) {
@@ -377,8 +377,9 @@ func filterAdd(in *Value, param *Value) (*Value, *Error) {
if in.IsNumber() && param.IsNumber() {
if in.IsFloat() || param.IsFloat() {
return AsValue(in.Float() + param.Float()), nil
+ } else {
+ return AsValue(in.Integer() + param.Integer()), nil
}
- return AsValue(in.Integer() + param.Integer()), nil
}
// If in/param is not a number, we're relying on the
// Value's String() convertion and just add them both together
@@ -549,8 +550,8 @@ func filterCenter(in *Value, param *Value) (*Value, *Error) {
}
func filterDate(in *Value, param *Value) (*Value, *Error) {
- t, isTime := in.Interface().(time.Time)
- if !isTime {
+ t, is_time := in.Interface().(time.Time)
+ if !is_time {
return nil, &Error{
Sender: "filter:date",
ErrorMsg: "Filter input argument must be of type 'time.Time'.",
@@ -711,13 +712,13 @@ func filterStringformat(in *Value, param *Value) (*Value, *Error) {
return AsValue(fmt.Sprintf(param.String(), in.Interface())), nil
}
-var reStriptags = regexp.MustCompile("<[^>]*?>")
+var re_striptags = regexp.MustCompile("<[^>]*?>")
func filterStriptags(in *Value, param *Value) (*Value, *Error) {
s := in.String()
// Strip all tags
- s = reStriptags.ReplaceAllString(s, "")
+ s = re_striptags.ReplaceAllString(s, "")
return AsValue(strings.TrimSpace(s)), nil
}
@@ -769,10 +770,11 @@ func filterPluralize(in *Value, param *Value) (*Value, *Error) {
}
return AsValue(""), nil
- }
- return nil, &Error{
- Sender: "filter:pluralize",
- ErrorMsg: "Filter 'pluralize' does only work on numbers.",
+ } else {
+ return nil, &Error{
+ Sender: "filter:pluralize",
+ ErrorMsg: "Filter 'pluralize' does only work on numbers.",
+ }
}
}
@@ -842,16 +844,16 @@ func filterWordcount(in *Value, param *Value) (*Value, *Error) {
func filterWordwrap(in *Value, param *Value) (*Value, *Error) {
words := strings.Fields(in.String())
- wordsLen := len(words)
- wrapAt := param.Integer()
- if wrapAt <= 0 {
+ words_len := len(words)
+ wrap_at := param.Integer()
+ if wrap_at <= 0 {
return in, nil
}
- linecount := wordsLen/wrapAt + wordsLen%wrapAt
+ linecount := words_len/wrap_at + words_len%wrap_at
lines := make([]string, 0, linecount)
for i := 0; i < linecount; i++ {
- lines = append(lines, strings.Join(words[wrapAt*i:min(wrapAt*(i+1), wordsLen)], " "))
+ lines = append(lines, strings.Join(words[wrap_at*i:min(wrap_at*(i+1), words_len)], " "))
}
return AsValue(strings.Join(lines, "\n")), nil
}
@@ -862,27 +864,27 @@ func filterYesno(in *Value, param *Value) (*Value, *Error) {
1: "no",
2: "maybe",
}
- paramString := param.String()
- customChoices := strings.Split(paramString, ",")
- if len(paramString) > 0 {
- if len(customChoices) > 3 {
+ param_string := param.String()
+ custom_choices := strings.Split(param_string, ",")
+ if len(param_string) > 0 {
+ if len(custom_choices) > 3 {
return nil, &Error{
Sender: "filter:yesno",
- ErrorMsg: fmt.Sprintf("You cannot pass more than 3 options to the 'yesno'-filter (got: '%s').", paramString),
+ ErrorMsg: fmt.Sprintf("You cannot pass more than 3 options to the 'yesno'-filter (got: '%s').", param_string),
}
}
- if len(customChoices) < 2 {
+ if len(custom_choices) < 2 {
return nil, &Error{
Sender: "filter:yesno",
- ErrorMsg: fmt.Sprintf("You must pass either no or at least 2 arguments to the 'yesno'-filter (got: '%s').", paramString),
+ ErrorMsg: fmt.Sprintf("You must pass either no or at least 2 arguments to the 'yesno'-filter (got: '%s').", param_string),
}
}
// Map to the options now
- choices[0] = customChoices[0]
- choices[1] = customChoices[1]
- if len(customChoices) == 3 {
- choices[2] = customChoices[2]
+ choices[0] = custom_choices[0]
+ choices[1] = custom_choices[1]
+ if len(custom_choices) == 3 {
+ choices[2] = custom_choices[2]
}
}
diff --git a/vendor/github.com/flosch/pongo2/lexer.go b/vendor/github.com/flosch/pongo2/lexer.go
index 1698e41..8956f9c 100644
--- a/vendor/github.com/flosch/pongo2/lexer.go
+++ b/vendor/github.com/flosch/pongo2/lexer.go
@@ -63,8 +63,8 @@ type lexer struct {
line int
col int
- inVerbatim bool
- verbatimName string
+ in_verbatim bool
+ verbatim_name string
}
func (t *Token) String() string {
@@ -216,8 +216,8 @@ func (l *lexer) run() {
for {
// TODO: Support verbatim tag names
// https://docs.djangoproject.com/en/dev/ref/templates/builtins/#verbatim
- if l.inVerbatim {
- name := l.verbatimName
+ if l.in_verbatim {
+ name := l.verbatim_name
if name != "" {
name += " "
}
@@ -229,20 +229,20 @@ func (l *lexer) run() {
l.pos += w
l.col += w
l.ignore()
- l.inVerbatim = false
+ l.in_verbatim = false
}
} else if strings.HasPrefix(l.input[l.pos:], "{% verbatim %}") { // tag
if l.pos > l.start {
l.emit(TokenHTML)
}
- l.inVerbatim = true
+ l.in_verbatim = true
w := len("{% verbatim %}")
l.pos += w
l.col += w
l.ignore()
}
- if !l.inVerbatim {
+ if !l.in_verbatim {
// Ignore single-line comments {# ... #}
if strings.HasPrefix(l.input[l.pos:], "{#") {
if l.pos > l.start {
@@ -303,7 +303,7 @@ func (l *lexer) run() {
l.emit(TokenHTML)
}
- if l.inVerbatim {
+ if l.in_verbatim {
l.errorf("verbatim-tag not closed, got EOF.")
}
}
@@ -394,7 +394,7 @@ func (l *lexer) stateNumber() lexerStateFn {
func (l *lexer) stateString() lexerStateFn {
l.ignore()
- l.startcol-- // we're starting the position at the first "
+ l.startcol -= 1 // we're starting the position at the first "
for !l.accept(`"`) {
switch l.next() {
case '\\':
diff --git a/vendor/github.com/flosch/pongo2/nodes.go b/vendor/github.com/flosch/pongo2/nodes.go
index 5b039cd..5fd5a6c 100644
--- a/vendor/github.com/flosch/pongo2/nodes.go
+++ b/vendor/github.com/flosch/pongo2/nodes.go
@@ -1,13 +1,17 @@
package pongo2
+import (
+ "bytes"
+)
+
// The root document
type nodeDocument struct {
Nodes []INode
}
-func (doc *nodeDocument) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (doc *nodeDocument) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
for _, n := range doc.Nodes {
- err := n.Execute(ctx, writer)
+ err := n.Execute(ctx, buffer)
if err != nil {
return err
}
diff --git a/vendor/github.com/flosch/pongo2/nodes_html.go b/vendor/github.com/flosch/pongo2/nodes_html.go
index 9680285..9aa630c 100644
--- a/vendor/github.com/flosch/pongo2/nodes_html.go
+++ b/vendor/github.com/flosch/pongo2/nodes_html.go
@@ -1,10 +1,14 @@
package pongo2
+import (
+ "bytes"
+)
+
type nodeHTML struct {
token *Token
}
-func (n *nodeHTML) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
- writer.WriteString(n.token.Val)
+func (n *nodeHTML) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
+ buffer.WriteString(n.token.Val)
return nil
}
diff --git a/vendor/github.com/flosch/pongo2/nodes_wrapper.go b/vendor/github.com/flosch/pongo2/nodes_wrapper.go
index d1bcb8d..9180dc7 100644
--- a/vendor/github.com/flosch/pongo2/nodes_wrapper.go
+++ b/vendor/github.com/flosch/pongo2/nodes_wrapper.go
@@ -1,13 +1,17 @@
package pongo2
+import (
+ "bytes"
+)
+
type NodeWrapper struct {
Endtag string
nodes []INode
}
-func (wrapper *NodeWrapper) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (wrapper *NodeWrapper) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
for _, n := range wrapper.nodes {
- err := n.Execute(ctx, writer)
+ err := n.Execute(ctx, buffer)
if err != nil {
return err
}
diff --git a/vendor/github.com/flosch/pongo2/parser.go b/vendor/github.com/flosch/pongo2/parser.go
index bed5061..c85e2d2 100644
--- a/vendor/github.com/flosch/pongo2/parser.go
+++ b/vendor/github.com/flosch/pongo2/parser.go
@@ -1,12 +1,13 @@
package pongo2
import (
+ "bytes"
"fmt"
"strings"
)
type INode interface {
- Execute(*ExecutionContext, TemplateWriter) *Error
+ Execute(*ExecutionContext, *bytes.Buffer) *Error
}
type IEvaluator interface {
@@ -26,10 +27,10 @@ type IEvaluator interface {
//
// (See Token's documentation for more about tokens)
type Parser struct {
- name string
- idx int
- tokens []*Token
- lastToken *Token
+ name string
+ idx int
+ tokens []*Token
+ last_token *Token
// if the parser parses a template document, here will be
// a reference to it (needed to access the template through Tags)
@@ -46,7 +47,7 @@ func newParser(name string, tokens []*Token, template *Template) *Parser {
template: template,
}
if len(tokens) > 0 {
- p.lastToken = tokens[len(tokens)-1]
+ p.last_token = tokens[len(tokens)-1]
}
return p
}
@@ -211,19 +212,19 @@ func (p *Parser) Error(msg string, token *Token) *Error {
func (p *Parser) WrapUntilTag(names ...string) (*NodeWrapper, *Parser, *Error) {
wrapper := &NodeWrapper{}
- var tagArgs []*Token
+ tagArgs := make([]*Token, 0)
for p.Remaining() > 0 {
// New tag, check whether we have to stop wrapping here
if p.Peek(TokenSymbol, "{%") != nil {
- tagIdent := p.PeekTypeN(1, TokenIdentifier)
+ tag_ident := p.PeekTypeN(1, TokenIdentifier)
- if tagIdent != nil {
+ if tag_ident != nil {
// We've found a (!) end-tag
found := false
for _, n := range names {
- if tagIdent.Val == n {
+ if tag_ident.Val == n {
found = true
break
}
@@ -237,15 +238,16 @@ func (p *Parser) WrapUntilTag(names ...string) (*NodeWrapper, *Parser, *Error) {
for {
if p.Match(TokenSymbol, "%}") != nil {
// Okay, end the wrapping here
- wrapper.Endtag = tagIdent.Val
+ wrapper.Endtag = tag_ident.Val
return wrapper, newParser(p.template.name, tagArgs, p.template), nil
+ } else {
+ t := p.Current()
+ p.Consume()
+ if t == nil {
+ return nil, nil, p.Error("Unexpected EOF.", p.last_token)
+ }
+ tagArgs = append(tagArgs, t)
}
- t := p.Current()
- p.Consume()
- if t == nil {
- return nil, nil, p.Error("Unexpected EOF.", p.lastToken)
- }
- tagArgs = append(tagArgs, t)
}
}
}
@@ -261,5 +263,5 @@ func (p *Parser) WrapUntilTag(names ...string) (*NodeWrapper, *Parser, *Error) {
}
return nil, nil, p.Error(fmt.Sprintf("Unexpected EOF, expected tag %s.", strings.Join(names, " or ")),
- p.lastToken)
+ p.last_token)
}
diff --git a/vendor/github.com/flosch/pongo2/parser_expression.go b/vendor/github.com/flosch/pongo2/parser_expression.go
index 98c6580..c1002de 100644
--- a/vendor/github.com/flosch/pongo2/parser_expression.go
+++ b/vendor/github.com/flosch/pongo2/parser_expression.go
@@ -1,37 +1,38 @@
package pongo2
import (
+ "bytes"
"fmt"
"math"
)
type Expression struct {
// TODO: Add location token?
- expr1 IEvaluator
- expr2 IEvaluator
- opToken *Token
+ expr1 IEvaluator
+ expr2 IEvaluator
+ op_token *Token
}
type relationalExpression struct {
// TODO: Add location token?
- expr1 IEvaluator
- expr2 IEvaluator
- opToken *Token
+ expr1 IEvaluator
+ expr2 IEvaluator
+ op_token *Token
}
type simpleExpression struct {
- negate bool
- negativeSign bool
- term1 IEvaluator
- term2 IEvaluator
- opToken *Token
+ negate bool
+ negative_sign bool
+ term1 IEvaluator
+ term2 IEvaluator
+ op_token *Token
}
type term struct {
// TODO: Add location token?
- factor1 IEvaluator
- factor2 IEvaluator
- opToken *Token
+ factor1 IEvaluator
+ factor2 IEvaluator
+ op_token *Token
}
type power struct {
@@ -55,14 +56,14 @@ func (expr *simpleExpression) FilterApplied(name string) bool {
(expr.term2 != nil && expr.term2.FilterApplied(name)))
}
-func (expr *term) FilterApplied(name string) bool {
- return expr.factor1.FilterApplied(name) && (expr.factor2 == nil ||
- (expr.factor2 != nil && expr.factor2.FilterApplied(name)))
+func (t *term) FilterApplied(name string) bool {
+ return t.factor1.FilterApplied(name) && (t.factor2 == nil ||
+ (t.factor2 != nil && t.factor2.FilterApplied(name)))
}
-func (expr *power) FilterApplied(name string) bool {
- return expr.power1.FilterApplied(name) && (expr.power2 == nil ||
- (expr.power2 != nil && expr.power2.FilterApplied(name)))
+func (p *power) FilterApplied(name string) bool {
+ return p.power1.FilterApplied(name) && (p.power2 == nil ||
+ (p.power2 != nil && p.power2.FilterApplied(name)))
}
func (expr *Expression) GetPositionToken() *Token {
@@ -85,48 +86,48 @@ func (expr *power) GetPositionToken() *Token {
return expr.power1.GetPositionToken()
}
-func (expr *Expression) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (expr *Expression) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
value, err := expr.Evaluate(ctx)
if err != nil {
return err
}
- writer.WriteString(value.String())
+ buffer.WriteString(value.String())
return nil
}
-func (expr *relationalExpression) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (expr *relationalExpression) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
value, err := expr.Evaluate(ctx)
if err != nil {
return err
}
- writer.WriteString(value.String())
+ buffer.WriteString(value.String())
return nil
}
-func (expr *simpleExpression) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (expr *simpleExpression) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
value, err := expr.Evaluate(ctx)
if err != nil {
return err
}
- writer.WriteString(value.String())
+ buffer.WriteString(value.String())
return nil
}
-func (expr *term) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (expr *term) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
value, err := expr.Evaluate(ctx)
if err != nil {
return err
}
- writer.WriteString(value.String())
+ buffer.WriteString(value.String())
return nil
}
-func (expr *power) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (expr *power) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
value, err := expr.Evaluate(ctx)
if err != nil {
return err
}
- writer.WriteString(value.String())
+ buffer.WriteString(value.String())
return nil
}
@@ -140,13 +141,13 @@ func (expr *Expression) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
if err != nil {
return nil, err
}
- switch expr.opToken.Val {
+ switch expr.op_token.Val {
case "and", "&&":
return AsValue(v1.IsTrue() && v2.IsTrue()), nil
case "or", "||":
return AsValue(v1.IsTrue() || v2.IsTrue()), nil
default:
- panic(fmt.Sprintf("unimplemented: %s", expr.opToken.Val))
+ panic(fmt.Sprintf("unimplemented: %s", expr.op_token.Val))
}
} else {
return v1, nil
@@ -163,35 +164,39 @@ func (expr *relationalExpression) Evaluate(ctx *ExecutionContext) (*Value, *Erro
if err != nil {
return nil, err
}
- switch expr.opToken.Val {
+ switch expr.op_token.Val {
case "<=":
if v1.IsFloat() || v2.IsFloat() {
return AsValue(v1.Float() <= v2.Float()), nil
+ } else {
+ return AsValue(v1.Integer() <= v2.Integer()), nil
}
- return AsValue(v1.Integer() <= v2.Integer()), nil
case ">=":
if v1.IsFloat() || v2.IsFloat() {
return AsValue(v1.Float() >= v2.Float()), nil
+ } else {
+ return AsValue(v1.Integer() >= v2.Integer()), nil
}
- return AsValue(v1.Integer() >= v2.Integer()), nil
case "==":
return AsValue(v1.EqualValueTo(v2)), nil
case ">":
if v1.IsFloat() || v2.IsFloat() {
return AsValue(v1.Float() > v2.Float()), nil
+ } else {
+ return AsValue(v1.Integer() > v2.Integer()), nil
}
- return AsValue(v1.Integer() > v2.Integer()), nil
case "<":
if v1.IsFloat() || v2.IsFloat() {
return AsValue(v1.Float() < v2.Float()), nil
+ } else {
+ return AsValue(v1.Integer() < v2.Integer()), nil
}
- return AsValue(v1.Integer() < v2.Integer()), nil
case "!=", "<>":
return AsValue(!v1.EqualValueTo(v2)), nil
case "in":
return AsValue(v2.Contains(v1)), nil
default:
- panic(fmt.Sprintf("unimplemented: %s", expr.opToken.Val))
+ panic(fmt.Sprintf("unimplemented: %s", expr.op_token.Val))
}
} else {
return v1, nil
@@ -209,7 +214,7 @@ func (expr *simpleExpression) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
result = result.Negate()
}
- if expr.negativeSign {
+ if expr.negative_sign {
if result.IsNumber() {
switch {
case result.IsFloat():
@@ -229,21 +234,23 @@ func (expr *simpleExpression) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
if err != nil {
return nil, err
}
- switch expr.opToken.Val {
+ switch expr.op_token.Val {
case "+":
if result.IsFloat() || t2.IsFloat() {
// Result will be a float
return AsValue(result.Float() + t2.Float()), nil
+ } else {
+ // Result will be an integer
+ return AsValue(result.Integer() + t2.Integer()), nil
}
- // Result will be an integer
- return AsValue(result.Integer() + t2.Integer()), nil
case "-":
if result.IsFloat() || t2.IsFloat() {
// Result will be a float
return AsValue(result.Float() - t2.Float()), nil
+ } else {
+ // Result will be an integer
+ return AsValue(result.Integer() - t2.Integer()), nil
}
- // Result will be an integer
- return AsValue(result.Integer() - t2.Integer()), nil
default:
panic("unimplemented")
}
@@ -252,17 +259,17 @@ func (expr *simpleExpression) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
return result, nil
}
-func (expr *term) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
- f1, err := expr.factor1.Evaluate(ctx)
+func (t *term) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
+ f1, err := t.factor1.Evaluate(ctx)
if err != nil {
return nil, err
}
- if expr.factor2 != nil {
- f2, err := expr.factor2.Evaluate(ctx)
+ if t.factor2 != nil {
+ f2, err := t.factor2.Evaluate(ctx)
if err != nil {
return nil, err
}
- switch expr.opToken.Val {
+ switch t.op_token.Val {
case "*":
if f1.IsFloat() || f2.IsFloat() {
// Result will be float
@@ -288,19 +295,20 @@ func (expr *term) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
}
}
-func (expr *power) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
- p1, err := expr.power1.Evaluate(ctx)
+func (pw *power) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
+ p1, err := pw.power1.Evaluate(ctx)
if err != nil {
return nil, err
}
- if expr.power2 != nil {
- p2, err := expr.power2.Evaluate(ctx)
+ if pw.power2 != nil {
+ p2, err := pw.power2.Evaluate(ctx)
if err != nil {
return nil, err
}
return AsValue(math.Pow(p1.Float(), p2.Float())), nil
+ } else {
+ return p1, nil
}
- return p1, nil
}
func (p *Parser) parseFactor() (IEvaluator, *Error) {
@@ -344,19 +352,19 @@ func (p *Parser) parsePower() (IEvaluator, *Error) {
}
func (p *Parser) parseTerm() (IEvaluator, *Error) {
- returnTerm := new(term)
+ return_term := new(term)
factor1, err := p.parsePower()
if err != nil {
return nil, err
}
- returnTerm.factor1 = factor1
+ return_term.factor1 = factor1
for p.PeekOne(TokenSymbol, "*", "/", "%") != nil {
- if returnTerm.opToken != nil {
+ if return_term.op_token != nil {
// Create new sub-term
- returnTerm = &term{
- factor1: returnTerm,
+ return_term = &term{
+ factor1: return_term,
}
}
@@ -368,16 +376,16 @@ func (p *Parser) parseTerm() (IEvaluator, *Error) {
return nil, err
}
- returnTerm.opToken = op
- returnTerm.factor2 = factor2
+ return_term.op_token = op
+ return_term.factor2 = factor2
}
- if returnTerm.opToken == nil {
+ if return_term.op_token == nil {
// Shortcut for faster evaluation
- return returnTerm.factor1, nil
+ return return_term.factor1, nil
}
- return returnTerm, nil
+ return return_term, nil
}
func (p *Parser) parseSimpleExpression() (IEvaluator, *Error) {
@@ -385,7 +393,7 @@ func (p *Parser) parseSimpleExpression() (IEvaluator, *Error) {
if sign := p.MatchOne(TokenSymbol, "+", "-"); sign != nil {
if sign.Val == "-" {
- expr.negativeSign = true
+ expr.negative_sign = true
}
}
@@ -400,7 +408,7 @@ func (p *Parser) parseSimpleExpression() (IEvaluator, *Error) {
expr.term1 = term1
for p.PeekOne(TokenSymbol, "+", "-") != nil {
- if expr.opToken != nil {
+ if expr.op_token != nil {
// New sub expr
expr = &simpleExpression{
term1: expr,
@@ -416,10 +424,10 @@ func (p *Parser) parseSimpleExpression() (IEvaluator, *Error) {
}
expr.term2 = term2
- expr.opToken = op
+ expr.op_token = op
}
- if expr.negate == false && expr.negativeSign == false && expr.term2 == nil {
+ if expr.negate == false && expr.negative_sign == false && expr.term2 == nil {
// Shortcut for faster evaluation
return expr.term1, nil
}
@@ -442,14 +450,14 @@ func (p *Parser) parseRelationalExpression() (IEvaluator, *Error) {
if err != nil {
return nil, err
}
- expr.opToken = t
+ expr.op_token = t
expr.expr2 = expr2
} else if t := p.MatchOne(TokenKeyword, "in"); t != nil {
expr2, err := p.parseSimpleExpression()
if err != nil {
return nil, err
}
- expr.opToken = t
+ expr.op_token = t
expr.expr2 = expr2
}
@@ -479,7 +487,7 @@ func (p *Parser) ParseExpression() (IEvaluator, *Error) {
return nil, err
}
exp.expr2 = expr2
- exp.opToken = op
+ exp.op_token = op
}
if exp.expr2 == nil {
diff --git a/vendor/github.com/flosch/pongo2/pongo2.go b/vendor/github.com/flosch/pongo2/pongo2.go
index eda3aa0..e61faa4 100644
--- a/vendor/github.com/flosch/pongo2/pongo2.go
+++ b/vendor/github.com/flosch/pongo2/pongo2.go
@@ -1,10 +1,10 @@
package pongo2
// Version string
-const Version = "dev"
+const Version = "v3"
-// Must panics, if a Template couldn't successfully parsed. This is how you
-// would use it:
+// Helper function which panics, if a Template couldn't
+// successfully parsed. This is how you would use it:
// var baseTemplate = pongo2.Must(pongo2.FromFile("templates/base.html"))
func Must(tpl *Template, err error) *Template {
if err != nil {
diff --git a/vendor/github.com/flosch/pongo2/pongo2_issues_test.go b/vendor/github.com/flosch/pongo2/pongo2_issues_test.go
new file mode 100644
index 0000000..731a290
--- /dev/null
+++ b/vendor/github.com/flosch/pongo2/pongo2_issues_test.go
@@ -0,0 +1,20 @@
+package pongo2
+
+import (
+ "testing"
+
+ . "gopkg.in/check.v1"
+)
+
+// Hook up gocheck into the "go test" runner.
+
+func TestIssues(t *testing.T) { TestingT(t) }
+
+type IssueTestSuite struct{}
+
+var _ = Suite(&IssueTestSuite{})
+
+func (s *TestSuite) TestIssues(c *C) {
+ // Add a test for any issue
+ c.Check(42, Equals, 42)
+}
diff --git a/vendor/github.com/flosch/pongo2/pongo2_template_test.go b/vendor/github.com/flosch/pongo2/pongo2_template_test.go
index 8493dae..b6dc8fa 100644
--- a/vendor/github.com/flosch/pongo2/pongo2_template_test.go
+++ b/vendor/github.com/flosch/pongo2/pongo2_template_test.go
@@ -1,4 +1,4 @@
-package pongo2_test
+package pongo2
import (
"bytes"
@@ -9,11 +9,9 @@ import (
"strings"
"testing"
"time"
-
- "github.com/flosch/pongo2"
)
-var adminList = []string{"user2"}
+var admin_list = []string{"user2"}
var time1 = time.Date(2014, 06, 10, 15, 30, 15, 0, time.UTC)
var time2 = time.Date(2011, 03, 21, 8, 37, 56, 12, time.UTC)
@@ -34,8 +32,8 @@ type comment struct {
Text string
}
-func isAdmin(u *user) bool {
- for _, a := range adminList {
+func is_admin(u *user) bool {
+ for _, a := range admin_list {
if a == u.Name {
return true
}
@@ -43,12 +41,12 @@ func isAdmin(u *user) bool {
return false
}
-func (u *user) Is_admin() *pongo2.Value {
- return pongo2.AsValue(isAdmin(u))
+func (u *user) Is_admin() *Value {
+ return AsValue(is_admin(u))
}
func (u *user) Is_admin2() bool {
- return isAdmin(u)
+ return is_admin(u)
}
func (p *post) String() string {
@@ -62,53 +60,74 @@ func (p *post) String() string {
type tagSandboxDemoTag struct {
}
-func (node *tagSandboxDemoTag) Execute(ctx *pongo2.ExecutionContext, writer pongo2.TemplateWriter) *pongo2.Error {
- writer.WriteString("hello")
+func (node *tagSandboxDemoTag) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
+ buffer.WriteString("hello")
return nil
}
-func tagSandboxDemoTagParser(doc *pongo2.Parser, start *pongo2.Token, arguments *pongo2.Parser) (pongo2.INodeTag, *pongo2.Error) {
+func tagSandboxDemoTagParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
return &tagSandboxDemoTag{}, nil
}
-func BannedFilterFn(in *pongo2.Value, params *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
+func BannedFilterFn(in *Value, params *Value) (*Value, *Error) {
return in, nil
}
func init() {
- pongo2.DefaultSet.Debug = true
+ DefaultSet.Debug = true
- pongo2.RegisterFilter("banned_filter", BannedFilterFn)
- pongo2.RegisterFilter("unbanned_filter", BannedFilterFn)
- pongo2.RegisterTag("banned_tag", tagSandboxDemoTagParser)
- pongo2.RegisterTag("unbanned_tag", tagSandboxDemoTagParser)
+ RegisterFilter("banned_filter", BannedFilterFn)
+ RegisterFilter("unbanned_filter", BannedFilterFn)
+ RegisterTag("banned_tag", tagSandboxDemoTagParser)
+ RegisterTag("unbanned_tag", tagSandboxDemoTagParser)
- pongo2.DefaultSet.BanFilter("banned_filter")
- pongo2.DefaultSet.BanTag("banned_tag")
+ DefaultSet.BanFilter("banned_filter")
+ DefaultSet.BanTag("banned_tag")
+
+ // Allow different kind of levels inside template_tests/
+ abs_path, err := filepath.Abs("./template_tests/*")
+ if err != nil {
+ panic(err)
+ }
+ DefaultSet.SandboxDirectories = append(DefaultSet.SandboxDirectories, abs_path)
+
+ abs_path, err = filepath.Abs("./template_tests/*/*")
+ if err != nil {
+ panic(err)
+ }
+ DefaultSet.SandboxDirectories = append(DefaultSet.SandboxDirectories, abs_path)
+
+ abs_path, err = filepath.Abs("./template_tests/*/*/*")
+ if err != nil {
+ panic(err)
+ }
+ DefaultSet.SandboxDirectories = append(DefaultSet.SandboxDirectories, abs_path)
+
+ // Allow pongo2 temp files
+ DefaultSet.SandboxDirectories = append(DefaultSet.SandboxDirectories, "/tmp/pongo2_*")
f, err := ioutil.TempFile("/tmp/", "pongo2_")
if err != nil {
panic("cannot write to /tmp/")
}
f.Write([]byte("Hello from pongo2"))
- pongo2.DefaultSet.Globals["temp_file"] = f.Name()
+ DefaultSet.Globals["temp_file"] = f.Name()
}
/*
* End setup sandbox
*/
-var tplContext = pongo2.Context{
+var tplContext = Context{
"number": 11,
"simple": map[string]interface{}{
- "number": 42,
- "name": "john doe",
- "included_file": "INCLUDES.helper",
- "included_file_not_exists": "INCLUDES.helper.not_exists",
- "nil": nil,
- "uint": uint(8),
- "float": float64(3.1415),
- "str": "string",
+ "number": 42,
+ "name": "john doe",
+ "included_file": "INCLUDES.helper",
+ "nil": nil,
+ "uint": uint(8),
+ "float": float64(3.1415),
+ "str": "string",
"chinese_hello_world": "你好世界",
"bool_true": true,
"bool_false": false,
@@ -123,22 +142,13 @@ Yep!`,
"escape_js_test": `escape sequences \r\n\'\" special chars "?!=$<>`,
"one_item_list": []int{99},
"multiple_item_list": []int{1, 1, 2, 3, 5, 8, 13, 21, 34, 55},
- "unsorted_int_list": []int{192, 581, 22, 1, 249, 9999, 1828591, 8271},
"misc_list": []interface{}{"Hello", 99, 3.14, "good"},
"escape_text": "This is \\a Test. \"Yep\". 'Yep'.",
"xss": "",
"intmap": map[int]string{
1: "one",
- 5: "five",
2: "two",
- },
- "strmap": map[string]string{
- "abc": "def",
- "bcd": "efg",
- "zab": "cde",
- "gh": "kqm",
- "ukq": "qqa",
- "aab": "aba",
+ 5: "five",
},
"func_add": func(a, b int) int {
return a + b
@@ -157,17 +167,17 @@ Yep!`,
}
return s
},
- "func_variadic_sum_int2": func(args ...*pongo2.Value) *pongo2.Value {
+ "func_variadic_sum_int2": func(args ...*Value) *Value {
// Create a sum
s := 0
for _, i := range args {
s += i.Integer()
}
- return pongo2.AsValue(s)
+ return AsValue(s)
},
},
"complex": map[string]interface{}{
- "is_admin": isAdmin,
+ "is_admin": is_admin,
"post": post{
Text: "Hello!
Welcome to my new blog page. I'm using pongo2 which supports {{ variables }} and {% tags %}.
",
Created: time2,
@@ -228,8 +238,10 @@ Yep!`,
}
func TestTemplates(t *testing.T) {
+ debug = true
+
// Add a global to the default set
- pongo2.Globals["this_is_a_global_variable"] = "this is a global text"
+ Globals["this_is_a_global_variable"] = "this is a global text"
matches, err := filepath.Glob("./template_tests/*.tpl")
if err != nil {
@@ -237,34 +249,34 @@ func TestTemplates(t *testing.T) {
}
for idx, match := range matches {
t.Logf("[Template %3d] Testing '%s'", idx+1, match)
- tpl, err := pongo2.FromFile(match)
+ tpl, err := FromFile(match)
if err != nil {
t.Fatalf("Error on FromFile('%s'): %s", match, err.Error())
}
- testFilename := fmt.Sprintf("%s.out", match)
- testOut, rerr := ioutil.ReadFile(testFilename)
+ test_filename := fmt.Sprintf("%s.out", match)
+ test_out, rerr := ioutil.ReadFile(test_filename)
if rerr != nil {
- t.Fatalf("Error on ReadFile('%s'): %s", testFilename, rerr.Error())
+ t.Fatalf("Error on ReadFile('%s'): %s", test_filename, rerr.Error())
}
- tplOut, err := tpl.ExecuteBytes(tplContext)
+ tpl_out, err := tpl.ExecuteBytes(tplContext)
if err != nil {
t.Fatalf("Error on Execute('%s'): %s", match, err.Error())
}
- if bytes.Compare(testOut, tplOut) != 0 {
- t.Logf("Template (rendered) '%s': '%s'", match, tplOut)
- errFilename := filepath.Base(fmt.Sprintf("%s.error", match))
- err := ioutil.WriteFile(errFilename, []byte(tplOut), 0600)
+ if bytes.Compare(test_out, tpl_out) != 0 {
+ t.Logf("Template (rendered) '%s': '%s'", match, tpl_out)
+ err_filename := filepath.Base(fmt.Sprintf("%s.error", match))
+ err := ioutil.WriteFile(err_filename, []byte(tpl_out), 0600)
if err != nil {
t.Fatalf(err.Error())
}
- t.Logf("get a complete diff with command: 'diff -ya %s %s'", testFilename, errFilename)
+ t.Logf("get a complete diff with command: 'diff -ya %s %s'", test_filename, err_filename)
t.Errorf("Failed: test_out != tpl_out for %s", match)
}
}
}
func TestExecutionErrors(t *testing.T) {
- //debug = true
+ debug = true
matches, err := filepath.Glob("./template_tests/*-execution.err")
if err != nil {
@@ -273,15 +285,15 @@ func TestExecutionErrors(t *testing.T) {
for idx, match := range matches {
t.Logf("[Errors %3d] Testing '%s'", idx+1, match)
- testData, err := ioutil.ReadFile(match)
- tests := strings.Split(string(testData), "\n")
+ test_data, err := ioutil.ReadFile(match)
+ tests := strings.Split(string(test_data), "\n")
- checkFilename := fmt.Sprintf("%s.out", match)
- checkData, err := ioutil.ReadFile(checkFilename)
+ check_filename := fmt.Sprintf("%s.out", match)
+ check_data, err := ioutil.ReadFile(check_filename)
if err != nil {
- t.Fatalf("Error on ReadFile('%s'): %s", checkFilename, err.Error())
+ t.Fatalf("Error on ReadFile('%s'): %s", check_filename, err.Error())
}
- checks := strings.Split(string(checkData), "\n")
+ checks := strings.Split(string(check_data), "\n")
if len(checks) != len(tests) {
t.Fatal("Template lines != Checks lines")
@@ -296,7 +308,7 @@ func TestExecutionErrors(t *testing.T) {
match, idx+1)
}
- tpl, err := pongo2.FromString(test)
+ tpl, err := FromString(test)
if err != nil {
t.Fatalf("Error on FromString('%s'): %s", test, err.Error())
}
@@ -317,7 +329,7 @@ func TestExecutionErrors(t *testing.T) {
}
func TestCompilationErrors(t *testing.T) {
- //debug = true
+ debug = true
matches, err := filepath.Glob("./template_tests/*-compilation.err")
if err != nil {
@@ -326,15 +338,15 @@ func TestCompilationErrors(t *testing.T) {
for idx, match := range matches {
t.Logf("[Errors %3d] Testing '%s'", idx+1, match)
- testData, err := ioutil.ReadFile(match)
- tests := strings.Split(string(testData), "\n")
+ test_data, err := ioutil.ReadFile(match)
+ tests := strings.Split(string(test_data), "\n")
- checkFilename := fmt.Sprintf("%s.out", match)
- checkData, err := ioutil.ReadFile(checkFilename)
+ check_filename := fmt.Sprintf("%s.out", match)
+ check_data, err := ioutil.ReadFile(check_filename)
if err != nil {
- t.Fatalf("Error on ReadFile('%s'): %s", checkFilename, err.Error())
+ t.Fatalf("Error on ReadFile('%s'): %s", check_filename, err.Error())
}
- checks := strings.Split(string(checkData), "\n")
+ checks := strings.Split(string(check_data), "\n")
if len(checks) != len(tests) {
t.Fatal("Template lines != Checks lines")
@@ -349,7 +361,7 @@ func TestCompilationErrors(t *testing.T) {
match, idx+1)
}
- _, err = pongo2.FromString(test)
+ _, err = FromString(test)
if err == nil {
t.Fatalf("[%s | Line %d] Expected error for (got none): %s", match, idx+1, tests[idx])
}
@@ -365,10 +377,9 @@ func TestCompilationErrors(t *testing.T) {
func TestBaseDirectory(t *testing.T) {
mustStr := "Hello from template_tests/base_dir_test/"
- fs := pongo2.MustNewLocalFileSystemLoader("")
- s := pongo2.NewSet("test set with base directory", fs)
+ s := NewSet("test set with base directory")
s.Globals["base_directory"] = "template_tests/base_dir_test/"
- if err := fs.SetBaseDir(s.Globals["base_directory"].(string)); err != nil {
+ if err := s.SetBaseDirectory(s.Globals["base_directory"].(string)); err != nil {
t.Fatal(err)
}
@@ -394,13 +405,13 @@ func TestBaseDirectory(t *testing.T) {
}
func BenchmarkCache(b *testing.B) {
- cacheSet := pongo2.NewSet("cache set", pongo2.MustNewLocalFileSystemLoader(""))
+ cache_set := NewSet("cache set")
for i := 0; i < b.N; i++ {
- tpl, err := cacheSet.FromCache("template_tests/complex.tpl")
+ tpl, err := cache_set.FromCache("template_tests/complex.tpl")
if err != nil {
b.Fatal(err)
}
- err = tpl.ExecuteWriterUnbuffered(tplContext, ioutil.Discard)
+ _, err = tpl.ExecuteBytes(tplContext)
if err != nil {
b.Fatal(err)
}
@@ -408,14 +419,14 @@ func BenchmarkCache(b *testing.B) {
}
func BenchmarkCacheDebugOn(b *testing.B) {
- cacheDebugSet := pongo2.NewSet("cache set", pongo2.MustNewLocalFileSystemLoader(""))
- cacheDebugSet.Debug = true
+ cache_debug_set := NewSet("cache set")
+ cache_debug_set.Debug = true
for i := 0; i < b.N; i++ {
- tpl, err := cacheDebugSet.FromFile("template_tests/complex.tpl")
+ tpl, err := cache_debug_set.FromFile("template_tests/complex.tpl")
if err != nil {
b.Fatal(err)
}
- err = tpl.ExecuteWriterUnbuffered(tplContext, ioutil.Discard)
+ _, err = tpl.ExecuteBytes(tplContext)
if err != nil {
b.Fatal(err)
}
@@ -423,13 +434,13 @@ func BenchmarkCacheDebugOn(b *testing.B) {
}
func BenchmarkExecuteComplexWithSandboxActive(b *testing.B) {
- tpl, err := pongo2.FromFile("template_tests/complex.tpl")
+ tpl, err := FromFile("template_tests/complex.tpl")
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
- err = tpl.ExecuteWriterUnbuffered(tplContext, ioutil.Discard)
+ _, err = tpl.ExecuteBytes(tplContext)
if err != nil {
b.Fatal(err)
}
@@ -444,12 +455,12 @@ func BenchmarkCompileAndExecuteComplexWithSandboxActive(b *testing.B) {
preloadedTpl := string(buf)
b.ResetTimer()
for i := 0; i < b.N; i++ {
- tpl, err := pongo2.FromString(preloadedTpl)
+ tpl, err := FromString(preloadedTpl)
if err != nil {
b.Fatal(err)
}
- err = tpl.ExecuteWriterUnbuffered(tplContext, ioutil.Discard)
+ _, err = tpl.ExecuteBytes(tplContext)
if err != nil {
b.Fatal(err)
}
@@ -457,14 +468,14 @@ func BenchmarkCompileAndExecuteComplexWithSandboxActive(b *testing.B) {
}
func BenchmarkParallelExecuteComplexWithSandboxActive(b *testing.B) {
- tpl, err := pongo2.FromFile("template_tests/complex.tpl")
+ tpl, err := FromFile("template_tests/complex.tpl")
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
- err := tpl.ExecuteWriterUnbuffered(tplContext, ioutil.Discard)
+ _, err := tpl.ExecuteBytes(tplContext)
if err != nil {
b.Fatal(err)
}
@@ -473,14 +484,14 @@ func BenchmarkParallelExecuteComplexWithSandboxActive(b *testing.B) {
}
func BenchmarkExecuteComplexWithoutSandbox(b *testing.B) {
- s := pongo2.NewSet("set without sandbox", pongo2.MustNewLocalFileSystemLoader(""))
+ s := NewSet("set without sandbox")
tpl, err := s.FromFile("template_tests/complex.tpl")
if err != nil {
b.Fatal(err)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
- err = tpl.ExecuteWriterUnbuffered(tplContext, ioutil.Discard)
+ _, err = tpl.ExecuteBytes(tplContext)
if err != nil {
b.Fatal(err)
}
@@ -494,7 +505,7 @@ func BenchmarkCompileAndExecuteComplexWithoutSandbox(b *testing.B) {
}
preloadedTpl := string(buf)
- s := pongo2.NewSet("set without sandbox", pongo2.MustNewLocalFileSystemLoader(""))
+ s := NewSet("set without sandbox")
b.ResetTimer()
for i := 0; i < b.N; i++ {
@@ -503,7 +514,7 @@ func BenchmarkCompileAndExecuteComplexWithoutSandbox(b *testing.B) {
b.Fatal(err)
}
- err = tpl.ExecuteWriterUnbuffered(tplContext, ioutil.Discard)
+ _, err = tpl.ExecuteBytes(tplContext)
if err != nil {
b.Fatal(err)
}
@@ -511,7 +522,7 @@ func BenchmarkCompileAndExecuteComplexWithoutSandbox(b *testing.B) {
}
func BenchmarkParallelExecuteComplexWithoutSandbox(b *testing.B) {
- s := pongo2.NewSet("set without sandbox", pongo2.MustNewLocalFileSystemLoader(""))
+ s := NewSet("set without sandbox")
tpl, err := s.FromFile("template_tests/complex.tpl")
if err != nil {
b.Fatal(err)
@@ -519,7 +530,7 @@ func BenchmarkParallelExecuteComplexWithoutSandbox(b *testing.B) {
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
- err := tpl.ExecuteWriterUnbuffered(tplContext, ioutil.Discard)
+ _, err := tpl.ExecuteBytes(tplContext)
if err != nil {
b.Fatal(err)
}
diff --git a/vendor/github.com/flosch/pongo2/pongo2_test.go b/vendor/github.com/flosch/pongo2/pongo2_test.go
index ea56f0b..5f54584 100644
--- a/vendor/github.com/flosch/pongo2/pongo2_test.go
+++ b/vendor/github.com/flosch/pongo2/pongo2_test.go
@@ -1,10 +1,8 @@
-package pongo2_test
+package pongo2
import (
"testing"
- "github.com/flosch/pongo2"
-
. "gopkg.in/check.v1"
)
@@ -13,16 +11,16 @@ import (
func Test(t *testing.T) { TestingT(t) }
type TestSuite struct {
- tpl *pongo2.Template
+ tpl *Template
}
var (
- _ = Suite(&TestSuite{})
- testSuite2 = pongo2.NewSet("test suite 2", pongo2.MustNewLocalFileSystemLoader(""))
+ _ = Suite(&TestSuite{})
+ test_suite2 = NewSet("test suite 2")
)
-func parseTemplate(s string, c pongo2.Context) string {
- t, err := testSuite2.FromString(s)
+func parseTemplate(s string, c Context) string {
+ t, err := test_suite2.FromString(s)
if err != nil {
panic(err)
}
@@ -33,7 +31,7 @@ func parseTemplate(s string, c pongo2.Context) string {
return out
}
-func parseTemplateFn(s string, c pongo2.Context) func() {
+func parseTemplateFn(s string, c Context) func() {
return func() {
parseTemplate(s, c)
}
@@ -42,27 +40,25 @@ func parseTemplateFn(s string, c pongo2.Context) func() {
func (s *TestSuite) TestMisc(c *C) {
// Must
// TODO: Add better error message (see issue #18)
- c.Check(
- func() { pongo2.Must(testSuite2.FromFile("template_tests/inheritance/base2.tpl")) },
+ c.Check(func() { Must(test_suite2.FromFile("template_tests/inheritance/base2.tpl")) },
PanicMatches,
- `\[Error \(where: fromfile\) in .*template_tests/inheritance/doesnotexist.tpl | Line 1 Col 12 near 'doesnotexist.tpl'\] open .*template_tests/inheritance/doesnotexist.tpl: no such file or directory`,
- )
+ `\[Error \(where: fromfile\) in template_tests/inheritance/doesnotexist.tpl | Line 1 Col 12 near 'doesnotexist.tpl'\] open template_tests/inheritance/doesnotexist.tpl: no such file or directory`)
// Context
- c.Check(parseTemplateFn("", pongo2.Context{"'illegal": nil}), PanicMatches, ".*not a valid identifier.*")
+ c.Check(parseTemplateFn("", Context{"'illegal": nil}), PanicMatches, ".*not a valid identifier.*")
// Registers
- c.Check(func() { pongo2.RegisterFilter("escape", nil) }, PanicMatches, ".*is already registered.*")
- c.Check(func() { pongo2.RegisterTag("for", nil) }, PanicMatches, ".*is already registered.*")
+ c.Check(func() { RegisterFilter("escape", nil) }, PanicMatches, ".*is already registered.*")
+ c.Check(func() { RegisterTag("for", nil) }, PanicMatches, ".*is already registered.*")
// ApplyFilter
- v, err := pongo2.ApplyFilter("title", pongo2.AsValue("this is a title"), nil)
+ v, err := ApplyFilter("title", AsValue("this is a title"), nil)
if err != nil {
c.Fatal(err)
}
c.Check(v.String(), Equals, "This Is A Title")
c.Check(func() {
- _, err := pongo2.ApplyFilter("doesnotexist", nil, nil)
+ _, err := ApplyFilter("doesnotexist", nil, nil)
if err != nil {
panic(err)
}
diff --git a/vendor/github.com/flosch/pongo2/tags.go b/vendor/github.com/flosch/pongo2/tags.go
index 5168d17..292c30d 100644
--- a/vendor/github.com/flosch/pongo2/tags.go
+++ b/vendor/github.com/flosch/pongo2/tags.go
@@ -87,46 +87,46 @@ func ReplaceTag(name string, parserFn TagParser) {
// Tag = "{%" IDENT ARGS "%}"
func (p *Parser) parseTagElement() (INodeTag, *Error) {
p.Consume() // consume "{%"
- tokenName := p.MatchType(TokenIdentifier)
+ token_name := p.MatchType(TokenIdentifier)
// Check for identifier
- if tokenName == nil {
+ if token_name == nil {
return nil, p.Error("Tag name must be an identifier.", nil)
}
// Check for the existing tag
- tag, exists := tags[tokenName.Val]
+ tag, exists := tags[token_name.Val]
if !exists {
// Does not exists
- return nil, p.Error(fmt.Sprintf("Tag '%s' not found (or beginning tag not provided)", tokenName.Val), tokenName)
+ return nil, p.Error(fmt.Sprintf("Tag '%s' not found (or beginning tag not provided)", token_name.Val), token_name)
}
// Check sandbox tag restriction
- if _, isBanned := p.template.set.bannedTags[tokenName.Val]; isBanned {
- return nil, p.Error(fmt.Sprintf("Usage of tag '%s' is not allowed (sandbox restriction active).", tokenName.Val), tokenName)
+ if _, is_banned := p.template.set.bannedTags[token_name.Val]; is_banned {
+ return nil, p.Error(fmt.Sprintf("Usage of tag '%s' is not allowed (sandbox restriction active).", token_name.Val), token_name)
}
- var argsToken []*Token
+ args_token := make([]*Token, 0)
for p.Peek(TokenSymbol, "%}") == nil && p.Remaining() > 0 {
// Add token to args
- argsToken = append(argsToken, p.Current())
+ args_token = append(args_token, p.Current())
p.Consume() // next token
}
// EOF?
if p.Remaining() == 0 {
- return nil, p.Error("Unexpectedly reached EOF, no tag end found.", p.lastToken)
+ return nil, p.Error("Unexpectedly reached EOF, no tag end found.", p.last_token)
}
p.Match(TokenSymbol, "%}")
- argParser := newParser(p.name, argsToken, p.template)
- if len(argsToken) == 0 {
+ arg_parser := newParser(p.name, args_token, p.template)
+ if len(args_token) == 0 {
// This is done to have nice EOF error messages
- argParser.lastToken = tokenName
+ arg_parser.last_token = token_name
}
p.template.level++
defer func() { p.template.level-- }()
- return tag.parser(p, tokenName, argParser)
+ return tag.parser(p, token_name, arg_parser)
}
diff --git a/vendor/github.com/flosch/pongo2/tags_autoescape.go b/vendor/github.com/flosch/pongo2/tags_autoescape.go
index 590a1db..ec30438 100644
--- a/vendor/github.com/flosch/pongo2/tags_autoescape.go
+++ b/vendor/github.com/flosch/pongo2/tags_autoescape.go
@@ -1,15 +1,19 @@
package pongo2
+import (
+ "bytes"
+)
+
type tagAutoescapeNode struct {
wrapper *NodeWrapper
autoescape bool
}
-func (node *tagAutoescapeNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagAutoescapeNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
old := ctx.Autoescape
ctx.Autoescape = node.autoescape
- err := node.wrapper.Execute(ctx, writer)
+ err := node.wrapper.Execute(ctx, buffer)
if err != nil {
return err
}
@@ -20,22 +24,22 @@ func (node *tagAutoescapeNode) Execute(ctx *ExecutionContext, writer TemplateWri
}
func tagAutoescapeParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- autoescapeNode := &tagAutoescapeNode{}
+ autoescape_node := &tagAutoescapeNode{}
wrapper, _, err := doc.WrapUntilTag("endautoescape")
if err != nil {
return nil, err
}
- autoescapeNode.wrapper = wrapper
+ autoescape_node.wrapper = wrapper
- modeToken := arguments.MatchType(TokenIdentifier)
- if modeToken == nil {
+ mode_token := arguments.MatchType(TokenIdentifier)
+ if mode_token == nil {
return nil, arguments.Error("A mode is required for autoescape-tag.", nil)
}
- if modeToken.Val == "on" {
- autoescapeNode.autoescape = true
- } else if modeToken.Val == "off" {
- autoescapeNode.autoescape = false
+ if mode_token.Val == "on" {
+ autoescape_node.autoescape = true
+ } else if mode_token.Val == "off" {
+ autoescape_node.autoescape = false
} else {
return nil, arguments.Error("Only 'on' or 'off' is valid as an autoescape-mode.", nil)
}
@@ -44,7 +48,7 @@ func tagAutoescapeParser(doc *Parser, start *Token, arguments *Parser) (INodeTag
return nil, arguments.Error("Malformed autoescape-tag arguments.", nil)
}
- return autoescapeNode, nil
+ return autoescape_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_block.go b/vendor/github.com/flosch/pongo2/tags_block.go
index b558930..30e205a 100644
--- a/vendor/github.com/flosch/pongo2/tags_block.go
+++ b/vendor/github.com/flosch/pongo2/tags_block.go
@@ -1,6 +1,7 @@
package pongo2
import (
+ "bytes"
"fmt"
)
@@ -21,18 +22,18 @@ func (node *tagBlockNode) getBlockWrapperByName(tpl *Template) *NodeWrapper {
return t
}
-func (node *tagBlockNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagBlockNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
tpl := ctx.template
if tpl == nil {
panic("internal error: tpl == nil")
}
// Determine the block to execute
- blockWrapper := node.getBlockWrapperByName(tpl)
- if blockWrapper == nil {
+ block_wrapper := node.getBlockWrapperByName(tpl)
+ if block_wrapper == nil {
// fmt.Printf("could not find: %s\n", node.name)
return ctx.Error("internal error: block_wrapper == nil in tagBlockNode.Execute()", nil)
}
- err := blockWrapper.Execute(ctx, writer)
+ err := block_wrapper.Execute(ctx, buffer)
if err != nil {
return err
}
@@ -47,8 +48,8 @@ func tagBlockParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Er
return nil, arguments.Error("Tag 'block' requires an identifier.", nil)
}
- nameToken := arguments.MatchType(TokenIdentifier)
- if nameToken == nil {
+ name_token := arguments.MatchType(TokenIdentifier)
+ if name_token == nil {
return nil, arguments.Error("First argument for tag 'block' must be an identifier.", nil)
}
@@ -61,15 +62,15 @@ func tagBlockParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Er
return nil, err
}
if endtagargs.Remaining() > 0 {
- endtagnameToken := endtagargs.MatchType(TokenIdentifier)
- if endtagnameToken != nil {
- if endtagnameToken.Val != nameToken.Val {
+ endtagname_token := endtagargs.MatchType(TokenIdentifier)
+ if endtagname_token != nil {
+ if endtagname_token.Val != name_token.Val {
return nil, endtagargs.Error(fmt.Sprintf("Name for 'endblock' must equal to 'block'-tag's name ('%s' != '%s').",
- nameToken.Val, endtagnameToken.Val), nil)
+ name_token.Val, endtagname_token.Val), nil)
}
}
- if endtagnameToken == nil || endtagargs.Remaining() > 0 {
+ if endtagname_token == nil || endtagargs.Remaining() > 0 {
return nil, endtagargs.Error("Either no or only one argument (identifier) allowed for 'endblock'.", nil)
}
}
@@ -78,14 +79,14 @@ func tagBlockParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Er
if tpl == nil {
panic("internal error: tpl == nil")
}
- _, hasBlock := tpl.blocks[nameToken.Val]
- if !hasBlock {
- tpl.blocks[nameToken.Val] = wrapper
+ _, has_block := tpl.blocks[name_token.Val]
+ if !has_block {
+ tpl.blocks[name_token.Val] = wrapper
} else {
- return nil, arguments.Error(fmt.Sprintf("Block named '%s' already defined", nameToken.Val), nil)
+ return nil, arguments.Error(fmt.Sprintf("Block named '%s' already defined", name_token.Val), nil)
}
- return &tagBlockNode{name: nameToken.Val}, nil
+ return &tagBlockNode{name: name_token.Val}, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_comment.go b/vendor/github.com/flosch/pongo2/tags_comment.go
index a66a973..8c22496 100644
--- a/vendor/github.com/flosch/pongo2/tags_comment.go
+++ b/vendor/github.com/flosch/pongo2/tags_comment.go
@@ -1,13 +1,17 @@
package pongo2
+import (
+ "bytes"
+)
+
type tagCommentNode struct{}
-func (node *tagCommentNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagCommentNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
return nil
}
func tagCommentParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- commentNode := &tagCommentNode{}
+ comment_node := &tagCommentNode{}
// TODO: Process the endtag's arguments (see django 'comment'-tag documentation)
_, _, err := doc.WrapUntilTag("endcomment")
@@ -19,7 +23,7 @@ func tagCommentParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *
return nil, arguments.Error("Tag 'comment' does not take any argument.", nil)
}
- return commentNode, nil
+ return comment_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_cycle.go b/vendor/github.com/flosch/pongo2/tags_cycle.go
index 9b83b9b..6a6830e 100644
--- a/vendor/github.com/flosch/pongo2/tags_cycle.go
+++ b/vendor/github.com/flosch/pongo2/tags_cycle.go
@@ -1,5 +1,9 @@
package pongo2
+import (
+ "bytes"
+)
+
type tagCycleValue struct {
node *tagCycleNode
value *Value
@@ -9,7 +13,7 @@ type tagCycleNode struct {
position *Token
args []IEvaluator
idx int
- asName string
+ as_name string
silent bool
}
@@ -17,7 +21,7 @@ func (cv *tagCycleValue) String() string {
return cv.value.String()
}
-func (node *tagCycleNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagCycleNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
item := node.args[node.idx%len(node.args)]
node.idx++
@@ -42,21 +46,21 @@ func (node *tagCycleNode) Execute(ctx *ExecutionContext, writer TemplateWriter)
t.value = val
if !t.node.silent {
- writer.WriteString(val.String())
+ buffer.WriteString(val.String())
}
} else {
// Regular call
- cycleValue := &tagCycleValue{
+ cycle_value := &tagCycleValue{
node: node,
value: val,
}
- if node.asName != "" {
- ctx.Private[node.asName] = cycleValue
+ if node.as_name != "" {
+ ctx.Private[node.as_name] = cycle_value
}
if !node.silent {
- writer.WriteString(val.String())
+ buffer.WriteString(val.String())
}
}
@@ -65,7 +69,7 @@ func (node *tagCycleNode) Execute(ctx *ExecutionContext, writer TemplateWriter)
// HINT: We're not supporting the old comma-seperated list of expresions argument-style
func tagCycleParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- cycleNode := &tagCycleNode{
+ cycle_node := &tagCycleNode{
position: start,
}
@@ -74,19 +78,19 @@ func tagCycleParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Er
if err != nil {
return nil, err
}
- cycleNode.args = append(cycleNode.args, node)
+ cycle_node.args = append(cycle_node.args, node)
if arguments.MatchOne(TokenKeyword, "as") != nil {
// as
- nameToken := arguments.MatchType(TokenIdentifier)
- if nameToken == nil {
+ name_token := arguments.MatchType(TokenIdentifier)
+ if name_token == nil {
return nil, arguments.Error("Name (identifier) expected after 'as'.", nil)
}
- cycleNode.asName = nameToken.Val
+ cycle_node.as_name = name_token.Val
if arguments.MatchOne(TokenIdentifier, "silent") != nil {
- cycleNode.silent = true
+ cycle_node.silent = true
}
// Now we're finished
@@ -98,7 +102,7 @@ func tagCycleParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Er
return nil, arguments.Error("Malformed cycle-tag.", nil)
}
- return cycleNode, nil
+ return cycle_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_extends.go b/vendor/github.com/flosch/pongo2/tags_extends.go
index 5771020..6abbb6b 100644
--- a/vendor/github.com/flosch/pongo2/tags_extends.go
+++ b/vendor/github.com/flosch/pongo2/tags_extends.go
@@ -1,15 +1,19 @@
package pongo2
+import (
+ "bytes"
+)
+
type tagExtendsNode struct {
filename string
}
-func (node *tagExtendsNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagExtendsNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
return nil
}
func tagExtendsParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- extendsNode := &tagExtendsNode{}
+ extends_node := &tagExtendsNode{}
if doc.template.level > 1 {
return nil, arguments.Error("The 'extends' tag can only defined on root level.", start)
@@ -20,22 +24,22 @@ func tagExtendsParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *
return nil, arguments.Error("This template has already one parent.", start)
}
- if filenameToken := arguments.MatchType(TokenString); filenameToken != nil {
+ if filename_token := arguments.MatchType(TokenString); filename_token != nil {
// prepared, static template
// Get parent's filename
- parentFilename := doc.template.set.resolveFilename(doc.template, filenameToken.Val)
+ parent_filename := doc.template.set.resolveFilename(doc.template, filename_token.Val)
// Parse the parent
- parentTemplate, err := doc.template.set.FromFile(parentFilename)
+ parent_template, err := doc.template.set.FromFile(parent_filename)
if err != nil {
return nil, err.(*Error)
}
// Keep track of things
- parentTemplate.child = doc.template
- doc.template.parent = parentTemplate
- extendsNode.filename = parentFilename
+ parent_template.child = doc.template
+ doc.template.parent = parent_template
+ extends_node.filename = parent_filename
} else {
return nil, arguments.Error("Tag 'extends' requires a template filename as string.", nil)
}
@@ -44,7 +48,7 @@ func tagExtendsParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *
return nil, arguments.Error("Tag 'extends' does only take 1 argument.", nil)
}
- return extendsNode, nil
+ return extends_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_filter.go b/vendor/github.com/flosch/pongo2/tags_filter.go
index b38fd92..f421e5a 100644
--- a/vendor/github.com/flosch/pongo2/tags_filter.go
+++ b/vendor/github.com/flosch/pongo2/tags_filter.go
@@ -5,8 +5,8 @@ import (
)
type nodeFilterCall struct {
- name string
- paramExpr IEvaluator
+ name string
+ param_expr IEvaluator
}
type tagFilterNode struct {
@@ -15,7 +15,7 @@ type tagFilterNode struct {
filterChain []*nodeFilterCall
}
-func (node *tagFilterNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagFilterNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
temp := bytes.NewBuffer(make([]byte, 0, 1024)) // 1 KiB size
err := node.bodyWrapper.Execute(ctx, temp)
@@ -27,8 +27,8 @@ func (node *tagFilterNode) Execute(ctx *ExecutionContext, writer TemplateWriter)
for _, call := range node.filterChain {
var param *Value
- if call.paramExpr != nil {
- param, err = call.paramExpr.Evaluate(ctx)
+ if call.param_expr != nil {
+ param, err = call.param_expr.Evaluate(ctx)
if err != nil {
return err
}
@@ -41,13 +41,13 @@ func (node *tagFilterNode) Execute(ctx *ExecutionContext, writer TemplateWriter)
}
}
- writer.WriteString(value.String())
+ buffer.WriteString(value.String())
return nil
}
func tagFilterParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- filterNode := &tagFilterNode{
+ filter_node := &tagFilterNode{
position: start,
}
@@ -55,16 +55,16 @@ func tagFilterParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *E
if err != nil {
return nil, err
}
- filterNode.bodyWrapper = wrapper
+ filter_node.bodyWrapper = wrapper
for arguments.Remaining() > 0 {
filterCall := &nodeFilterCall{}
- nameToken := arguments.MatchType(TokenIdentifier)
- if nameToken == nil {
+ name_token := arguments.MatchType(TokenIdentifier)
+ if name_token == nil {
return nil, arguments.Error("Expected a filter name (identifier).", nil)
}
- filterCall.name = nameToken.Val
+ filterCall.name = name_token.Val
if arguments.MatchOne(TokenSymbol, ":") != nil {
// Filter parameter
@@ -73,10 +73,10 @@ func tagFilterParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *E
if err != nil {
return nil, err
}
- filterCall.paramExpr = expr
+ filterCall.param_expr = expr
}
- filterNode.filterChain = append(filterNode.filterChain, filterCall)
+ filter_node.filterChain = append(filter_node.filterChain, filterCall)
if arguments.MatchOne(TokenSymbol, "|") == nil {
break
@@ -87,7 +87,7 @@ func tagFilterParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *E
return nil, arguments.Error("Malformed filter-tag arguments.", nil)
}
- return filterNode, nil
+ return filter_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_firstof.go b/vendor/github.com/flosch/pongo2/tags_firstof.go
index 5b2888e..b677979 100644
--- a/vendor/github.com/flosch/pongo2/tags_firstof.go
+++ b/vendor/github.com/flosch/pongo2/tags_firstof.go
@@ -1,11 +1,15 @@
package pongo2
+import (
+ "bytes"
+)
+
type tagFirstofNode struct {
position *Token
args []IEvaluator
}
-func (node *tagFirstofNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagFirstofNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
for _, arg := range node.args {
val, err := arg.Evaluate(ctx)
if err != nil {
@@ -20,7 +24,7 @@ func (node *tagFirstofNode) Execute(ctx *ExecutionContext, writer TemplateWriter
}
}
- writer.WriteString(val.String())
+ buffer.WriteString(val.String())
return nil
}
}
@@ -29,7 +33,7 @@ func (node *tagFirstofNode) Execute(ctx *ExecutionContext, writer TemplateWriter
}
func tagFirstofParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- firstofNode := &tagFirstofNode{
+ firstof_node := &tagFirstofNode{
position: start,
}
@@ -38,10 +42,10 @@ func tagFirstofParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *
if err != nil {
return nil, err
}
- firstofNode.args = append(firstofNode.args, node)
+ firstof_node.args = append(firstof_node.args, node)
}
- return firstofNode, nil
+ return firstof_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_for.go b/vendor/github.com/flosch/pongo2/tags_for.go
index 5b0b555..de56699 100644
--- a/vendor/github.com/flosch/pongo2/tags_for.go
+++ b/vendor/github.com/flosch/pongo2/tags_for.go
@@ -1,11 +1,14 @@
package pongo2
+import (
+ "bytes"
+)
+
type tagForNode struct {
- key string
- value string // only for maps: for key, value in map
- objectEvaluator IEvaluator
- reversed bool
- sorted bool
+ key string
+ value string // only for maps: for key, value in map
+ object_evaluator IEvaluator
+ reversed bool
bodyWrapper *NodeWrapper
emptyWrapper *NodeWrapper
@@ -21,7 +24,7 @@ type tagForLoopInformation struct {
Parentloop *tagForLoopInformation
}
-func (node *tagForNode) Execute(ctx *ExecutionContext, writer TemplateWriter) (forError *Error) {
+func (node *tagForNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) (forError *Error) {
// Backup forloop (as parentloop in public context), key-name and value-name
forCtx := NewChildExecutionContext(ctx)
parentloop := forCtx.Private["forloop"]
@@ -39,7 +42,7 @@ func (node *tagForNode) Execute(ctx *ExecutionContext, writer TemplateWriter) (f
// Register loopInfo in public context
forCtx.Private["forloop"] = loopInfo
- obj, err := node.objectEvaluator.Evaluate(forCtx)
+ obj, err := node.object_evaluator.Evaluate(forCtx)
if err != nil {
return err
}
@@ -64,7 +67,7 @@ func (node *tagForNode) Execute(ctx *ExecutionContext, writer TemplateWriter) (f
loopInfo.Revcounter0 = count - (idx + 1) // TODO: Not sure about this, have to look it up
// Render elements with updated context
- err := node.bodyWrapper.Execute(forCtx, writer)
+ err := node.bodyWrapper.Execute(forCtx, buffer)
if err != nil {
forError = err
return false
@@ -73,30 +76,30 @@ func (node *tagForNode) Execute(ctx *ExecutionContext, writer TemplateWriter) (f
}, func() {
// Nothing to iterate over (maybe wrong type or no items)
if node.emptyWrapper != nil {
- err := node.emptyWrapper.Execute(forCtx, writer)
+ err := node.emptyWrapper.Execute(forCtx, buffer)
if err != nil {
forError = err
}
}
- }, node.reversed, node.sorted)
+ }, node.reversed)
- return forError
+ return nil
}
func tagForParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- forNode := &tagForNode{}
+ for_node := &tagForNode{}
// Arguments parsing
- var valueToken *Token
- keyToken := arguments.MatchType(TokenIdentifier)
- if keyToken == nil {
+ var value_token *Token
+ key_token := arguments.MatchType(TokenIdentifier)
+ if key_token == nil {
return nil, arguments.Error("Expected an key identifier as first argument for 'for'-tag", nil)
}
if arguments.Match(TokenSymbol, ",") != nil {
// Value name is provided
- valueToken = arguments.MatchType(TokenIdentifier)
- if valueToken == nil {
+ value_token = arguments.MatchType(TokenIdentifier)
+ if value_token == nil {
return nil, arguments.Error("Value name must be an identifier.", nil)
}
}
@@ -105,22 +108,18 @@ func tagForParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Erro
return nil, arguments.Error("Expected keyword 'in'.", nil)
}
- objectEvaluator, err := arguments.ParseExpression()
+ object_evaluator, err := arguments.ParseExpression()
if err != nil {
return nil, err
}
- forNode.objectEvaluator = objectEvaluator
- forNode.key = keyToken.Val
- if valueToken != nil {
- forNode.value = valueToken.Val
+ for_node.object_evaluator = object_evaluator
+ for_node.key = key_token.Val
+ if value_token != nil {
+ for_node.value = value_token.Val
}
if arguments.MatchOne(TokenIdentifier, "reversed") != nil {
- forNode.reversed = true
- }
-
- if arguments.MatchOne(TokenIdentifier, "sorted") != nil {
- forNode.sorted = true
+ for_node.reversed = true
}
if arguments.Remaining() > 0 {
@@ -132,7 +131,7 @@ func tagForParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Erro
if err != nil {
return nil, err
}
- forNode.bodyWrapper = wrapper
+ for_node.bodyWrapper = wrapper
if endargs.Count() > 0 {
return nil, endargs.Error("Arguments not allowed here.", nil)
@@ -144,14 +143,14 @@ func tagForParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Erro
if err != nil {
return nil, err
}
- forNode.emptyWrapper = wrapper
+ for_node.emptyWrapper = wrapper
if endargs.Count() > 0 {
return nil, endargs.Error("Arguments not allowed here.", nil)
}
}
- return forNode, nil
+ return for_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_if.go b/vendor/github.com/flosch/pongo2/tags_if.go
index 3eeaf3b..2515c44 100644
--- a/vendor/github.com/flosch/pongo2/tags_if.go
+++ b/vendor/github.com/flosch/pongo2/tags_if.go
@@ -1,11 +1,15 @@
package pongo2
+import (
+ "bytes"
+)
+
type tagIfNode struct {
conditions []IEvaluator
wrappers []*NodeWrapper
}
-func (node *tagIfNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagIfNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
for i, condition := range node.conditions {
result, err := condition.Evaluate(ctx)
if err != nil {
@@ -13,25 +17,26 @@ func (node *tagIfNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Er
}
if result.IsTrue() {
- return node.wrappers[i].Execute(ctx, writer)
- }
- // Last condition?
- if len(node.conditions) == i+1 && len(node.wrappers) > i+1 {
- return node.wrappers[i+1].Execute(ctx, writer)
+ return node.wrappers[i].Execute(ctx, buffer)
+ } else {
+ // Last condition?
+ if len(node.conditions) == i+1 && len(node.wrappers) > i+1 {
+ return node.wrappers[i+1].Execute(ctx, buffer)
+ }
}
}
return nil
}
func tagIfParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- ifNode := &tagIfNode{}
+ if_node := &tagIfNode{}
// Parse first and main IF condition
condition, err := arguments.ParseExpression()
if err != nil {
return nil, err
}
- ifNode.conditions = append(ifNode.conditions, condition)
+ if_node.conditions = append(if_node.conditions, condition)
if arguments.Remaining() > 0 {
return nil, arguments.Error("If-condition is malformed.", nil)
@@ -39,27 +44,27 @@ func tagIfParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error
// Check the rest
for {
- wrapper, tagArgs, err := doc.WrapUntilTag("elif", "else", "endif")
+ wrapper, tag_args, err := doc.WrapUntilTag("elif", "else", "endif")
if err != nil {
return nil, err
}
- ifNode.wrappers = append(ifNode.wrappers, wrapper)
+ if_node.wrappers = append(if_node.wrappers, wrapper)
if wrapper.Endtag == "elif" {
// elif can take a condition
- condition, err = tagArgs.ParseExpression()
+ condition, err := tag_args.ParseExpression()
if err != nil {
return nil, err
}
- ifNode.conditions = append(ifNode.conditions, condition)
+ if_node.conditions = append(if_node.conditions, condition)
- if tagArgs.Remaining() > 0 {
- return nil, tagArgs.Error("Elif-condition is malformed.", nil)
+ if tag_args.Remaining() > 0 {
+ return nil, tag_args.Error("Elif-condition is malformed.", nil)
}
} else {
- if tagArgs.Count() > 0 {
+ if tag_args.Count() > 0 {
// else/endif can't take any conditions
- return nil, tagArgs.Error("Arguments not allowed here.", nil)
+ return nil, tag_args.Error("Arguments not allowed here.", nil)
}
}
@@ -68,7 +73,7 @@ func tagIfParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error
}
}
- return ifNode, nil
+ return if_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_ifchanged.go b/vendor/github.com/flosch/pongo2/tags_ifchanged.go
index 45296a0..4412ace 100644
--- a/vendor/github.com/flosch/pongo2/tags_ifchanged.go
+++ b/vendor/github.com/flosch/pongo2/tags_ifchanged.go
@@ -5,15 +5,16 @@ import (
)
type tagIfchangedNode struct {
- watchedExpr []IEvaluator
- lastValues []*Value
- lastContent []byte
- thenWrapper *NodeWrapper
- elseWrapper *NodeWrapper
+ watched_expr []IEvaluator
+ last_values []*Value
+ last_content []byte
+ thenWrapper *NodeWrapper
+ elseWrapper *NodeWrapper
}
-func (node *tagIfchangedNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
- if len(node.watchedExpr) == 0 {
+func (node *tagIfchangedNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
+
+ if len(node.watched_expr) == 0 {
// Check against own rendered body
buf := bytes.NewBuffer(make([]byte, 0, 1024)) // 1 KiB
@@ -22,43 +23,43 @@ func (node *tagIfchangedNode) Execute(ctx *ExecutionContext, writer TemplateWrit
return err
}
- bufBytes := buf.Bytes()
- if !bytes.Equal(node.lastContent, bufBytes) {
+ buf_bytes := buf.Bytes()
+ if !bytes.Equal(node.last_content, buf_bytes) {
// Rendered content changed, output it
- writer.Write(bufBytes)
- node.lastContent = bufBytes
+ buffer.Write(buf_bytes)
+ node.last_content = buf_bytes
}
} else {
- nowValues := make([]*Value, 0, len(node.watchedExpr))
- for _, expr := range node.watchedExpr {
+ now_values := make([]*Value, 0, len(node.watched_expr))
+ for _, expr := range node.watched_expr {
val, err := expr.Evaluate(ctx)
if err != nil {
return err
}
- nowValues = append(nowValues, val)
+ now_values = append(now_values, val)
}
// Compare old to new values now
- changed := len(node.lastValues) == 0
+ changed := len(node.last_values) == 0
- for idx, oldVal := range node.lastValues {
- if !oldVal.EqualValueTo(nowValues[idx]) {
+ for idx, old_val := range node.last_values {
+ if !old_val.EqualValueTo(now_values[idx]) {
changed = true
break // we can stop here because ONE value changed
}
}
- node.lastValues = nowValues
+ node.last_values = now_values
if changed {
// Render thenWrapper
- err := node.thenWrapper.Execute(ctx, writer)
+ err := node.thenWrapper.Execute(ctx, buffer)
if err != nil {
return err
}
} else {
// Render elseWrapper
- err := node.elseWrapper.Execute(ctx, writer)
+ err := node.elseWrapper.Execute(ctx, buffer)
if err != nil {
return err
}
@@ -69,7 +70,7 @@ func (node *tagIfchangedNode) Execute(ctx *ExecutionContext, writer TemplateWrit
}
func tagIfchangedParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- ifchangedNode := &tagIfchangedNode{}
+ ifchanged_node := &tagIfchangedNode{}
for arguments.Remaining() > 0 {
// Parse condition
@@ -77,7 +78,7 @@ func tagIfchangedParser(doc *Parser, start *Token, arguments *Parser) (INodeTag,
if err != nil {
return nil, err
}
- ifchangedNode.watchedExpr = append(ifchangedNode.watchedExpr, expr)
+ ifchanged_node.watched_expr = append(ifchanged_node.watched_expr, expr)
}
if arguments.Remaining() > 0 {
@@ -89,7 +90,7 @@ func tagIfchangedParser(doc *Parser, start *Token, arguments *Parser) (INodeTag,
if err != nil {
return nil, err
}
- ifchangedNode.thenWrapper = wrapper
+ ifchanged_node.thenWrapper = wrapper
if endargs.Count() > 0 {
return nil, endargs.Error("Arguments not allowed here.", nil)
@@ -101,14 +102,14 @@ func tagIfchangedParser(doc *Parser, start *Token, arguments *Parser) (INodeTag,
if err != nil {
return nil, err
}
- ifchangedNode.elseWrapper = wrapper
+ ifchanged_node.elseWrapper = wrapper
if endargs.Count() > 0 {
return nil, endargs.Error("Arguments not allowed here.", nil)
}
}
- return ifchangedNode, nil
+ return ifchanged_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_ifequal.go b/vendor/github.com/flosch/pongo2/tags_ifequal.go
index 103f1c7..035b8fd 100644
--- a/vendor/github.com/flosch/pongo2/tags_ifequal.go
+++ b/vendor/github.com/flosch/pongo2/tags_ifequal.go
@@ -1,12 +1,16 @@
package pongo2
+import (
+ "bytes"
+)
+
type tagIfEqualNode struct {
var1, var2 IEvaluator
thenWrapper *NodeWrapper
elseWrapper *NodeWrapper
}
-func (node *tagIfEqualNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagIfEqualNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
r1, err := node.var1.Evaluate(ctx)
if err != nil {
return err
@@ -19,16 +23,17 @@ func (node *tagIfEqualNode) Execute(ctx *ExecutionContext, writer TemplateWriter
result := r1.EqualValueTo(r2)
if result {
- return node.thenWrapper.Execute(ctx, writer)
- }
- if node.elseWrapper != nil {
- return node.elseWrapper.Execute(ctx, writer)
+ return node.thenWrapper.Execute(ctx, buffer)
+ } else {
+ if node.elseWrapper != nil {
+ return node.elseWrapper.Execute(ctx, buffer)
+ }
}
return nil
}
func tagIfEqualParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- ifequalNode := &tagIfEqualNode{}
+ ifequal_node := &tagIfEqualNode{}
// Parse two expressions
var1, err := arguments.ParseExpression()
@@ -39,8 +44,8 @@ func tagIfEqualParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *
if err != nil {
return nil, err
}
- ifequalNode.var1 = var1
- ifequalNode.var2 = var2
+ ifequal_node.var1 = var1
+ ifequal_node.var2 = var2
if arguments.Remaining() > 0 {
return nil, arguments.Error("ifequal only takes 2 arguments.", nil)
@@ -51,7 +56,7 @@ func tagIfEqualParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *
if err != nil {
return nil, err
}
- ifequalNode.thenWrapper = wrapper
+ ifequal_node.thenWrapper = wrapper
if endargs.Count() > 0 {
return nil, endargs.Error("Arguments not allowed here.", nil)
@@ -63,14 +68,14 @@ func tagIfEqualParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *
if err != nil {
return nil, err
}
- ifequalNode.elseWrapper = wrapper
+ ifequal_node.elseWrapper = wrapper
if endargs.Count() > 0 {
return nil, endargs.Error("Arguments not allowed here.", nil)
}
}
- return ifequalNode, nil
+ return ifequal_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_ifnotequal.go b/vendor/github.com/flosch/pongo2/tags_ifnotequal.go
index 0d287d3..1c1ba53 100644
--- a/vendor/github.com/flosch/pongo2/tags_ifnotequal.go
+++ b/vendor/github.com/flosch/pongo2/tags_ifnotequal.go
@@ -1,12 +1,16 @@
package pongo2
+import (
+ "bytes"
+)
+
type tagIfNotEqualNode struct {
var1, var2 IEvaluator
thenWrapper *NodeWrapper
elseWrapper *NodeWrapper
}
-func (node *tagIfNotEqualNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagIfNotEqualNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
r1, err := node.var1.Evaluate(ctx)
if err != nil {
return err
@@ -19,16 +23,17 @@ func (node *tagIfNotEqualNode) Execute(ctx *ExecutionContext, writer TemplateWri
result := !r1.EqualValueTo(r2)
if result {
- return node.thenWrapper.Execute(ctx, writer)
- }
- if node.elseWrapper != nil {
- return node.elseWrapper.Execute(ctx, writer)
+ return node.thenWrapper.Execute(ctx, buffer)
+ } else {
+ if node.elseWrapper != nil {
+ return node.elseWrapper.Execute(ctx, buffer)
+ }
}
return nil
}
func tagIfNotEqualParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- ifnotequalNode := &tagIfNotEqualNode{}
+ ifnotequal_node := &tagIfNotEqualNode{}
// Parse two expressions
var1, err := arguments.ParseExpression()
@@ -39,19 +44,19 @@ func tagIfNotEqualParser(doc *Parser, start *Token, arguments *Parser) (INodeTag
if err != nil {
return nil, err
}
- ifnotequalNode.var1 = var1
- ifnotequalNode.var2 = var2
+ ifnotequal_node.var1 = var1
+ ifnotequal_node.var2 = var2
if arguments.Remaining() > 0 {
return nil, arguments.Error("ifequal only takes 2 arguments.", nil)
}
// Wrap then/else-blocks
- wrapper, endargs, err := doc.WrapUntilTag("else", "endifnotequal")
+ wrapper, endargs, err := doc.WrapUntilTag("else", "endifequal")
if err != nil {
return nil, err
}
- ifnotequalNode.thenWrapper = wrapper
+ ifnotequal_node.thenWrapper = wrapper
if endargs.Count() > 0 {
return nil, endargs.Error("Arguments not allowed here.", nil)
@@ -59,18 +64,18 @@ func tagIfNotEqualParser(doc *Parser, start *Token, arguments *Parser) (INodeTag
if wrapper.Endtag == "else" {
// if there's an else in the if-statement, we need the else-Block as well
- wrapper, endargs, err = doc.WrapUntilTag("endifnotequal")
+ wrapper, endargs, err = doc.WrapUntilTag("endifequal")
if err != nil {
return nil, err
}
- ifnotequalNode.elseWrapper = wrapper
+ ifnotequal_node.elseWrapper = wrapper
if endargs.Count() > 0 {
return nil, endargs.Error("Arguments not allowed here.", nil)
}
}
- return ifnotequalNode, nil
+ return ifnotequal_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_import.go b/vendor/github.com/flosch/pongo2/tags_import.go
index 7e0d6a0..2abeccd 100644
--- a/vendor/github.com/flosch/pongo2/tags_import.go
+++ b/vendor/github.com/flosch/pongo2/tags_import.go
@@ -1,16 +1,18 @@
package pongo2
import (
+ "bytes"
"fmt"
)
type tagImportNode struct {
position *Token
filename string
+ template *Template
macros map[string]*tagMacroNode // alias/name -> macro instance
}
-func (node *tagImportNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagImportNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
for name, macro := range node.macros {
func(name string, macro *tagMacroNode) {
ctx.Private[name] = func(args ...*Value) *Value {
@@ -22,50 +24,50 @@ func (node *tagImportNode) Execute(ctx *ExecutionContext, writer TemplateWriter)
}
func tagImportParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- importNode := &tagImportNode{
+ import_node := &tagImportNode{
position: start,
macros: make(map[string]*tagMacroNode),
}
- filenameToken := arguments.MatchType(TokenString)
- if filenameToken == nil {
+ filename_token := arguments.MatchType(TokenString)
+ if filename_token == nil {
return nil, arguments.Error("Import-tag needs a filename as string.", nil)
}
- importNode.filename = doc.template.set.resolveFilename(doc.template, filenameToken.Val)
+ import_node.filename = doc.template.set.resolveFilename(doc.template, filename_token.Val)
if arguments.Remaining() == 0 {
return nil, arguments.Error("You must at least specify one macro to import.", nil)
}
// Compile the given template
- tpl, err := doc.template.set.FromFile(importNode.filename)
+ tpl, err := doc.template.set.FromFile(import_node.filename)
if err != nil {
return nil, err.(*Error).updateFromTokenIfNeeded(doc.template, start)
}
for arguments.Remaining() > 0 {
- macroNameToken := arguments.MatchType(TokenIdentifier)
- if macroNameToken == nil {
+ macro_name_token := arguments.MatchType(TokenIdentifier)
+ if macro_name_token == nil {
return nil, arguments.Error("Expected macro name (identifier).", nil)
}
- asName := macroNameToken.Val
+ as_name := macro_name_token.Val
if arguments.Match(TokenKeyword, "as") != nil {
- aliasToken := arguments.MatchType(TokenIdentifier)
- if aliasToken == nil {
+ alias_token := arguments.MatchType(TokenIdentifier)
+ if alias_token == nil {
return nil, arguments.Error("Expected macro alias name (identifier).", nil)
}
- asName = aliasToken.Val
+ as_name = alias_token.Val
}
- macroInstance, has := tpl.exportedMacros[macroNameToken.Val]
+ macro_instance, has := tpl.exported_macros[macro_name_token.Val]
if !has {
- return nil, arguments.Error(fmt.Sprintf("Macro '%s' not found (or not exported) in '%s'.", macroNameToken.Val,
- importNode.filename), macroNameToken)
+ return nil, arguments.Error(fmt.Sprintf("Macro '%s' not found (or not exported) in '%s'.", macro_name_token.Val,
+ import_node.filename), macro_name_token)
}
- importNode.macros[asName] = macroInstance
+ import_node.macros[as_name] = macro_instance
if arguments.Remaining() == 0 {
break
@@ -76,7 +78,7 @@ func tagImportParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *E
}
}
- return importNode, nil
+ return import_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_include.go b/vendor/github.com/flosch/pongo2/tags_include.go
index 6d619fd..7a7cce2 100644
--- a/vendor/github.com/flosch/pongo2/tags_include.go
+++ b/vendor/github.com/flosch/pongo2/tags_include.go
@@ -1,38 +1,41 @@
package pongo2
+import (
+ "bytes"
+)
+
type tagIncludeNode struct {
- tpl *Template
- filenameEvaluator IEvaluator
- lazy bool
- only bool
- filename string
- withPairs map[string]IEvaluator
- ifExists bool
+ tpl *Template
+ filename_evaluator IEvaluator
+ lazy bool
+ only bool
+ filename string
+ with_pairs map[string]IEvaluator
}
-func (node *tagIncludeNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagIncludeNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
// Building the context for the template
- includeCtx := make(Context)
+ include_ctx := make(Context)
// Fill the context with all data from the parent
if !node.only {
- includeCtx.Update(ctx.Public)
- includeCtx.Update(ctx.Private)
+ include_ctx.Update(ctx.Public)
+ include_ctx.Update(ctx.Private)
}
// Put all custom with-pairs into the context
- for key, value := range node.withPairs {
+ for key, value := range node.with_pairs {
val, err := value.Evaluate(ctx)
if err != nil {
return err
}
- includeCtx[key] = val
+ include_ctx[key] = val
}
// Execute the template
if node.lazy {
// Evaluate the filename
- filename, err := node.filenameEvaluator.Evaluate(ctx)
+ filename, err := node.filename_evaluator.Evaluate(ctx)
if err != nil {
return err
}
@@ -42,93 +45,76 @@ func (node *tagIncludeNode) Execute(ctx *ExecutionContext, writer TemplateWriter
}
// Get include-filename
- includedFilename := ctx.template.set.resolveFilename(ctx.template, filename.String())
+ included_filename := ctx.template.set.resolveFilename(ctx.template, filename.String())
- includedTpl, err2 := ctx.template.set.FromFile(includedFilename)
+ included_tpl, err2 := ctx.template.set.FromFile(included_filename)
if err2 != nil {
- // if this is ReadFile error, and "if_exists" flag is enabled
- if node.ifExists && err2.(*Error).Sender == "fromfile" {
- return nil
- }
return err2.(*Error)
}
- err2 = includedTpl.ExecuteWriter(includeCtx, writer)
+ err2 = included_tpl.ExecuteWriter(include_ctx, buffer)
if err2 != nil {
return err2.(*Error)
}
return nil
+ } else {
+ // Template is already parsed with static filename
+ err := node.tpl.ExecuteWriter(include_ctx, buffer)
+ if err != nil {
+ return err.(*Error)
+ }
+ return nil
}
- // Template is already parsed with static filename
- err := node.tpl.ExecuteWriter(includeCtx, writer)
- if err != nil {
- return err.(*Error)
- }
- return nil
-}
-
-type tagIncludeEmptyNode struct{}
-
-func (node *tagIncludeEmptyNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
- return nil
}
func tagIncludeParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- includeNode := &tagIncludeNode{
- withPairs: make(map[string]IEvaluator),
+ include_node := &tagIncludeNode{
+ with_pairs: make(map[string]IEvaluator),
}
- if filenameToken := arguments.MatchType(TokenString); filenameToken != nil {
+ if filename_token := arguments.MatchType(TokenString); filename_token != nil {
// prepared, static template
- // "if_exists" flag
- ifExists := arguments.Match(TokenIdentifier, "if_exists") != nil
-
// Get include-filename
- includedFilename := doc.template.set.resolveFilename(doc.template, filenameToken.Val)
+ included_filename := doc.template.set.resolveFilename(doc.template, filename_token.Val)
// Parse the parent
- includeNode.filename = includedFilename
- includedTpl, err := doc.template.set.FromFile(includedFilename)
+ include_node.filename = included_filename
+ included_tpl, err := doc.template.set.FromFile(included_filename)
if err != nil {
- // if this is ReadFile error, and "if_exists" token presents we should create and empty node
- if err.(*Error).Sender == "fromfile" && ifExists {
- return &tagIncludeEmptyNode{}, nil
- }
- return nil, err.(*Error).updateFromTokenIfNeeded(doc.template, filenameToken)
+ return nil, err.(*Error).updateFromTokenIfNeeded(doc.template, filename_token)
}
- includeNode.tpl = includedTpl
+ include_node.tpl = included_tpl
} else {
// No String, then the user wants to use lazy-evaluation (slower, but possible)
- filenameEvaluator, err := arguments.ParseExpression()
+ filename_evaluator, err := arguments.ParseExpression()
if err != nil {
- return nil, err.updateFromTokenIfNeeded(doc.template, filenameToken)
+ return nil, err.updateFromTokenIfNeeded(doc.template, filename_token)
}
- includeNode.filenameEvaluator = filenameEvaluator
- includeNode.lazy = true
- includeNode.ifExists = arguments.Match(TokenIdentifier, "if_exists") != nil // "if_exists" flag
+ include_node.filename_evaluator = filename_evaluator
+ include_node.lazy = true
}
// After having parsed the filename we're gonna parse the with+only options
if arguments.Match(TokenIdentifier, "with") != nil {
for arguments.Remaining() > 0 {
// We have at least one key=expr pair (because of starting "with")
- keyToken := arguments.MatchType(TokenIdentifier)
- if keyToken == nil {
+ key_token := arguments.MatchType(TokenIdentifier)
+ if key_token == nil {
return nil, arguments.Error("Expected an identifier", nil)
}
if arguments.Match(TokenSymbol, "=") == nil {
return nil, arguments.Error("Expected '='.", nil)
}
- valueExpr, err := arguments.ParseExpression()
+ value_expr, err := arguments.ParseExpression()
if err != nil {
- return nil, err.updateFromTokenIfNeeded(doc.template, keyToken)
+ return nil, err.updateFromTokenIfNeeded(doc.template, key_token)
}
- includeNode.withPairs[keyToken.Val] = valueExpr
+ include_node.with_pairs[key_token.Val] = value_expr
// Only?
if arguments.Match(TokenIdentifier, "only") != nil {
- includeNode.only = true
+ include_node.only = true
break // stop parsing arguments because it's the last option
}
}
@@ -138,7 +124,7 @@ func tagIncludeParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *
return nil, arguments.Error("Malformed 'include'-tag arguments.", nil)
}
- return includeNode, nil
+ return include_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_lorem.go b/vendor/github.com/flosch/pongo2/tags_lorem.go
index 8a152b3..16b018c 100644
--- a/vendor/github.com/flosch/pongo2/tags_lorem.go
+++ b/vendor/github.com/flosch/pongo2/tags_lorem.go
@@ -1,6 +1,7 @@
package pongo2
import (
+ "bytes"
"math/rand"
"strings"
"time"
@@ -18,64 +19,64 @@ type tagLoremNode struct {
random bool // does not use the default paragraph "Lorem ipsum dolor sit amet, ..."
}
-func (node *tagLoremNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagLoremNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
switch node.method {
case "b":
if node.random {
for i := 0; i < node.count; i++ {
if i > 0 {
- writer.WriteString("\n")
+ buffer.WriteString("\n")
}
par := tagLoremParagraphs[rand.Intn(len(tagLoremParagraphs))]
- writer.WriteString(par)
+ buffer.WriteString(par)
}
} else {
for i := 0; i < node.count; i++ {
if i > 0 {
- writer.WriteString("\n")
+ buffer.WriteString("\n")
}
par := tagLoremParagraphs[i%len(tagLoremParagraphs)]
- writer.WriteString(par)
+ buffer.WriteString(par)
}
}
case "w":
if node.random {
for i := 0; i < node.count; i++ {
if i > 0 {
- writer.WriteString(" ")
+ buffer.WriteString(" ")
}
word := tagLoremWords[rand.Intn(len(tagLoremWords))]
- writer.WriteString(word)
+ buffer.WriteString(word)
}
} else {
for i := 0; i < node.count; i++ {
if i > 0 {
- writer.WriteString(" ")
+ buffer.WriteString(" ")
}
word := tagLoremWords[i%len(tagLoremWords)]
- writer.WriteString(word)
+ buffer.WriteString(word)
}
}
case "p":
if node.random {
for i := 0; i < node.count; i++ {
if i > 0 {
- writer.WriteString("\n")
+ buffer.WriteString("\n")
}
- writer.WriteString("")
+ buffer.WriteString("
")
par := tagLoremParagraphs[rand.Intn(len(tagLoremParagraphs))]
- writer.WriteString(par)
- writer.WriteString("
")
+ buffer.WriteString(par)
+ buffer.WriteString("
")
}
} else {
for i := 0; i < node.count; i++ {
if i > 0 {
- writer.WriteString("\n")
+ buffer.WriteString("\n")
}
- writer.WriteString("")
+ buffer.WriteString("
")
par := tagLoremParagraphs[i%len(tagLoremParagraphs)]
- writer.WriteString(par)
- writer.WriteString("
")
+ buffer.WriteString(par)
+ buffer.WriteString("")
}
}
@@ -87,33 +88,33 @@ func (node *tagLoremNode) Execute(ctx *ExecutionContext, writer TemplateWriter)
}
func tagLoremParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- loremNode := &tagLoremNode{
+ lorem_node := &tagLoremNode{
position: start,
count: 1,
method: "b",
}
- if countToken := arguments.MatchType(TokenNumber); countToken != nil {
- loremNode.count = AsValue(countToken.Val).Integer()
+ if count_token := arguments.MatchType(TokenNumber); count_token != nil {
+ lorem_node.count = AsValue(count_token.Val).Integer()
}
- if methodToken := arguments.MatchType(TokenIdentifier); methodToken != nil {
- if methodToken.Val != "w" && methodToken.Val != "p" && methodToken.Val != "b" {
+ if method_token := arguments.MatchType(TokenIdentifier); method_token != nil {
+ if method_token.Val != "w" && method_token.Val != "p" && method_token.Val != "b" {
return nil, arguments.Error("lorem-method must be either 'w', 'p' or 'b'.", nil)
}
- loremNode.method = methodToken.Val
+ lorem_node.method = method_token.Val
}
if arguments.MatchOne(TokenIdentifier, "random") != nil {
- loremNode.random = true
+ lorem_node.random = true
}
if arguments.Remaining() > 0 {
return nil, arguments.Error("Malformed lorem-tag arguments.", nil)
}
- return loremNode, nil
+ return lorem_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_macro.go b/vendor/github.com/flosch/pongo2/tags_macro.go
index 18a2c3c..41cba99 100644
--- a/vendor/github.com/flosch/pongo2/tags_macro.go
+++ b/vendor/github.com/flosch/pongo2/tags_macro.go
@@ -6,16 +6,16 @@ import (
)
type tagMacroNode struct {
- position *Token
- name string
- argsOrder []string
- args map[string]IEvaluator
- exported bool
+ position *Token
+ name string
+ args_order []string
+ args map[string]IEvaluator
+ exported bool
wrapper *NodeWrapper
}
-func (node *tagMacroNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagMacroNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
ctx.Private[node.name] = func(args ...*Value) *Value {
return node.call(ctx, args...)
}
@@ -24,28 +24,28 @@ func (node *tagMacroNode) Execute(ctx *ExecutionContext, writer TemplateWriter)
}
func (node *tagMacroNode) call(ctx *ExecutionContext, args ...*Value) *Value {
- argsCtx := make(Context)
+ args_ctx := make(Context)
for k, v := range node.args {
if v == nil {
// User did not provided a default value
- argsCtx[k] = nil
+ args_ctx[k] = nil
} else {
// Evaluate the default value
- valueExpr, err := v.Evaluate(ctx)
+ value_expr, err := v.Evaluate(ctx)
if err != nil {
ctx.Logf(err.Error())
return AsSafeValue(err.Error())
}
- argsCtx[k] = valueExpr
+ args_ctx[k] = value_expr
}
}
- if len(args) > len(node.argsOrder) {
+ if len(args) > len(node.args_order) {
// Too many arguments, we're ignoring them and just logging into debug mode.
err := ctx.Error(fmt.Sprintf("Macro '%s' called with too many arguments (%d instead of %d).",
- node.name, len(args), len(node.argsOrder)), nil).updateFromTokenIfNeeded(ctx.template, node.position)
+ node.name, len(args), len(node.args_order)), nil).updateFromTokenIfNeeded(ctx.template, node.position)
ctx.Logf(err.Error()) // TODO: This is a workaround, because the error is not returned yet to the Execution()-methods
return AsSafeValue(err.Error())
@@ -55,10 +55,10 @@ func (node *tagMacroNode) call(ctx *ExecutionContext, args ...*Value) *Value {
macroCtx := NewChildExecutionContext(ctx)
// Register all arguments in the private context
- macroCtx.Private.Update(argsCtx)
+ macroCtx.Private.Update(args_ctx)
- for idx, argValue := range args {
- macroCtx.Private[node.argsOrder[idx]] = argValue.Interface()
+ for idx, arg_value := range args {
+ macroCtx.Private[node.args_order[idx]] = arg_value.Interface()
}
var b bytes.Buffer
@@ -71,38 +71,38 @@ func (node *tagMacroNode) call(ctx *ExecutionContext, args ...*Value) *Value {
}
func tagMacroParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- macroNode := &tagMacroNode{
+ macro_node := &tagMacroNode{
position: start,
args: make(map[string]IEvaluator),
}
- nameToken := arguments.MatchType(TokenIdentifier)
- if nameToken == nil {
+ name_token := arguments.MatchType(TokenIdentifier)
+ if name_token == nil {
return nil, arguments.Error("Macro-tag needs at least an identifier as name.", nil)
}
- macroNode.name = nameToken.Val
+ macro_node.name = name_token.Val
if arguments.MatchOne(TokenSymbol, "(") == nil {
return nil, arguments.Error("Expected '('.", nil)
}
for arguments.Match(TokenSymbol, ")") == nil {
- argNameToken := arguments.MatchType(TokenIdentifier)
- if argNameToken == nil {
+ arg_name_token := arguments.MatchType(TokenIdentifier)
+ if arg_name_token == nil {
return nil, arguments.Error("Expected argument name as identifier.", nil)
}
- macroNode.argsOrder = append(macroNode.argsOrder, argNameToken.Val)
+ macro_node.args_order = append(macro_node.args_order, arg_name_token.Val)
if arguments.Match(TokenSymbol, "=") != nil {
// Default expression follows
- argDefaultExpr, err := arguments.ParseExpression()
+ arg_default_expr, err := arguments.ParseExpression()
if err != nil {
return nil, err
}
- macroNode.args[argNameToken.Val] = argDefaultExpr
+ macro_node.args[arg_name_token.Val] = arg_default_expr
} else {
// No default expression
- macroNode.args[argNameToken.Val] = nil
+ macro_node.args[arg_name_token.Val] = nil
}
if arguments.Match(TokenSymbol, ")") != nil {
@@ -114,7 +114,7 @@ func tagMacroParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Er
}
if arguments.Match(TokenKeyword, "export") != nil {
- macroNode.exported = true
+ macro_node.exported = true
}
if arguments.Remaining() > 0 {
@@ -126,22 +126,22 @@ func tagMacroParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Er
if err != nil {
return nil, err
}
- macroNode.wrapper = wrapper
+ macro_node.wrapper = wrapper
if endargs.Count() > 0 {
return nil, endargs.Error("Arguments not allowed here.", nil)
}
- if macroNode.exported {
+ if macro_node.exported {
// Now register the macro if it wants to be exported
- _, has := doc.template.exportedMacros[macroNode.name]
+ _, has := doc.template.exported_macros[macro_node.name]
if has {
- return nil, doc.Error(fmt.Sprintf("Another macro with name '%s' already exported.", macroNode.name), start)
+ return nil, doc.Error(fmt.Sprintf("Another macro with name '%s' already exported.", macro_node.name), start)
}
- doc.template.exportedMacros[macroNode.name] = macroNode
+ doc.template.exported_macros[macro_node.name] = macro_node
}
- return macroNode, nil
+ return macro_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_now.go b/vendor/github.com/flosch/pongo2/tags_now.go
index d9fa4a3..0f4320f 100644
--- a/vendor/github.com/flosch/pongo2/tags_now.go
+++ b/vendor/github.com/flosch/pongo2/tags_now.go
@@ -1,6 +1,7 @@
package pongo2
import (
+ "bytes"
"time"
)
@@ -10,7 +11,7 @@ type tagNowNode struct {
fake bool
}
-func (node *tagNowNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagNowNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
var t time.Time
if node.fake {
t = time.Date(2014, time.February, 05, 18, 31, 45, 00, time.UTC)
@@ -18,31 +19,31 @@ func (node *tagNowNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *E
t = time.Now()
}
- writer.WriteString(t.Format(node.format))
+ buffer.WriteString(t.Format(node.format))
return nil
}
func tagNowParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- nowNode := &tagNowNode{
+ now_node := &tagNowNode{
position: start,
}
- formatToken := arguments.MatchType(TokenString)
- if formatToken == nil {
+ format_token := arguments.MatchType(TokenString)
+ if format_token == nil {
return nil, arguments.Error("Expected a format string.", nil)
}
- nowNode.format = formatToken.Val
+ now_node.format = format_token.Val
if arguments.MatchOne(TokenIdentifier, "fake") != nil {
- nowNode.fake = true
+ now_node.fake = true
}
if arguments.Remaining() > 0 {
return nil, arguments.Error("Malformed now-tag arguments.", nil)
}
- return nowNode, nil
+ return now_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_set.go b/vendor/github.com/flosch/pongo2/tags_set.go
index be121c1..2729f44 100644
--- a/vendor/github.com/flosch/pongo2/tags_set.go
+++ b/vendor/github.com/flosch/pongo2/tags_set.go
@@ -1,11 +1,13 @@
package pongo2
+import "bytes"
+
type tagSetNode struct {
name string
expression IEvaluator
}
-func (node *tagSetNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagSetNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
// Evaluate expression
value, err := node.expression.Evaluate(ctx)
if err != nil {
diff --git a/vendor/github.com/flosch/pongo2/tags_spaceless.go b/vendor/github.com/flosch/pongo2/tags_spaceless.go
index 4fa851b..a4b3003 100644
--- a/vendor/github.com/flosch/pongo2/tags_spaceless.go
+++ b/vendor/github.com/flosch/pongo2/tags_spaceless.go
@@ -11,7 +11,7 @@ type tagSpacelessNode struct {
var tagSpacelessRegexp = regexp.MustCompile(`(?U:(<.*>))([\t\n\v\f\r ]+)(?U:(<.*>))`)
-func (node *tagSpacelessNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagSpacelessNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
b := bytes.NewBuffer(make([]byte, 0, 1024)) // 1 KiB
err := node.wrapper.Execute(ctx, b)
@@ -28,25 +28,25 @@ func (node *tagSpacelessNode) Execute(ctx *ExecutionContext, writer TemplateWrit
s = s2
}
- writer.WriteString(s)
+ buffer.WriteString(s)
return nil
}
func tagSpacelessParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- spacelessNode := &tagSpacelessNode{}
+ spaceless_node := &tagSpacelessNode{}
wrapper, _, err := doc.WrapUntilTag("endspaceless")
if err != nil {
return nil, err
}
- spacelessNode.wrapper = wrapper
+ spaceless_node.wrapper = wrapper
if arguments.Remaining() > 0 {
return nil, arguments.Error("Malformed spaceless-tag arguments.", nil)
}
- return spacelessNode, nil
+ return spaceless_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_ssi.go b/vendor/github.com/flosch/pongo2/tags_ssi.go
index 09c2325..3c3894f 100644
--- a/vendor/github.com/flosch/pongo2/tags_ssi.go
+++ b/vendor/github.com/flosch/pongo2/tags_ssi.go
@@ -1,6 +1,7 @@
package pongo2
import (
+ "bytes"
"io/ioutil"
)
@@ -10,47 +11,47 @@ type tagSSINode struct {
template *Template
}
-func (node *tagSSINode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagSSINode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
if node.template != nil {
// Execute the template within the current context
includeCtx := make(Context)
includeCtx.Update(ctx.Public)
includeCtx.Update(ctx.Private)
- err := node.template.execute(includeCtx, writer)
+ err := node.template.ExecuteWriter(includeCtx, buffer)
if err != nil {
return err.(*Error)
}
} else {
// Just print out the content
- writer.WriteString(node.content)
+ buffer.WriteString(node.content)
}
return nil
}
func tagSSIParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- SSINode := &tagSSINode{}
+ ssi_node := &tagSSINode{}
- if fileToken := arguments.MatchType(TokenString); fileToken != nil {
- SSINode.filename = fileToken.Val
+ if file_token := arguments.MatchType(TokenString); file_token != nil {
+ ssi_node.filename = file_token.Val
if arguments.Match(TokenIdentifier, "parsed") != nil {
// parsed
- temporaryTpl, err := doc.template.set.FromFile(doc.template.set.resolveFilename(doc.template, fileToken.Val))
+ temporary_tpl, err := doc.template.set.FromFile(doc.template.set.resolveFilename(doc.template, file_token.Val))
if err != nil {
- return nil, err.(*Error).updateFromTokenIfNeeded(doc.template, fileToken)
+ return nil, err.(*Error).updateFromTokenIfNeeded(doc.template, file_token)
}
- SSINode.template = temporaryTpl
+ ssi_node.template = temporary_tpl
} else {
// plaintext
- buf, err := ioutil.ReadFile(doc.template.set.resolveFilename(doc.template, fileToken.Val))
+ buf, err := ioutil.ReadFile(doc.template.set.resolveFilename(doc.template, file_token.Val))
if err != nil {
return nil, (&Error{
Sender: "tag:ssi",
ErrorMsg: err.Error(),
- }).updateFromTokenIfNeeded(doc.template, fileToken)
+ }).updateFromTokenIfNeeded(doc.template, file_token)
}
- SSINode.content = string(buf)
+ ssi_node.content = string(buf)
}
} else {
return nil, arguments.Error("First argument must be a string.", nil)
@@ -60,7 +61,7 @@ func tagSSIParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Erro
return nil, arguments.Error("Malformed SSI-tag argument.", nil)
}
- return SSINode, nil
+ return ssi_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_templatetag.go b/vendor/github.com/flosch/pongo2/tags_templatetag.go
index 164b4dc..ffd3d9d 100644
--- a/vendor/github.com/flosch/pongo2/tags_templatetag.go
+++ b/vendor/github.com/flosch/pongo2/tags_templatetag.go
@@ -1,5 +1,9 @@
package pongo2
+import (
+ "bytes"
+)
+
type tagTemplateTagNode struct {
content string
}
@@ -15,20 +19,20 @@ var templateTagMapping = map[string]string{
"closecomment": "#}",
}
-func (node *tagTemplateTagNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
- writer.WriteString(node.content)
+func (node *tagTemplateTagNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
+ buffer.WriteString(node.content)
return nil
}
func tagTemplateTagParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- ttNode := &tagTemplateTagNode{}
+ tt_node := &tagTemplateTagNode{}
- if argToken := arguments.MatchType(TokenIdentifier); argToken != nil {
- output, found := templateTagMapping[argToken.Val]
+ if arg_token := arguments.MatchType(TokenIdentifier); arg_token != nil {
+ output, found := templateTagMapping[arg_token.Val]
if !found {
- return nil, arguments.Error("Argument not found", argToken)
+ return nil, arguments.Error("Argument not found", arg_token)
}
- ttNode.content = output
+ tt_node.content = output
} else {
return nil, arguments.Error("Identifier expected.", nil)
}
@@ -37,7 +41,7 @@ func tagTemplateTagParser(doc *Parser, start *Token, arguments *Parser) (INodeTa
return nil, arguments.Error("Malformed templatetag-tag argument.", nil)
}
- return ttNode, nil
+ return tt_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_widthratio.go b/vendor/github.com/flosch/pongo2/tags_widthratio.go
index 70c9c3e..d7d7141 100644
--- a/vendor/github.com/flosch/pongo2/tags_widthratio.go
+++ b/vendor/github.com/flosch/pongo2/tags_widthratio.go
@@ -1,6 +1,7 @@
package pongo2
import (
+ "bytes"
"fmt"
"math"
)
@@ -9,10 +10,10 @@ type tagWidthratioNode struct {
position *Token
current, max IEvaluator
width IEvaluator
- ctxName string
+ ctx_name string
}
-func (node *tagWidthratioNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagWidthratioNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
current, err := node.current.Evaluate(ctx)
if err != nil {
return err
@@ -30,17 +31,17 @@ func (node *tagWidthratioNode) Execute(ctx *ExecutionContext, writer TemplateWri
value := int(math.Ceil(current.Float()/max.Float()*width.Float() + 0.5))
- if node.ctxName == "" {
- writer.WriteString(fmt.Sprintf("%d", value))
+ if node.ctx_name == "" {
+ buffer.WriteString(fmt.Sprintf("%d", value))
} else {
- ctx.Private[node.ctxName] = value
+ ctx.Private[node.ctx_name] = value
}
return nil
}
func tagWidthratioParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- widthratioNode := &tagWidthratioNode{
+ widthratio_node := &tagWidthratioNode{
position: start,
}
@@ -48,34 +49,34 @@ func tagWidthratioParser(doc *Parser, start *Token, arguments *Parser) (INodeTag
if err != nil {
return nil, err
}
- widthratioNode.current = current
+ widthratio_node.current = current
max, err := arguments.ParseExpression()
if err != nil {
return nil, err
}
- widthratioNode.max = max
+ widthratio_node.max = max
width, err := arguments.ParseExpression()
if err != nil {
return nil, err
}
- widthratioNode.width = width
+ widthratio_node.width = width
if arguments.MatchOne(TokenKeyword, "as") != nil {
// Name follows
- nameToken := arguments.MatchType(TokenIdentifier)
- if nameToken == nil {
+ name_token := arguments.MatchType(TokenIdentifier)
+ if name_token == nil {
return nil, arguments.Error("Expected name (identifier).", nil)
}
- widthratioNode.ctxName = nameToken.Val
+ widthratio_node.ctx_name = name_token.Val
}
if arguments.Remaining() > 0 {
return nil, arguments.Error("Malformed widthratio-tag arguments.", nil)
}
- return widthratioNode, nil
+ return widthratio_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/tags_with.go b/vendor/github.com/flosch/pongo2/tags_with.go
index 32b3c1c..5bf4af0 100644
--- a/vendor/github.com/flosch/pongo2/tags_with.go
+++ b/vendor/github.com/flosch/pongo2/tags_with.go
@@ -1,16 +1,20 @@
package pongo2
+import (
+ "bytes"
+)
+
type tagWithNode struct {
- withPairs map[string]IEvaluator
- wrapper *NodeWrapper
+ with_pairs map[string]IEvaluator
+ wrapper *NodeWrapper
}
-func (node *tagWithNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (node *tagWithNode) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
//new context for block
withctx := NewChildExecutionContext(ctx)
// Put all custom with-pairs into the context
- for key, value := range node.withPairs {
+ for key, value := range node.with_pairs {
val, err := value.Evaluate(ctx)
if err != nil {
return err
@@ -18,12 +22,12 @@ func (node *tagWithNode) Execute(ctx *ExecutionContext, writer TemplateWriter) *
withctx.Private[key] = val
}
- return node.wrapper.Execute(withctx, writer)
+ return node.wrapper.Execute(withctx, buffer)
}
func tagWithParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Error) {
- withNode := &tagWithNode{
- withPairs: make(map[string]IEvaluator),
+ with_node := &tagWithNode{
+ with_pairs: make(map[string]IEvaluator),
}
if arguments.Count() == 0 {
@@ -34,7 +38,7 @@ func tagWithParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Err
if err != nil {
return nil, err
}
- withNode.wrapper = wrapper
+ with_node.wrapper = wrapper
if endargs.Count() > 0 {
return nil, endargs.Error("Arguments not allowed here.", nil)
@@ -42,45 +46,45 @@ func tagWithParser(doc *Parser, start *Token, arguments *Parser) (INodeTag, *Err
// Scan through all arguments to see which style the user uses (old or new style).
// If we find any "as" keyword we will enforce old style; otherwise we will use new style.
- oldStyle := false // by default we're using the new_style
+ old_style := false // by default we're using the new_style
for i := 0; i < arguments.Count(); i++ {
if arguments.PeekN(i, TokenKeyword, "as") != nil {
- oldStyle = true
+ old_style = true
break
}
}
for arguments.Remaining() > 0 {
- if oldStyle {
- valueExpr, err := arguments.ParseExpression()
+ if old_style {
+ value_expr, err := arguments.ParseExpression()
if err != nil {
return nil, err
}
if arguments.Match(TokenKeyword, "as") == nil {
return nil, arguments.Error("Expected 'as' keyword.", nil)
}
- keyToken := arguments.MatchType(TokenIdentifier)
- if keyToken == nil {
+ key_token := arguments.MatchType(TokenIdentifier)
+ if key_token == nil {
return nil, arguments.Error("Expected an identifier", nil)
}
- withNode.withPairs[keyToken.Val] = valueExpr
+ with_node.with_pairs[key_token.Val] = value_expr
} else {
- keyToken := arguments.MatchType(TokenIdentifier)
- if keyToken == nil {
+ key_token := arguments.MatchType(TokenIdentifier)
+ if key_token == nil {
return nil, arguments.Error("Expected an identifier", nil)
}
if arguments.Match(TokenSymbol, "=") == nil {
return nil, arguments.Error("Expected '='.", nil)
}
- valueExpr, err := arguments.ParseExpression()
+ value_expr, err := arguments.ParseExpression()
if err != nil {
return nil, err
}
- withNode.withPairs[keyToken.Val] = valueExpr
+ with_node.with_pairs[key_token.Val] = value_expr
}
}
- return withNode, nil
+ return with_node, nil
}
func init() {
diff --git a/vendor/github.com/flosch/pongo2/template.go b/vendor/github.com/flosch/pongo2/template.go
index 74bd30b..c7fe98b 100644
--- a/vendor/github.com/flosch/pongo2/template.go
+++ b/vendor/github.com/flosch/pongo2/template.go
@@ -6,67 +6,48 @@ import (
"io"
)
-type TemplateWriter interface {
- io.Writer
- WriteString(string) (int, error)
-}
-
-type templateWriter struct {
- w io.Writer
-}
-
-func (tw *templateWriter) WriteString(s string) (int, error) {
- return tw.w.Write([]byte(s))
-}
-
-func (tw *templateWriter) Write(b []byte) (int, error) {
- return tw.w.Write(b)
-}
-
type Template struct {
set *TemplateSet
// Input
- isTplString bool
- name string
- tpl string
- size int
+ is_tpl_string bool
+ name string
+ tpl string
+ size int
// Calculation
tokens []*Token
parser *Parser
// first come, first serve (it's important to not override existing entries in here)
- level int
- parent *Template
- child *Template
- blocks map[string]*NodeWrapper
- exportedMacros map[string]*tagMacroNode
+ level int
+ parent *Template
+ child *Template
+ blocks map[string]*NodeWrapper
+ exported_macros map[string]*tagMacroNode
// Output
root *nodeDocument
}
-func newTemplateString(set *TemplateSet, tpl []byte) (*Template, error) {
+func newTemplateString(set *TemplateSet, tpl string) (*Template, error) {
return newTemplate(set, "", true, tpl)
}
-func newTemplate(set *TemplateSet, name string, isTplString bool, tpl []byte) (*Template, error) {
- strTpl := string(tpl)
-
+func newTemplate(set *TemplateSet, name string, is_tpl_string bool, tpl string) (*Template, error) {
// Create the template
t := &Template{
- set: set,
- isTplString: isTplString,
- name: name,
- tpl: strTpl,
- size: len(strTpl),
- blocks: make(map[string]*NodeWrapper),
- exportedMacros: make(map[string]*tagMacroNode),
+ set: set,
+ is_tpl_string: is_tpl_string,
+ name: name,
+ tpl: tpl,
+ size: len(tpl),
+ blocks: make(map[string]*NodeWrapper),
+ exported_macros: make(map[string]*tagMacroNode),
}
// Tokenize it
- tokens, err := lex(name, strTpl)
+ tokens, err := lex(name, tpl)
if err != nil {
return nil, err
}
@@ -86,7 +67,11 @@ func newTemplate(set *TemplateSet, name string, isTplString bool, tpl []byte) (*
return t, nil
}
-func (tpl *Template) execute(context Context, writer TemplateWriter) error {
+func (tpl *Template) execute(context Context) (*bytes.Buffer, error) {
+ // Create output buffer
+ // We assume that the rendered template will be 30% larger
+ buffer := bytes.NewBuffer(make([]byte, 0, int(float64(tpl.size)*1.3)))
+
// Determine the parent to be executed (for template inheritance)
parent := tpl
for parent.parent != nil {
@@ -104,14 +89,14 @@ func (tpl *Template) execute(context Context, writer TemplateWriter) error {
// Check for context name syntax
err := newContext.checkForValidIdentifiers()
if err != nil {
- return err
+ return nil, err
}
// Check for clashes with macro names
- for k := range newContext {
- _, has := tpl.exportedMacros[k]
+ for k, _ := range newContext {
+ _, has := tpl.exported_macros[k]
if has {
- return &Error{
+ return nil, &Error{
Filename: tpl.name,
Sender: "execution",
ErrorMsg: fmt.Sprintf("Context key name '%s' clashes with macro '%s'.", k, k),
@@ -125,22 +110,8 @@ func (tpl *Template) execute(context Context, writer TemplateWriter) error {
ctx := newExecutionContext(parent, newContext)
// Run the selected document
- if err := parent.root.Execute(ctx, writer); err != nil {
- return err
- }
-
- return nil
-}
-
-func (tpl *Template) newTemplateWriterAndExecute(context Context, writer io.Writer) error {
- return tpl.execute(context, &templateWriter{w: writer})
-}
-
-func (tpl *Template) newBufferAndExecute(context Context) (*bytes.Buffer, error) {
- // Create output buffer
- // We assume that the rendered template will be 30% larger
- buffer := bytes.NewBuffer(make([]byte, 0, int(float64(tpl.size)*1.3)))
- if err := tpl.execute(context, buffer); err != nil {
+ err := parent.root.Execute(ctx, buffer)
+ if err != nil {
return nil, err
}
return buffer, nil
@@ -150,30 +121,30 @@ func (tpl *Template) newBufferAndExecute(context Context) (*bytes.Buffer, error)
// on success. Context can be nil. Nothing is written on error; instead the error
// is being returned.
func (tpl *Template) ExecuteWriter(context Context, writer io.Writer) error {
- buf, err := tpl.newBufferAndExecute(context)
+ buffer, err := tpl.execute(context)
if err != nil {
return err
}
- _, err = buf.WriteTo(writer)
- if err != nil {
- return err
+
+ l := buffer.Len()
+ n, werr := buffer.WriteTo(writer)
+ if int(n) != l {
+ panic(fmt.Sprintf("error on writing template: n(%d) != buffer.Len(%d)", n, l))
+ }
+ if werr != nil {
+ return &Error{
+ Filename: tpl.name,
+ Sender: "execution",
+ ErrorMsg: werr.Error(),
+ }
}
return nil
}
-// Same as ExecuteWriter. The only difference between both functions is that
-// this function might already have written parts of the generated template in the
-// case of an execution error because there's no intermediate buffer involved for
-// performance reasons. This is handy if you need high performance template
-// generation or if you want to manage your own pool of buffers.
-func (tpl *Template) ExecuteWriterUnbuffered(context Context, writer io.Writer) error {
- return tpl.newTemplateWriterAndExecute(context, writer)
-}
-
// Executes the template and returns the rendered template as a []byte
func (tpl *Template) ExecuteBytes(context Context) ([]byte, error) {
// Execute template
- buffer, err := tpl.newBufferAndExecute(context)
+ buffer, err := tpl.execute(context)
if err != nil {
return nil, err
}
@@ -183,7 +154,7 @@ func (tpl *Template) ExecuteBytes(context Context) ([]byte, error) {
// Executes the template and returns the rendered template as a string
func (tpl *Template) Execute(context Context) (string, error) {
// Execute template
- buffer, err := tpl.newBufferAndExecute(context)
+ buffer, err := tpl.execute(context)
if err != nil {
return "", err
}
diff --git a/vendor/github.com/flosch/pongo2/template_loader.go b/vendor/github.com/flosch/pongo2/template_loader.go
deleted file mode 100644
index abd2340..0000000
--- a/vendor/github.com/flosch/pongo2/template_loader.go
+++ /dev/null
@@ -1,156 +0,0 @@
-package pongo2
-
-import (
- "bytes"
- "fmt"
- "io"
- "io/ioutil"
- "log"
- "os"
- "path/filepath"
-)
-
-// LocalFilesystemLoader represents a local filesystem loader with basic
-// BaseDirectory capabilities. The access to the local filesystem is unrestricted.
-type LocalFilesystemLoader struct {
- baseDir string
-}
-
-// MustNewLocalFileSystemLoader creates a new LocalFilesystemLoader instance
-// and panics if there's any error during instantiation. The parameters
-// are the same like NewLocalFileSystemLoader.
-func MustNewLocalFileSystemLoader(baseDir string) *LocalFilesystemLoader {
- fs, err := NewLocalFileSystemLoader(baseDir)
- if err != nil {
- log.Panic(err)
- }
- return fs
-}
-
-// NewLocalFileSystemLoader creates a new LocalFilesystemLoader and allows
-// templatesto be loaded from disk (unrestricted). If any base directory
-// is given (or being set using SetBaseDir), this base directory is being used
-// for path calculation in template inclusions/imports. Otherwise the path
-// is calculated based relatively to the including template's path.
-func NewLocalFileSystemLoader(baseDir string) (*LocalFilesystemLoader, error) {
- fs := &LocalFilesystemLoader{}
- if baseDir != "" {
- if err := fs.SetBaseDir(baseDir); err != nil {
- return nil, err
- }
- }
- return fs, nil
-}
-
-// SetBaseDir sets the template's base directory. This directory will
-// be used for any relative path in filters, tags and From*-functions to determine
-// your template. See the comment for NewLocalFileSystemLoader as well.
-func (fs *LocalFilesystemLoader) SetBaseDir(path string) error {
- // Make the path absolute
- if !filepath.IsAbs(path) {
- abs, err := filepath.Abs(path)
- if err != nil {
- return err
- }
- path = abs
- }
-
- // Check for existence
- fi, err := os.Stat(path)
- if err != nil {
- return err
- }
- if !fi.IsDir() {
- return fmt.Errorf("The given path '%s' is not a directory.", path)
- }
-
- fs.baseDir = path
- return nil
-}
-
-// Get reads the path's content from your local filesystem.
-func (fs *LocalFilesystemLoader) Get(path string) (io.Reader, error) {
- buf, err := ioutil.ReadFile(path)
- if err != nil {
- return nil, err
- }
- return bytes.NewReader(buf), nil
-}
-
-// Abs resolves a filename relative to the base directory. Absolute paths are allowed.
-// When there's no base dir set, the absolute path to the filename
-// will be calculated based on either the provided base directory (which
-// might be a path of a template which includes another template) or
-// the current working directory.
-func (fs *LocalFilesystemLoader) Abs(base, name string) string {
- if filepath.IsAbs(name) {
- return name
- }
-
- // Our own base dir has always priority; if there's none
- // we use the path provided in base.
- var err error
- if fs.baseDir == "" {
- if base == "" {
- base, err = os.Getwd()
- if err != nil {
- panic(err)
- }
- return filepath.Join(base, name)
- }
-
- return filepath.Join(filepath.Dir(base), name)
- }
-
- return filepath.Join(fs.baseDir, name)
-}
-
-// SandboxedFilesystemLoader is still WIP.
-type SandboxedFilesystemLoader struct {
- *LocalFilesystemLoader
-}
-
-// NewSandboxedFilesystemLoader creates a new sandboxed local file system instance.
-func NewSandboxedFilesystemLoader(baseDir string) (*SandboxedFilesystemLoader, error) {
- fs, err := NewLocalFileSystemLoader(baseDir)
- if err != nil {
- return nil, err
- }
- return &SandboxedFilesystemLoader{
- LocalFilesystemLoader: fs,
- }, nil
-}
-
-// Move sandbox to a virtual fs
-
-/*
-if len(set.SandboxDirectories) > 0 {
- defer func() {
- // Remove any ".." or other crap
- resolvedPath = filepath.Clean(resolvedPath)
-
- // Make the path absolute
- absPath, err := filepath.Abs(resolvedPath)
- if err != nil {
- panic(err)
- }
- resolvedPath = absPath
-
- // Check against the sandbox directories (once one pattern matches, we're done and can allow it)
- for _, pattern := range set.SandboxDirectories {
- matched, err := filepath.Match(pattern, resolvedPath)
- if err != nil {
- panic("Wrong sandbox directory match pattern (see http://golang.org/pkg/path/filepath/#Match).")
- }
- if matched {
- // OK!
- return
- }
- }
-
- // No pattern matched, we have to log+deny the request
- set.logf("Access attempt outside of the sandbox directories (blocked): '%s'", resolvedPath)
- resolvedPath = ""
- }()
-}
-*/
diff --git a/vendor/github.com/flosch/pongo2/template_sets.go b/vendor/github.com/flosch/pongo2/template_sets.go
index bcd8a63..c582c5d 100644
--- a/vendor/github.com/flosch/pongo2/template_sets.go
+++ b/vendor/github.com/flosch/pongo2/template_sets.go
@@ -1,49 +1,49 @@
package pongo2
import (
- "errors"
"fmt"
- "io"
"io/ioutil"
"log"
"os"
+ "path/filepath"
"sync"
)
-// TemplateLoader allows to implement a virtual file system.
-type TemplateLoader interface {
- // Abs calculates the path to a given template. Whenever a path must be resolved
- // due to an import from another template, the base equals the parent template's path.
- Abs(base, name string) string
-
- // Get returns an io.Reader where the template's content can be read from.
- Get(path string) (io.Reader, error)
-}
-
-// TemplateSet allows you to create your own group of templates with their own
-// global context (which is shared among all members of the set) and their own
-// configuration.
-// It's useful for a separation of different kind of templates
-// (e. g. web templates vs. mail templates).
+// A template set allows you to create your own group of templates with their own global context (which is shared
+// among all members of the set), their own configuration (like a specific base directory) and their own sandbox.
+// It's useful for a separation of different kind of templates (e. g. web templates vs. mail templates).
type TemplateSet struct {
- name string
- loader TemplateLoader
+ name string
// Globals will be provided to all templates created within this template set
Globals Context
- // If debug is true (default false), ExecutionContext.Logf() will work and output
- // to STDOUT. Furthermore, FromCache() won't cache the templates.
- // Make sure to synchronize the access to it in case you're changing this
+ // If debug is true (default false), ExecutionContext.Logf() will work and output to STDOUT. Furthermore,
+ // FromCache() won't cache the templates. Make sure to synchronize the access to it in case you're changing this
// variable during program execution (and template compilation/execution).
Debug bool
+ // Base directory: If you set the base directory (string is non-empty), all filename lookups in tags/filters are
+ // relative to this directory. If it's empty, all lookups are relative to the current filename which is importing.
+ baseDirectory string
+
// Sandbox features
+ // - Limit access to directories (using SandboxDirectories)
// - Disallow access to specific tags and/or filters (using BanTag() and BanFilter())
//
- // For efficiency reasons you can ban tags/filters only *before* you have
- // added your first template to the set (restrictions are statically checked).
- // After you added one, it's not possible anymore (for your personal security).
+ // You can limit file accesses (for all tags/filters which are using pongo2's file resolver technique)
+ // to these sandbox directories. All default pongo2 filters/tags are respecting these restrictions.
+ // For example, if you only have your base directory in the list, a {% ssi "/etc/passwd" %} will not work.
+ // No items in SandboxDirectories means no restrictions at all.
+ //
+ // For efficiency reasons you can ban tags/filters only *before* you have added your first
+ // template to the set (restrictions are statically checked). After you added one, it's not possible anymore
+ // (for your personal security).
+ //
+ // SandboxDirectories can be changed at runtime. Please synchronize the access to it if you need to change it
+ // after you've added your first template to the set. You *must* use this match pattern for your directories:
+ // http://golang.org/pkg/path/filepath/#Match
+ SandboxDirectories []string
firstTemplateCreated bool
bannedTags map[string]bool
bannedFilters map[string]bool
@@ -53,13 +53,11 @@ type TemplateSet struct {
templateCacheMutex sync.Mutex
}
-// NewSet can be used to create sets with different kind of templates
-// (e. g. web from mail templates), with different globals or
-// other configurations.
-func NewSet(name string, loader TemplateLoader) *TemplateSet {
+// Create your own template sets to separate different kind of templates (e. g. web from mail templates) with
+// different globals or other configurations (like base directories).
+func NewSet(name string) *TemplateSet {
return &TemplateSet{
name: name,
- loader: loader,
Globals: make(Context),
bannedTags: make(map[string]bool),
bannedFilters: make(map[string]bool),
@@ -67,97 +65,117 @@ func NewSet(name string, loader TemplateLoader) *TemplateSet {
}
}
-func (set *TemplateSet) resolveFilename(tpl *Template, path string) string {
- name := ""
- if tpl != nil && tpl.isTplString {
- return path
+// Use this function to set your template set's base directory. This directory will be used for any relative
+// path in filters, tags and From*-functions to determine your template.
+func (set *TemplateSet) SetBaseDirectory(name string) error {
+ // Make the path absolute
+ if !filepath.IsAbs(name) {
+ abs, err := filepath.Abs(name)
+ if err != nil {
+ return err
+ }
+ name = abs
}
- if tpl != nil {
- name = tpl.name
+
+ // Check for existence
+ fi, err := os.Stat(name)
+ if err != nil {
+ return err
}
- return set.loader.Abs(name, path)
+ if !fi.IsDir() {
+ return fmt.Errorf("The given path '%s' is not a directory.")
+ }
+
+ set.baseDirectory = name
+ return nil
}
-// BanTag bans a specific tag for this template set. See more in the documentation for TemplateSet.
-func (set *TemplateSet) BanTag(name string) error {
+func (set *TemplateSet) BaseDirectory() string {
+ return set.baseDirectory
+}
+
+// Ban a specific tag for this template set. See more in the documentation for TemplateSet.
+func (set *TemplateSet) BanTag(name string) {
_, has := tags[name]
if !has {
- return fmt.Errorf("Tag '%s' not found.", name)
+ panic(fmt.Sprintf("Tag '%s' not found.", name))
}
if set.firstTemplateCreated {
- return errors.New("You cannot ban any tags after you've added your first template to your template set.")
+ panic("You cannot ban any tags after you've added your first template to your template set.")
}
_, has = set.bannedTags[name]
if has {
- return fmt.Errorf("Tag '%s' is already banned.", name)
+ panic(fmt.Sprintf("Tag '%s' is already banned.", name))
}
set.bannedTags[name] = true
-
- return nil
}
-// BanFilter bans a specific filter for this template set. See more in the documentation for TemplateSet.
-func (set *TemplateSet) BanFilter(name string) error {
+// Ban a specific filter for this template set. See more in the documentation for TemplateSet.
+func (set *TemplateSet) BanFilter(name string) {
_, has := filters[name]
if !has {
- return fmt.Errorf("Filter '%s' not found.", name)
+ panic(fmt.Sprintf("Filter '%s' not found.", name))
}
if set.firstTemplateCreated {
- return errors.New("You cannot ban any filters after you've added your first template to your template set.")
+ panic("You cannot ban any filters after you've added your first template to your template set.")
}
_, has = set.bannedFilters[name]
if has {
- return fmt.Errorf("Filter '%s' is already banned.", name)
+ panic(fmt.Sprintf("Filter '%s' is already banned.", name))
}
set.bannedFilters[name] = true
-
- return nil
}
-// FromCache is a convenient method to cache templates. It is thread-safe
+// FromCache() is a convenient method to cache templates. It is thread-safe
// and will only compile the template associated with a filename once.
// If TemplateSet.Debug is true (for example during development phase),
// FromCache() will not cache the template and instead recompile it on any
// call (to make changes to a template live instantaneously).
+// Like FromFile(), FromCache() takes a relative path to a set base directory.
+// Sandbox restrictions apply (if given).
func (set *TemplateSet) FromCache(filename string) (*Template, error) {
if set.Debug {
// Recompile on any request
return set.FromFile(filename)
- }
- // Cache the template
- cleanedFilename := set.resolveFilename(nil, filename)
+ } else {
+ // Cache the template
+ cleaned_filename := set.resolveFilename(nil, filename)
- set.templateCacheMutex.Lock()
- defer set.templateCacheMutex.Unlock()
+ set.templateCacheMutex.Lock()
+ defer set.templateCacheMutex.Unlock()
- tpl, has := set.templateCache[cleanedFilename]
+ tpl, has := set.templateCache[cleaned_filename]
- // Cache miss
- if !has {
- tpl, err := set.FromFile(cleanedFilename)
- if err != nil {
- return nil, err
+ // Cache miss
+ if !has {
+ tpl, err := set.FromFile(cleaned_filename)
+ if err != nil {
+ return nil, err
+ }
+ set.templateCache[cleaned_filename] = tpl
+ return tpl, nil
}
- set.templateCache[cleanedFilename] = tpl
+
+ // Cache hit
return tpl, nil
}
-
- // Cache hit
- return tpl, nil
}
-// FromString loads a template from string and returns a Template instance.
+// Loads a template from string and returns a Template instance.
func (set *TemplateSet) FromString(tpl string) (*Template, error) {
set.firstTemplateCreated = true
- return newTemplateString(set, []byte(tpl))
+ return newTemplateString(set, tpl)
}
-// FromFile loads a template from a filename and returns a Template instance.
+// Loads a template from a filename and returns a Template instance.
+// If a base directory is set, the filename must be either relative to it
+// or be an absolute path. Sandbox restrictions (SandboxDirectories) apply
+// if given.
func (set *TemplateSet) FromFile(filename string) (*Template, error) {
set.firstTemplateCreated = true
- fd, err := set.loader.Get(set.resolveFilename(nil, filename))
+ buf, err := ioutil.ReadFile(set.resolveFilename(nil, filename))
if err != nil {
return nil, &Error{
Filename: filename,
@@ -165,20 +183,11 @@ func (set *TemplateSet) FromFile(filename string) (*Template, error) {
ErrorMsg: err.Error(),
}
}
- buf, err := ioutil.ReadAll(fd)
- if err != nil {
- return nil, &Error{
- Filename: filename,
- Sender: "fromfile",
- ErrorMsg: err.Error(),
- }
- }
-
- return newTemplate(set, filename, false, buf)
+ return newTemplate(set, filename, false, string(buf))
}
-// RenderTemplateString is a shortcut and renders a template string directly.
-// Panics when providing a malformed template or an error occurs during execution.
+// Shortcut; renders a template string directly. Panics when providing a
+// malformed template or an error occurs during execution.
func (set *TemplateSet) RenderTemplateString(s string, ctx Context) string {
set.firstTemplateCreated = true
@@ -190,8 +199,8 @@ func (set *TemplateSet) RenderTemplateString(s string, ctx Context) string {
return result
}
-// RenderTemplateFile is a shortcut and renders a template file directly.
-// Panics when providing a malformed template or an error occurs during execution.
+// Shortcut; renders a template file directly. Panics when providing a
+// malformed template or an error occurs during execution.
func (set *TemplateSet) RenderTemplateFile(fn string, ctx Context) string {
set.firstTemplateCreated = true
@@ -209,6 +218,58 @@ func (set *TemplateSet) logf(format string, args ...interface{}) {
}
}
+// Resolves a filename relative to the base directory. Absolute paths are allowed.
+// If sandbox restrictions are given (SandboxDirectories), they will be respected and checked.
+// On sandbox restriction violation, resolveFilename() panics.
+func (set *TemplateSet) resolveFilename(tpl *Template, filename string) (resolved_path string) {
+ if len(set.SandboxDirectories) > 0 {
+ defer func() {
+ // Remove any ".." or other crap
+ resolved_path = filepath.Clean(resolved_path)
+
+ // Make the path absolute
+ abs_path, err := filepath.Abs(resolved_path)
+ if err != nil {
+ panic(err)
+ }
+ resolved_path = abs_path
+
+ // Check against the sandbox directories (once one pattern matches, we're done and can allow it)
+ for _, pattern := range set.SandboxDirectories {
+ matched, err := filepath.Match(pattern, resolved_path)
+ if err != nil {
+ panic("Wrong sandbox directory match pattern (see http://golang.org/pkg/path/filepath/#Match).")
+ }
+ if matched {
+ // OK!
+ return
+ }
+ }
+
+ // No pattern matched, we have to log+deny the request
+ set.logf("Access attempt outside of the sandbox directories (blocked): '%s'", resolved_path)
+ resolved_path = ""
+ }()
+ }
+
+ if filepath.IsAbs(filename) {
+ return filename
+ }
+
+ if set.baseDirectory == "" {
+ if tpl != nil {
+ if tpl.is_tpl_string {
+ return filename
+ }
+ base := filepath.Dir(tpl.name)
+ return filepath.Join(base, filename)
+ }
+ return filename
+ } else {
+ return filepath.Join(set.baseDirectory, filename)
+ }
+}
+
// Logging function (internally used)
func logf(format string, items ...interface{}) {
if debug {
@@ -218,14 +279,10 @@ func logf(format string, items ...interface{}) {
var (
debug bool // internal debugging
- logger = log.New(os.Stdout, "[pongo2] ", log.LstdFlags|log.Lshortfile)
+ logger = log.New(os.Stdout, "[pongo2] ", log.LstdFlags)
- // DefaultLoader allows the default un-sandboxed access to the local file
- // system and is being used by the DefaultSet.
- DefaultLoader = MustNewLocalFileSystemLoader("")
-
- // DefaultSet is a set created for you for convinience reasons.
- DefaultSet = NewSet("default", DefaultLoader)
+ // Creating a default set
+ DefaultSet = NewSet("default")
// Methods on the default set
FromString = DefaultSet.FromString
diff --git a/vendor/github.com/flosch/pongo2/template_tests/expressions.tpl b/vendor/github.com/flosch/pongo2/template_tests/expressions.tpl
index caada14..40a158a 100644
--- a/vendor/github.com/flosch/pongo2/template_tests/expressions.tpl
+++ b/vendor/github.com/flosch/pongo2/template_tests/expressions.tpl
@@ -46,24 +46,8 @@ in/not in
{{ 7 in simple.intmap }}
{{ !(5 in simple.intmap) }}
{{ not(7 in simple.intmap) }}
-{{ 1 in simple.multiple_item_list }}
-{{ 4 in simple.multiple_item_list }}
-{{ !(4 in simple.multiple_item_list) }}
-{{ "Hello" in simple.misc_list }}
-{{ "Hello2" in simple.misc_list }}
-{{ 99 in simple.misc_list }}
-{{ False in simple.misc_list }}
issue #48 (associativity for infix operators)
{{ 34/3*3 }}
{{ 10 + 24 / 6 / 2 }}
-{{ 6 - 4 - 2 }}
-
-issue #64 (uint comparison with int const)
-{{ simple.uint }}
-{{ simple.uint == 8 }}
-{{ simple.uint == 9 }}
-{{ simple.uint >= 8 }}
-{{ simple.uint <= 8 }}
-{{ simple.uint < 8 }}
-{{ simple.uint > 8 }}
\ No newline at end of file
+{{ 6 - 4 - 2 }}
\ No newline at end of file
diff --git a/vendor/github.com/flosch/pongo2/template_tests/expressions.tpl.out b/vendor/github.com/flosch/pongo2/template_tests/expressions.tpl.out
index d710fc8..be51073 100644
--- a/vendor/github.com/flosch/pongo2/template_tests/expressions.tpl.out
+++ b/vendor/github.com/flosch/pongo2/template_tests/expressions.tpl.out
@@ -46,24 +46,8 @@ True
False
False
True
-True
-False
-True
-True
-False
-True
-False
issue #48 (associativity for infix operators)
33
12
-0
-
-issue #64 (uint comparison with int const)
-8
-True
-False
-True
-True
-False
-False
\ No newline at end of file
+0
\ No newline at end of file
diff --git a/vendor/github.com/flosch/pongo2/template_tests/filters-execution.err b/vendor/github.com/flosch/pongo2/template_tests/filters-execution.err
index 1fc53f2..da761b2 100644
--- a/vendor/github.com/flosch/pongo2/template_tests/filters-execution.err
+++ b/vendor/github.com/flosch/pongo2/template_tests/filters-execution.err
@@ -1,4 +1,3 @@
{{ -(true || false) }}
{{ simple.func_add("test", 5) }}
-{% for item in simple.multiple_item_list %} {{ simple.func_add("test", 5) }} {% endfor %}
-{{ simple.func_variadic_sum_int("foo") }}
+{{ simple.func_variadic_sum_int("foo") }}
\ No newline at end of file
diff --git a/vendor/github.com/flosch/pongo2/template_tests/filters-execution.err.out b/vendor/github.com/flosch/pongo2/template_tests/filters-execution.err.out
index a960607..e83ae01 100644
--- a/vendor/github.com/flosch/pongo2/template_tests/filters-execution.err.out
+++ b/vendor/github.com/flosch/pongo2/template_tests/filters-execution.err.out
@@ -1,4 +1,3 @@
.*where: execution.*Negative sign on a non\-number expression
.*Function input argument 0 of 'simple.func_add' must be of type int or \*pongo2.Value \(not string\).
-.*Function input argument 0 of 'simple.func_add' must be of type int or \*pongo2.Value \(not string\).
-.*Function variadic input argument of 'simple.func_variadic_sum_int' must be of type int or \*pongo2.Value \(not string\).
+.*Function variadic input argument of 'simple.func_variadic_sum_int' must be of type int or \*pongo2.Value \(not string\).
\ No newline at end of file
diff --git a/vendor/github.com/flosch/pongo2/template_tests/filters.tpl.out b/vendor/github.com/flosch/pongo2/template_tests/filters.tpl.out
index f7fc97d..1044857 100644
--- a/vendor/github.com/flosch/pongo2/template_tests/filters.tpl.out
+++ b/vendor/github.com/flosch/pongo2/template_tests/filters.tpl.out
@@ -105,7 +105,7 @@ h
first
T
-
+
@@ -113,7 +113,7 @@ T
last
t
-
+
diff --git a/vendor/github.com/flosch/pongo2/template_tests/for.tpl b/vendor/github.com/flosch/pongo2/template_tests/for.tpl
index d14e632..51e144c 100644
--- a/vendor/github.com/flosch/pongo2/template_tests/for.tpl
+++ b/vendor/github.com/flosch/pongo2/template_tests/for.tpl
@@ -6,22 +6,4 @@
{% endfor %}
reversed
-'{% for item in simple.multiple_item_list reversed %}{{ item }} {% endfor %}'
-
-sorted string map
-'{% for key in simple.strmap sorted %}{{ key }} {% endfor %}'
-
-sorted int map
-'{% for key in simple.intmap sorted %}{{ key }} {% endfor %}'
-
-sorted int list
-'{% for key in simple.unsorted_int_list sorted %}{{ key }} {% endfor %}'
-
-reversed sorted int list
-'{% for key in simple.unsorted_int_list reversed sorted %}{{ key }} {% endfor %}'
-
-reversed sorted string map
-'{% for key in simple.strmap reversed sorted %}{{ key }} {% endfor %}'
-
-reversed sorted int map
-'{% for key in simple.intmap reversed sorted %}{{ key }} {% endfor %}'
+'{% for item in simple.multiple_item_list reversed %}{{ item }} {% endfor %}'
\ No newline at end of file
diff --git a/vendor/github.com/flosch/pongo2/template_tests/for.tpl.out b/vendor/github.com/flosch/pongo2/template_tests/for.tpl.out
index 27c7120..18258a2 100644
--- a/vendor/github.com/flosch/pongo2/template_tests/for.tpl.out
+++ b/vendor/github.com/flosch/pongo2/template_tests/for.tpl.out
@@ -16,22 +16,4 @@
reversed
-'55 34 21 13 8 5 3 2 1 1 '
-
-sorted string map
-'aab abc bcd gh ukq zab '
-
-sorted int map
-'1 2 5 '
-
-sorted int list
-'1 22 192 249 581 8271 9999 1828591 '
-
-reversed sorted int list
-'1828591 9999 8271 581 249 192 22 1 '
-
-reversed sorted string map
-'zab ukq gh bcd abc aab '
-
-reversed sorted int map
-'5 2 1 '
+'55 34 21 13 8 5 3 2 1 1 '
\ No newline at end of file
diff --git a/vendor/github.com/flosch/pongo2/template_tests/includes.tpl b/vendor/github.com/flosch/pongo2/template_tests/includes.tpl
index 2394ee9..f2b0253 100644
--- a/vendor/github.com/flosch/pongo2/template_tests/includes.tpl
+++ b/vendor/github.com/flosch/pongo2/template_tests/includes.tpl
@@ -1,7 +1,4 @@
Start '{% include "includes.helper" %}' End
-Start '{% include "includes.helper" if_exists %}' End
Start '{% include "includes.helper" with what_am_i=simple.name only %}' End
Start '{% include "includes.helper" with what_am_i=simple.name %}' End
-Start '{% include simple.included_file|lower with number=7 what_am_i="guest" %}' End
-Start '{% include "includes.helper.not_exists" if_exists %}' End
-Start '{% include simple.included_file_not_exists if_exists with number=7 what_am_i="guest" %}' End
\ No newline at end of file
+Start '{% include simple.included_file|lower with number=7 what_am_i="guest" %}' End
\ No newline at end of file
diff --git a/vendor/github.com/flosch/pongo2/template_tests/includes.tpl.out b/vendor/github.com/flosch/pongo2/template_tests/includes.tpl.out
index 61d9318..90f7726 100644
--- a/vendor/github.com/flosch/pongo2/template_tests/includes.tpl.out
+++ b/vendor/github.com/flosch/pongo2/template_tests/includes.tpl.out
@@ -1,7 +1,4 @@
Start 'I'm 11' End
-Start 'I'm 11' End
Start 'I'm john doe' End
Start 'I'm john doe11' End
-Start 'I'm guest7' End
-Start '' End
-Start '' End
\ No newline at end of file
+Start 'I'm guest7' End
\ No newline at end of file
diff --git a/vendor/github.com/flosch/pongo2/template_tests/pongo2ctx.tpl.out b/vendor/github.com/flosch/pongo2/template_tests/pongo2ctx.tpl.out
index 9001211..04d0d54 100644
--- a/vendor/github.com/flosch/pongo2/template_tests/pongo2ctx.tpl.out
+++ b/vendor/github.com/flosch/pongo2/template_tests/pongo2ctx.tpl.out
@@ -1 +1 @@
-dev
\ No newline at end of file
+v3
\ No newline at end of file
diff --git a/vendor/github.com/flosch/pongo2/template_tests/with.tpl.out b/vendor/github.com/flosch/pongo2/template_tests/with.tpl.out
index 46686bd..41e3829 100644
--- a/vendor/github.com/flosch/pongo2/template_tests/with.tpl.out
+++ b/vendor/github.com/flosch/pongo2/template_tests/with.tpl.out
@@ -11,6 +11,6 @@ Start 'I'm guest7' End
Start 'Hi number 10! Will not be overridden inside the block. I'm john doe, 50 years old.I have 10 children.' End
more with tests
-
+
user1
user3
\ No newline at end of file
diff --git a/vendor/github.com/flosch/pongo2/value.go b/vendor/github.com/flosch/pongo2/value.go
index b1d4f7b..8cf8552 100644
--- a/vendor/github.com/flosch/pongo2/value.go
+++ b/vendor/github.com/flosch/pongo2/value.go
@@ -3,7 +3,6 @@ package pongo2
import (
"fmt"
"reflect"
- "sort"
"strconv"
"strings"
)
@@ -13,7 +12,7 @@ type Value struct {
safe bool // used to indicate whether a Value needs explicit escaping in the template
}
-// AsValue converts any given value to a pongo2.Value
+// Converts any given value to a pongo2.Value
// Usually being used within own functions passed to a template
// through a Context or within filter functions.
//
@@ -25,7 +24,7 @@ func AsValue(i interface{}) *Value {
}
}
-// AsSafeValue works like AsValue, but does not apply the 'escape' filter.
+// Like AsValue, but does not apply the 'escape' filter.
func AsSafeValue(i interface{}) *Value {
return &Value{
val: reflect.ValueOf(i),
@@ -112,8 +111,9 @@ func (v *Value) String() string {
case reflect.Bool:
if v.Bool() {
return "True"
+ } else {
+ return "False"
}
- return "False"
case reflect.Struct:
if t, ok := v.Interface().(fmt.Stringer); ok {
return t.String()
@@ -229,13 +229,15 @@ func (v *Value) Negate() *Value {
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if v.Integer() != 0 {
return AsValue(0)
+ } else {
+ return AsValue(1)
}
- return AsValue(1)
case reflect.Float32, reflect.Float64:
if v.Float() != 0.0 {
return AsValue(float64(0.0))
+ } else {
+ return AsValue(float64(1.1))
}
- return AsValue(float64(1.1))
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
return AsValue(v.getResolvedValue().Len() == 0)
case reflect.Bool:
@@ -299,7 +301,7 @@ func (v *Value) Index(i int) *Value {
}
}
-// Contains checks whether the underlying value (which must be of type struct, map,
+// Checks whether the underlying value (which must be of type struct, map,
// string, array or slice) contains of another Value (e. g. used to check
// whether a struct contains of a specific field or a map contains a specific key).
//
@@ -308,32 +310,25 @@ func (v *Value) Index(i int) *Value {
func (v *Value) Contains(other *Value) bool {
switch v.getResolvedValue().Kind() {
case reflect.Struct:
- fieldValue := v.getResolvedValue().FieldByName(other.String())
- return fieldValue.IsValid()
+ field_value := v.getResolvedValue().FieldByName(other.String())
+ return field_value.IsValid()
case reflect.Map:
- var mapValue reflect.Value
+ var map_value reflect.Value
switch other.Interface().(type) {
case int:
- mapValue = v.getResolvedValue().MapIndex(other.getResolvedValue())
+ map_value = v.getResolvedValue().MapIndex(other.getResolvedValue())
case string:
- mapValue = v.getResolvedValue().MapIndex(other.getResolvedValue())
+ map_value = v.getResolvedValue().MapIndex(other.getResolvedValue())
default:
logf("Value.Contains() does not support lookup type '%s'\n", other.getResolvedValue().Kind().String())
return false
}
- return mapValue.IsValid()
+ return map_value.IsValid()
case reflect.String:
return strings.Contains(v.getResolvedValue().String(), other.String())
- case reflect.Slice, reflect.Array:
- for i := 0; i < v.getResolvedValue().Len(); i++ {
- item := v.getResolvedValue().Index(i)
- if other.Interface() == item.Interface() {
- return true
- }
- }
- return false
+ // TODO: reflect.Array, reflect.Slice
default:
logf("Value.Contains() not available for type: %s\n", v.getResolvedValue().Kind().String())
@@ -362,22 +357,16 @@ func (v *Value) CanSlice() bool {
// If the underlying value has no items or is not one of the types above,
// the empty function (function's second argument) will be called.
func (v *Value) Iterate(fn func(idx, count int, key, value *Value) bool, empty func()) {
- v.IterateOrder(fn, empty, false, false)
+ v.IterateOrder(fn, empty, false)
}
// Like Value.Iterate, but can iterate through an array/slice/string in reverse. Does
// not affect the iteration through a map because maps don't have any particular order.
-func (v *Value) IterateOrder(fn func(idx, count int, key, value *Value) bool, empty func(), reverse bool, sorted bool) {
+func (v *Value) IterateOrder(fn func(idx, count int, key, value *Value) bool, empty func(), reverse bool) {
switch v.getResolvedValue().Kind() {
case reflect.Map:
- keys := sortedKeys(v.getResolvedValue().MapKeys())
- if sorted {
- if reverse {
- sort.Sort(sort.Reverse(keys))
- } else {
- sort.Sort(keys)
- }
- }
+ // Reverse not needed for maps, since they are not ordered
+ keys := v.getResolvedValue().MapKeys()
keyLen := len(keys)
for idx, key := range keys {
value := v.getResolvedValue().MapIndex(key)
@@ -390,31 +379,19 @@ func (v *Value) IterateOrder(fn func(idx, count int, key, value *Value) bool, em
}
return // done
case reflect.Array, reflect.Slice:
- var items valuesList
-
itemCount := v.getResolvedValue().Len()
- for i := 0; i < itemCount; i++ {
- items = append(items, &Value{val: v.getResolvedValue().Index(i)})
- }
-
- if sorted {
+ if itemCount > 0 {
if reverse {
- sort.Sort(sort.Reverse(items))
- } else {
- sort.Sort(items)
- }
- } else {
- if reverse {
- for i := 0; i < itemCount/2; i++ {
- items[i], items[itemCount-1-i] = items[itemCount-1-i], items[i]
+ for i := itemCount - 1; i >= 0; i-- {
+ if !fn(i, itemCount, &Value{val: v.getResolvedValue().Index(i)}, nil) {
+ return
+ }
}
- }
- }
-
- if len(items) > 0 {
- for idx, item := range items {
- if !fn(idx, itemCount, item, nil) {
- return
+ } else {
+ for i := 0; i < itemCount; i++ {
+ if !fn(i, itemCount, &Value{val: v.getResolvedValue().Index(i)}, nil) {
+ return
+ }
}
}
} else {
@@ -422,12 +399,7 @@ func (v *Value) IterateOrder(fn func(idx, count int, key, value *Value) bool, em
}
return // done
case reflect.String:
- if sorted {
- // TODO(flosch): Handle sorted
- panic("TODO: handle sort for type string")
- }
-
- // TODO(flosch): Not utf8-compatible (utf8-decoding neccessary)
+ // TODO: Not utf8-compatible (utf8-decoding neccessary)
charCount := v.getResolvedValue().Len()
if charCount > 0 {
if reverse {
@@ -463,55 +435,5 @@ func (v *Value) Interface() interface{} {
// Checks whether two values are containing the same value or object.
func (v *Value) EqualValueTo(other *Value) bool {
- // comparison of uint with int fails using .Interface()-comparison (see issue #64)
- if v.IsInteger() && other.IsInteger() {
- return v.Integer() == other.Integer()
- }
return v.Interface() == other.Interface()
}
-
-type sortedKeys []reflect.Value
-
-func (sk sortedKeys) Len() int {
- return len(sk)
-}
-
-func (sk sortedKeys) Less(i, j int) bool {
- vi := &Value{val: sk[i]}
- vj := &Value{val: sk[j]}
- switch {
- case vi.IsInteger() && vj.IsInteger():
- return vi.Integer() < vj.Integer()
- case vi.IsFloat() && vj.IsFloat():
- return vi.Float() < vj.Float()
- default:
- return vi.String() < vj.String()
- }
-}
-
-func (sk sortedKeys) Swap(i, j int) {
- sk[i], sk[j] = sk[j], sk[i]
-}
-
-type valuesList []*Value
-
-func (vl valuesList) Len() int {
- return len(vl)
-}
-
-func (vl valuesList) Less(i, j int) bool {
- vi := vl[i]
- vj := vl[j]
- switch {
- case vi.IsInteger() && vj.IsInteger():
- return vi.Integer() < vj.Integer()
- case vi.IsFloat() && vj.IsFloat():
- return vi.Float() < vj.Float()
- default:
- return vi.String() < vj.String()
- }
-}
-
-func (vl valuesList) Swap(i, j int) {
- vl[i], vl[j] = vl[j], vl[i]
-}
diff --git a/vendor/github.com/flosch/pongo2/variable.go b/vendor/github.com/flosch/pongo2/variable.go
index 25bca20..9ec6a59 100644
--- a/vendor/github.com/flosch/pongo2/variable.go
+++ b/vendor/github.com/flosch/pongo2/variable.go
@@ -1,6 +1,7 @@
package pongo2
import (
+ "bytes"
"fmt"
"reflect"
"strconv"
@@ -17,8 +18,8 @@ type variablePart struct {
s string
i int
- isFunctionCall bool
- callingArgs []functionCallArgument // needed for a function call, represents all argument nodes (INode supports nested function calls)
+ is_function_call bool
+ calling_args []functionCallArgument // needed for a function call, represents all argument nodes (INode supports nested function calls)
}
type functionCallArgument interface {
@@ -27,119 +28,119 @@ type functionCallArgument interface {
// TODO: Add location tokens
type stringResolver struct {
- locationToken *Token
- val string
+ location_token *Token
+ val string
}
type intResolver struct {
- locationToken *Token
- val int
+ location_token *Token
+ val int
}
type floatResolver struct {
- locationToken *Token
- val float64
+ location_token *Token
+ val float64
}
type boolResolver struct {
- locationToken *Token
- val bool
+ location_token *Token
+ val bool
}
type variableResolver struct {
- locationToken *Token
+ location_token *Token
parts []*variablePart
}
type nodeFilteredVariable struct {
- locationToken *Token
+ location_token *Token
resolver IEvaluator
filterChain []*filterCall
}
type nodeVariable struct {
- locationToken *Token
- expr IEvaluator
+ location_token *Token
+ expr IEvaluator
}
-func (v *nodeFilteredVariable) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
- value, err := v.Evaluate(ctx)
+func (expr *nodeFilteredVariable) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
+ value, err := expr.Evaluate(ctx)
if err != nil {
return err
}
- writer.WriteString(value.String())
+ buffer.WriteString(value.String())
return nil
}
-func (vr *variableResolver) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
- value, err := vr.Evaluate(ctx)
+func (expr *variableResolver) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
+ value, err := expr.Evaluate(ctx)
if err != nil {
return err
}
- writer.WriteString(value.String())
+ buffer.WriteString(value.String())
return nil
}
-func (s *stringResolver) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
- value, err := s.Evaluate(ctx)
+func (expr *stringResolver) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
+ value, err := expr.Evaluate(ctx)
if err != nil {
return err
}
- writer.WriteString(value.String())
+ buffer.WriteString(value.String())
return nil
}
-func (i *intResolver) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
- value, err := i.Evaluate(ctx)
+func (expr *intResolver) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
+ value, err := expr.Evaluate(ctx)
if err != nil {
return err
}
- writer.WriteString(value.String())
+ buffer.WriteString(value.String())
return nil
}
-func (f *floatResolver) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
- value, err := f.Evaluate(ctx)
+func (expr *floatResolver) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
+ value, err := expr.Evaluate(ctx)
if err != nil {
return err
}
- writer.WriteString(value.String())
+ buffer.WriteString(value.String())
return nil
}
-func (b *boolResolver) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
- value, err := b.Evaluate(ctx)
+func (expr *boolResolver) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
+ value, err := expr.Evaluate(ctx)
if err != nil {
return err
}
- writer.WriteString(value.String())
+ buffer.WriteString(value.String())
return nil
}
func (v *nodeFilteredVariable) GetPositionToken() *Token {
- return v.locationToken
+ return v.location_token
}
-func (vr *variableResolver) GetPositionToken() *Token {
- return vr.locationToken
+func (v *variableResolver) GetPositionToken() *Token {
+ return v.location_token
}
-func (s *stringResolver) GetPositionToken() *Token {
- return s.locationToken
+func (v *stringResolver) GetPositionToken() *Token {
+ return v.location_token
}
-func (i *intResolver) GetPositionToken() *Token {
- return i.locationToken
+func (v *intResolver) GetPositionToken() *Token {
+ return v.location_token
}
-func (f *floatResolver) GetPositionToken() *Token {
- return f.locationToken
+func (v *floatResolver) GetPositionToken() *Token {
+ return v.location_token
}
-func (b *boolResolver) GetPositionToken() *Token {
- return b.locationToken
+func (v *boolResolver) GetPositionToken() *Token {
+ return v.location_token
}
func (s *stringResolver) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
@@ -178,7 +179,7 @@ func (nv *nodeVariable) FilterApplied(name string) bool {
return nv.expr.FilterApplied(name)
}
-func (nv *nodeVariable) Execute(ctx *ExecutionContext, writer TemplateWriter) *Error {
+func (nv *nodeVariable) Execute(ctx *ExecutionContext, buffer *bytes.Buffer) *Error {
value, err := nv.expr.Evaluate(ctx)
if err != nil {
return err
@@ -192,7 +193,7 @@ func (nv *nodeVariable) Execute(ctx *ExecutionContext, writer TemplateWriter) *E
}
}
- writer.WriteString(value.String())
+ buffer.WriteString(value.String())
return nil
}
@@ -217,15 +218,15 @@ func (vr *variableResolver) String() string {
func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) {
var current reflect.Value
- var isSafe bool
+ var is_safe bool
for idx, part := range vr.parts {
if idx == 0 {
// We're looking up the first part of the variable.
// First we're having a look in our private
// context (e. g. information provided by tags, like the forloop)
- val, inPrivate := ctx.Private[vr.parts[0].s]
- if !inPrivate {
+ val, in_private := ctx.Private[vr.parts[0].s]
+ if !in_private {
// Nothing found? Then have a final lookup in the public context
val = ctx.Public[vr.parts[0].s]
}
@@ -235,16 +236,16 @@ func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) {
// Before resolving the pointer, let's see if we have a method to call
// Problem with resolving the pointer is we're changing the receiver
- isFunc := false
+ is_func := false
if part.typ == varTypeIdent {
- funcValue := current.MethodByName(part.s)
- if funcValue.IsValid() {
- current = funcValue
- isFunc = true
+ func_value := current.MethodByName(part.s)
+ if func_value.IsValid() {
+ current = func_value
+ is_func = true
}
}
- if !isFunc {
+ if !is_func {
// If current a pointer, resolve it
if current.Kind() == reflect.Ptr {
current = current.Elem()
@@ -261,11 +262,7 @@ func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) {
// * slices/arrays/strings
switch current.Kind() {
case reflect.String, reflect.Array, reflect.Slice:
- if current.Len() > part.i {
- current = current.Index(part.i)
- } else {
- return nil, fmt.Errorf("Index out of range: %d (variable %s)", part.i, vr.String())
- }
+ current = current.Index(part.i)
default:
return nil, fmt.Errorf("Can't access an index on type %s (variable %s)",
current.Kind().String(), vr.String())
@@ -299,9 +296,9 @@ func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) {
// Happens in function calls (as a return value) or by injecting
// into the execution context (e.g. in a for-loop)
if current.Type() == reflect.TypeOf(&Value{}) {
- tmpValue := current.Interface().(*Value)
- current = tmpValue.val
- isSafe = tmpValue.safe
+ tmp_value := current.Interface().(*Value)
+ current = tmp_value.val
+ is_safe = tmp_value.safe
}
// Check whether this is an interface and resolve it where required
@@ -310,10 +307,10 @@ func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) {
}
// Check if the part is a function call
- if part.isFunctionCall || current.Kind() == reflect.Func {
+ if part.is_function_call || current.Kind() == reflect.Func {
// Check for callable
if current.Kind() != reflect.Func {
- return nil, fmt.Errorf("'%s' is not a function (it is %s)", vr.String(), current.Kind().String())
+ return nil, fmt.Errorf("'%s' is not a function (it is %s).", vr.String(), current.Kind().String())
}
// Check for correct function syntax and types
@@ -321,56 +318,58 @@ func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) {
t := current.Type()
// Input arguments
- if len(part.callingArgs) != t.NumIn() && !(len(part.callingArgs) >= t.NumIn()-1 && t.IsVariadic()) {
+ if len(part.calling_args) != t.NumIn() && !(len(part.calling_args) >= t.NumIn()-1 && t.IsVariadic()) {
return nil,
fmt.Errorf("Function input argument count (%d) of '%s' must be equal to the calling argument count (%d).",
- t.NumIn(), vr.String(), len(part.callingArgs))
+ t.NumIn(), vr.String(), len(part.calling_args))
}
// Output arguments
if t.NumOut() != 1 {
- return nil, fmt.Errorf("'%s' must have exactly 1 output argument", vr.String())
+ return nil, fmt.Errorf("'%s' must have exactly 1 output argument.", vr.String())
}
// Evaluate all parameters
- var parameters []reflect.Value
+ parameters := make([]reflect.Value, 0)
- numArgs := t.NumIn()
- isVariadic := t.IsVariadic()
- var fnArg reflect.Type
+ num_args := t.NumIn()
+ is_variadic := t.IsVariadic()
+ var fn_arg reflect.Type
- for idx, arg := range part.callingArgs {
+ for idx, arg := range part.calling_args {
pv, err := arg.Evaluate(ctx)
if err != nil {
return nil, err
}
- if isVariadic {
+ if is_variadic {
if idx >= t.NumIn()-1 {
- fnArg = t.In(numArgs - 1).Elem()
+ fn_arg = t.In(num_args - 1).Elem()
} else {
- fnArg = t.In(idx)
+ fn_arg = t.In(idx)
}
} else {
- fnArg = t.In(idx)
+ fn_arg = t.In(idx)
}
- if fnArg != reflect.TypeOf(new(Value)) {
+ if fn_arg != reflect.TypeOf(new(Value)) {
// Function's argument is not a *pongo2.Value, then we have to check whether input argument is of the same type as the function's argument
- if !isVariadic {
- if fnArg != reflect.TypeOf(pv.Interface()) && fnArg.Kind() != reflect.Interface {
+ if !is_variadic {
+ if fn_arg != reflect.TypeOf(pv.Interface()) && fn_arg.Kind() != reflect.Interface {
return nil, fmt.Errorf("Function input argument %d of '%s' must be of type %s or *pongo2.Value (not %T).",
- idx, vr.String(), fnArg.String(), pv.Interface())
+ idx, vr.String(), fn_arg.String(), pv.Interface())
+ } else {
+ // Function's argument has another type, using the interface-value
+ parameters = append(parameters, reflect.ValueOf(pv.Interface()))
}
- // Function's argument has another type, using the interface-value
- parameters = append(parameters, reflect.ValueOf(pv.Interface()))
} else {
- if fnArg != reflect.TypeOf(pv.Interface()) && fnArg.Kind() != reflect.Interface {
+ if fn_arg != reflect.TypeOf(pv.Interface()) && fn_arg.Kind() != reflect.Interface {
return nil, fmt.Errorf("Function variadic input argument of '%s' must be of type %s or *pongo2.Value (not %T).",
- vr.String(), fnArg.String(), pv.Interface())
+ vr.String(), fn_arg.String(), pv.Interface())
+ } else {
+ // Function's argument has another type, using the interface-value
+ parameters = append(parameters, reflect.ValueOf(pv.Interface()))
}
- // Function's argument has another type, using the interface-value
- parameters = append(parameters, reflect.ValueOf(pv.Interface()))
}
} else {
// Function's argument is a *pongo2.Value
@@ -378,13 +377,6 @@ func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) {
}
}
- // Check if any of the values are invalid
- for _, p := range parameters {
- if p.Kind() == reflect.Invalid {
- return nil, fmt.Errorf("Calling a function using an invalid parameter")
- }
- }
-
// Call it and get first return parameter back
rv := current.Call(parameters)[0]
@@ -393,7 +385,7 @@ func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) {
} else {
// Return the function call value
current = rv.Interface().(*Value).val
- isSafe = rv.Interface().(*Value).safe
+ is_safe = rv.Interface().(*Value).safe
}
}
}
@@ -403,13 +395,13 @@ func (vr *variableResolver) resolve(ctx *ExecutionContext) (*Value, error) {
return AsValue(nil), nil
}
- return &Value{val: current, safe: isSafe}, nil
+ return &Value{val: current, safe: is_safe}, nil
}
func (vr *variableResolver) Evaluate(ctx *ExecutionContext) (*Value, *Error) {
value, err := vr.resolve(ctx)
if err != nil {
- return AsValue(nil), ctx.Error(err.Error(), vr.locationToken)
+ return AsValue(nil), ctx.Error(err.Error(), vr.location_token)
}
return value, nil
}
@@ -444,7 +436,7 @@ func (p *Parser) parseVariableOrLiteral() (IEvaluator, *Error) {
t := p.Current()
if t == nil {
- return nil, p.Error("Unexpected EOF, expected a number, string, keyword or identifier.", p.lastToken)
+ return nil, p.Error("Unexpected EOF, expected a number, string, keyword or identifier.", p.last_token)
}
// Is first part a number or a string, there's nothing to resolve (because there's only to return the value then)
@@ -468,26 +460,26 @@ func (p *Parser) parseVariableOrLiteral() (IEvaluator, *Error) {
return nil, p.Error(err.Error(), t)
}
fr := &floatResolver{
- locationToken: t,
- val: f,
+ location_token: t,
+ val: f,
}
return fr, nil
+ } else {
+ i, err := strconv.Atoi(t.Val)
+ if err != nil {
+ return nil, p.Error(err.Error(), t)
+ }
+ nr := &intResolver{
+ location_token: t,
+ val: i,
+ }
+ return nr, nil
}
- i, err := strconv.Atoi(t.Val)
- if err != nil {
- return nil, p.Error(err.Error(), t)
- }
- nr := &intResolver{
- locationToken: t,
- val: i,
- }
- return nr, nil
-
case TokenString:
p.Consume()
sr := &stringResolver{
- locationToken: t,
- val: t.Val,
+ location_token: t,
+ val: t.Val,
}
return sr, nil
case TokenKeyword:
@@ -495,14 +487,14 @@ func (p *Parser) parseVariableOrLiteral() (IEvaluator, *Error) {
switch t.Val {
case "true":
br := &boolResolver{
- locationToken: t,
- val: true,
+ location_token: t,
+ val: true,
}
return br, nil
case "false":
br := &boolResolver{
- locationToken: t,
- val: false,
+ location_token: t,
+ val: false,
}
return br, nil
default:
@@ -511,7 +503,7 @@ func (p *Parser) parseVariableOrLiteral() (IEvaluator, *Error) {
}
resolver := &variableResolver{
- locationToken: t,
+ location_token: t,
}
// First part of a variable MUST be an identifier
@@ -559,26 +551,26 @@ variableLoop:
} else {
// EOF
return nil, p.Error("Unexpected EOF, expected either IDENTIFIER or NUMBER after DOT.",
- p.lastToken)
+ p.last_token)
}
} else if p.Match(TokenSymbol, "(") != nil {
// Function call
// FunctionName '(' Comma-separated list of expressions ')'
part := resolver.parts[len(resolver.parts)-1]
- part.isFunctionCall = true
+ part.is_function_call = true
argumentLoop:
for {
if p.Remaining() == 0 {
- return nil, p.Error("Unexpected EOF, expected function call argument list.", p.lastToken)
+ return nil, p.Error("Unexpected EOF, expected function call argument list.", p.last_token)
}
if p.Peek(TokenSymbol, ")") == nil {
// No closing bracket, so we're parsing an expression
- exprArg, err := p.ParseExpression()
+ expr_arg, err := p.ParseExpression()
if err != nil {
return nil, err
}
- part.callingArgs = append(part.callingArgs, exprArg)
+ part.calling_args = append(part.calling_args, expr_arg)
if p.Match(TokenSymbol, ")") != nil {
// If there's a closing bracket after an expression, we will stop parsing the arguments
@@ -609,7 +601,7 @@ variableLoop:
func (p *Parser) parseVariableOrLiteralWithFilter() (*nodeFilteredVariable, *Error) {
v := &nodeFilteredVariable{
- locationToken: p.Current(),
+ location_token: p.Current(),
}
// Parse the variable name
@@ -629,13 +621,15 @@ filterLoop:
}
// Check sandbox filter restriction
- if _, isBanned := p.template.set.bannedFilters[filter.name]; isBanned {
+ if _, is_banned := p.template.set.bannedFilters[filter.name]; is_banned {
return nil, p.Error(fmt.Sprintf("Usage of filter '%s' is not allowed (sandbox restriction active).", filter.name), nil)
}
v.filterChain = append(v.filterChain, filter)
continue filterLoop
+
+ return nil, p.Error("This token is not allowed within a variable.", nil)
}
return v, nil
@@ -643,7 +637,7 @@ filterLoop:
func (p *Parser) parseVariableElement() (INode, *Error) {
node := &nodeVariable{
- locationToken: p.Current(),
+ location_token: p.Current(),
}
p.Consume() // consume '{{'
diff --git a/vendor/github.com/golang/protobuf/.gitignore b/vendor/github.com/golang/protobuf/.gitignore
new file mode 100644
index 0000000..8f5b596
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/.gitignore
@@ -0,0 +1,16 @@
+.DS_Store
+*.[568ao]
+*.ao
+*.so
+*.pyc
+._*
+.nfs.*
+[568a].out
+*~
+*.orig
+core
+_obj
+_test
+_testmain.go
+protoc-gen-go/testdata/multi/*.pb.go
+_conformance/_conformance
diff --git a/vendor/github.com/golang/protobuf/.travis.yml b/vendor/github.com/golang/protobuf/.travis.yml
new file mode 100644
index 0000000..93c6780
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/.travis.yml
@@ -0,0 +1,18 @@
+sudo: false
+language: go
+go:
+- 1.6.x
+- 1.7.x
+- 1.8.x
+- 1.9.x
+
+install:
+ - go get -v -d -t github.com/golang/protobuf/...
+ - curl -L https://github.com/google/protobuf/releases/download/v3.3.0/protoc-3.3.0-linux-x86_64.zip -o /tmp/protoc.zip
+ - unzip /tmp/protoc.zip -d $HOME/protoc
+
+env:
+ - PATH=$HOME/protoc/bin:$PATH
+
+script:
+ - make all test
diff --git a/vendor/github.com/golang/protobuf/AUTHORS b/vendor/github.com/golang/protobuf/AUTHORS
new file mode 100644
index 0000000..15167cd
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/AUTHORS
@@ -0,0 +1,3 @@
+# This source code refers to The Go Authors for copyright purposes.
+# The master list of authors is in the main Go distribution,
+# visible at http://tip.golang.org/AUTHORS.
diff --git a/vendor/github.com/golang/protobuf/CONTRIBUTORS b/vendor/github.com/golang/protobuf/CONTRIBUTORS
new file mode 100644
index 0000000..1c4577e
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/CONTRIBUTORS
@@ -0,0 +1,3 @@
+# This source code was written by the Go contributors.
+# The master list of contributors is in the main Go distribution,
+# visible at http://tip.golang.org/CONTRIBUTORS.
diff --git a/vendor/github.com/golang/protobuf/LICENSE b/vendor/github.com/golang/protobuf/LICENSE
new file mode 100644
index 0000000..1b1b192
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/LICENSE
@@ -0,0 +1,31 @@
+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.
+
diff --git a/vendor/github.com/golang/protobuf/Make.protobuf b/vendor/github.com/golang/protobuf/Make.protobuf
new file mode 100644
index 0000000..15071de
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/Make.protobuf
@@ -0,0 +1,40 @@
+# 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.
+
+# Includable Makefile to add a rule for generating .pb.go files from .proto files
+# (Google protocol buffer descriptions).
+# Typical use if myproto.proto is a file in package mypackage in this directory:
+#
+# include $(GOROOT)/src/pkg/github.com/golang/protobuf/Make.protobuf
+
+%.pb.go: %.proto
+ protoc --go_out=. $<
+
diff --git a/vendor/github.com/golang/protobuf/Makefile b/vendor/github.com/golang/protobuf/Makefile
new file mode 100644
index 0000000..a1421d8
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/Makefile
@@ -0,0 +1,55 @@
+# 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.
+
+
+all: install
+
+install:
+ go install ./proto ./jsonpb ./ptypes
+ go install ./protoc-gen-go
+
+test:
+ go test ./proto ./jsonpb ./ptypes
+ make -C protoc-gen-go/testdata test
+
+clean:
+ go clean ./...
+
+nuke:
+ go clean -i ./...
+
+regenerate:
+ make -C protoc-gen-go/descriptor regenerate
+ make -C protoc-gen-go/plugin regenerate
+ make -C protoc-gen-go/testdata regenerate
+ make -C proto/testdata regenerate
+ make -C jsonpb/jsonpb_test_proto regenerate
+ make -C _conformance regenerate
diff --git a/vendor/github.com/golang/protobuf/README.md b/vendor/github.com/golang/protobuf/README.md
new file mode 100644
index 0000000..9c4c815
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/README.md
@@ -0,0 +1,244 @@
+# Go support for Protocol Buffers
+
+[![Build Status](https://travis-ci.org/golang/protobuf.svg?branch=master)](https://travis-ci.org/golang/protobuf)
+[![GoDoc](https://godoc.org/github.com/golang/protobuf?status.svg)](https://godoc.org/github.com/golang/protobuf)
+
+Google's data interchange format.
+Copyright 2010 The Go Authors.
+https://github.com/golang/protobuf
+
+This package and the code it generates requires at least Go 1.4.
+
+This software implements Go bindings for protocol buffers. For
+information about protocol buffers themselves, see
+ https://developers.google.com/protocol-buffers/
+
+## Installation ##
+
+To use this software, you must:
+- Install the standard C++ implementation of protocol buffers from
+ https://developers.google.com/protocol-buffers/
+- Of course, install the Go compiler and tools from
+ https://golang.org/
+ See
+ https://golang.org/doc/install
+ for details or, if you are using gccgo, follow the instructions at
+ https://golang.org/doc/install/gccgo
+- Grab the code from the repository and install the proto package.
+ The simplest way is to run `go get -u github.com/golang/protobuf/protoc-gen-go`.
+ The compiler plugin, protoc-gen-go, will be installed in $GOBIN,
+ defaulting to $GOPATH/bin. It must be in your $PATH for the protocol
+ compiler, protoc, to find it.
+
+This software has two parts: a 'protocol compiler plugin' that
+generates Go source files that, once compiled, can access and manage
+protocol buffers; and a library that implements run-time support for
+encoding (marshaling), decoding (unmarshaling), and accessing protocol
+buffers.
+
+There is support for gRPC in Go using protocol buffers.
+See the note at the bottom of this file for details.
+
+There are no insertion points in the plugin.
+
+
+## Using protocol buffers with Go ##
+
+Once the software is installed, there are two steps to using it.
+First you must compile the protocol buffer definitions and then import
+them, with the support library, into your program.
+
+To compile the protocol buffer definition, run protoc with the --go_out
+parameter set to the directory you want to output the Go code to.
+
+ protoc --go_out=. *.proto
+
+The generated files will be suffixed .pb.go. See the Test code below
+for an example using such a file.
+
+
+The package comment for the proto library contains text describing
+the interface provided in Go for protocol buffers. Here is an edited
+version.
+
+==========
+
+The proto package converts data structures to and from the
+wire format of protocol buffers. It works in concert with the
+Go source code generated for .proto files by the protocol compiler.
+
+A summary of the properties of the protocol buffer interface
+for a protocol buffer variable v:
+
+ - Names are turned from camel_case to CamelCase for export.
+ - There are no methods on v to set fields; just treat
+ them as structure fields.
+ - There are getters that return a field's value if set,
+ and return the field's default value if unset.
+ The getters work even if the receiver is a nil message.
+ - The zero value for a struct is its correct initialization state.
+ All desired fields must be set before marshaling.
+ - A Reset() method will restore a protobuf struct to its zero state.
+ - Non-repeated fields are pointers to the values; nil means unset.
+ That is, optional or required field int32 f becomes F *int32.
+ - Repeated fields are slices.
+ - Helper functions are available to aid the setting of fields.
+ Helpers for getting values are superseded by the
+ GetFoo methods and their use is deprecated.
+ msg.Foo = proto.String("hello") // set field
+ - Constants are defined to hold the default values of all fields that
+ have them. They have the form Default_StructName_FieldName.
+ Because the getter methods handle defaulted values,
+ direct use of these constants should be rare.
+ - Enums are given type names and maps from names to values.
+ Enum values are prefixed with the enum's type name. Enum types have
+ a String method, and a Enum method to assist in message construction.
+ - Nested groups and enums have type names prefixed with the name of
+ the surrounding message type.
+ - Extensions are given descriptor names that start with E_,
+ followed by an underscore-delimited list of the nested messages
+ that contain it (if any) followed by the CamelCased name of the
+ extension field itself. HasExtension, ClearExtension, GetExtension
+ and SetExtension are functions for manipulating extensions.
+ - Oneof field sets are given a single field in their message,
+ with distinguished wrapper types for each possible field value.
+ - Marshal and Unmarshal are functions to encode and decode the wire format.
+
+When the .proto file specifies `syntax="proto3"`, there are some differences:
+
+ - Non-repeated fields of non-message type are values instead of pointers.
+ - Enum types do not get an Enum method.
+
+Consider file test.proto, containing
+
+```proto
+ syntax = "proto2";
+ package example;
+
+ enum FOO { X = 17; };
+
+ message Test {
+ required string label = 1;
+ optional int32 type = 2 [default=77];
+ repeated int64 reps = 3;
+ optional group OptionalGroup = 4 {
+ required string RequiredField = 5;
+ }
+ }
+```
+
+To create and play with a Test object from the example package,
+
+```go
+ package main
+
+ import (
+ "log"
+
+ "github.com/golang/protobuf/proto"
+ "path/to/example"
+ )
+
+ func main() {
+ test := &example.Test {
+ Label: proto.String("hello"),
+ Type: proto.Int32(17),
+ Reps: []int64{1, 2, 3},
+ Optionalgroup: &example.Test_OptionalGroup {
+ RequiredField: proto.String("good bye"),
+ },
+ }
+ data, err := proto.Marshal(test)
+ if err != nil {
+ log.Fatal("marshaling error: ", err)
+ }
+ newTest := &example.Test{}
+ err = proto.Unmarshal(data, newTest)
+ if err != nil {
+ log.Fatal("unmarshaling error: ", err)
+ }
+ // Now test and newTest contain the same data.
+ if test.GetLabel() != newTest.GetLabel() {
+ log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
+ }
+ // etc.
+ }
+```
+
+## Parameters ##
+
+To pass extra parameters to the plugin, use a comma-separated
+parameter list separated from the output directory by a colon:
+
+
+ protoc --go_out=plugins=grpc,import_path=mypackage:. *.proto
+
+
+- `import_prefix=xxx` - a prefix that is added onto the beginning of
+ all imports. Useful for things like generating protos in a
+ subdirectory, or regenerating vendored protobufs in-place.
+- `import_path=foo/bar` - used as the package if no input files
+ declare `go_package`. If it contains slashes, everything up to the
+ rightmost slash is ignored.
+- `plugins=plugin1+plugin2` - specifies the list of sub-plugins to
+ load. The only plugin in this repo is `grpc`.
+- `Mfoo/bar.proto=quux/shme` - declares that foo/bar.proto is
+ associated with Go package quux/shme. This is subject to the
+ import_prefix parameter.
+
+## gRPC Support ##
+
+If a proto file specifies RPC services, protoc-gen-go can be instructed to
+generate code compatible with gRPC (http://www.grpc.io/). To do this, pass
+the `plugins` parameter to protoc-gen-go; the usual way is to insert it into
+the --go_out argument to protoc:
+
+ protoc --go_out=plugins=grpc:. *.proto
+
+## Compatibility ##
+
+The library and the generated code are expected to be stable over time.
+However, we reserve the right to make breaking changes without notice for the
+following reasons:
+
+- Security. A security issue in the specification or implementation may come to
+ light whose resolution requires breaking compatibility. We reserve the right
+ to address such security issues.
+- Unspecified behavior. There are some aspects of the Protocol Buffers
+ specification that are undefined. Programs that depend on such unspecified
+ behavior may break in future releases.
+- Specification errors or changes. If it becomes necessary to address an
+ inconsistency, incompleteness, or change in the Protocol Buffers
+ specification, resolving the issue could affect the meaning or legality of
+ existing programs. We reserve the right to address such issues, including
+ updating the implementations.
+- Bugs. If the library has a bug that violates the specification, a program
+ that depends on the buggy behavior may break if the bug is fixed. We reserve
+ the right to fix such bugs.
+- Adding methods or fields to generated structs. These may conflict with field
+ names that already exist in a schema, causing applications to break. When the
+ code generator encounters a field in the schema that would collide with a
+ generated field or method name, the code generator will append an underscore
+ to the generated field or method name.
+- Adding, removing, or changing methods or fields in generated structs that
+ start with `XXX`. These parts of the generated code are exported out of
+ necessity, but should not be considered part of the public API.
+- Adding, removing, or changing unexported symbols in generated code.
+
+Any breaking changes outside of these will be announced 6 months in advance to
+protobuf@googlegroups.com.
+
+You should, whenever possible, use generated code created by the `protoc-gen-go`
+tool built at the same commit as the `proto` package. The `proto` package
+declares package-level constants in the form `ProtoPackageIsVersionX`.
+Application code and generated code may depend on one of these constants to
+ensure that compilation will fail if the available version of the proto library
+is too old. Whenever we make a change to the generated code that requires newer
+library support, in the same commit we will increment the version number of the
+generated code and declare a new package-level constant whose name incorporates
+the latest version number. Removing a compatibility constant is considered a
+breaking change and would be subject to the announcement policy stated above.
+
+The `protoc-gen-go/generator` package exposes a plugin interface,
+which is used by the gRPC code generation. This interface is not
+supported and is subject to incompatible changes without notice.
diff --git a/vendor/github.com/golang/protobuf/_conformance/Makefile b/vendor/github.com/golang/protobuf/_conformance/Makefile
new file mode 100644
index 0000000..89800e2
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/_conformance/Makefile
@@ -0,0 +1,33 @@
+# Go support for Protocol Buffers - Google's data interchange format
+#
+# Copyright 2016 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.
+
+regenerate:
+ protoc --go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any,Mgoogle/protobuf/duration.proto=github.com/golang/protobuf/ptypes/duration,Mgoogle/protobuf/struct.proto=github.com/golang/protobuf/ptypes/struct,Mgoogle/protobuf/timestamp.proto=github.com/golang/protobuf/ptypes/timestamp,Mgoogle/protobuf/wrappers.proto=github.com/golang/protobuf/ptypes/wrappers,Mgoogle/protobuf/field_mask.proto=google.golang.org/genproto/protobuf:. conformance_proto/conformance.proto
diff --git a/vendor/github.com/golang/protobuf/_conformance/conformance.go b/vendor/github.com/golang/protobuf/_conformance/conformance.go
new file mode 100644
index 0000000..c54212c
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/_conformance/conformance.go
@@ -0,0 +1,161 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 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.
+
+// conformance implements the conformance test subprocess protocol as
+// documented in conformance.proto.
+package main
+
+import (
+ "encoding/binary"
+ "fmt"
+ "io"
+ "os"
+
+ pb "github.com/golang/protobuf/_conformance/conformance_proto"
+ "github.com/golang/protobuf/jsonpb"
+ "github.com/golang/protobuf/proto"
+)
+
+func main() {
+ var sizeBuf [4]byte
+ inbuf := make([]byte, 0, 4096)
+ outbuf := proto.NewBuffer(nil)
+ for {
+ if _, err := io.ReadFull(os.Stdin, sizeBuf[:]); err == io.EOF {
+ break
+ } else if err != nil {
+ fmt.Fprintln(os.Stderr, "go conformance: read request:", err)
+ os.Exit(1)
+ }
+ size := binary.LittleEndian.Uint32(sizeBuf[:])
+ if int(size) > cap(inbuf) {
+ inbuf = make([]byte, size)
+ }
+ inbuf = inbuf[:size]
+ if _, err := io.ReadFull(os.Stdin, inbuf); err != nil {
+ fmt.Fprintln(os.Stderr, "go conformance: read request:", err)
+ os.Exit(1)
+ }
+
+ req := new(pb.ConformanceRequest)
+ if err := proto.Unmarshal(inbuf, req); err != nil {
+ fmt.Fprintln(os.Stderr, "go conformance: parse request:", err)
+ os.Exit(1)
+ }
+ res := handle(req)
+
+ if err := outbuf.Marshal(res); err != nil {
+ fmt.Fprintln(os.Stderr, "go conformance: marshal response:", err)
+ os.Exit(1)
+ }
+ binary.LittleEndian.PutUint32(sizeBuf[:], uint32(len(outbuf.Bytes())))
+ if _, err := os.Stdout.Write(sizeBuf[:]); err != nil {
+ fmt.Fprintln(os.Stderr, "go conformance: write response:", err)
+ os.Exit(1)
+ }
+ if _, err := os.Stdout.Write(outbuf.Bytes()); err != nil {
+ fmt.Fprintln(os.Stderr, "go conformance: write response:", err)
+ os.Exit(1)
+ }
+ outbuf.Reset()
+ }
+}
+
+var jsonMarshaler = jsonpb.Marshaler{
+ OrigName: true,
+}
+
+func handle(req *pb.ConformanceRequest) *pb.ConformanceResponse {
+ var err error
+ var msg pb.TestAllTypes
+ switch p := req.Payload.(type) {
+ case *pb.ConformanceRequest_ProtobufPayload:
+ err = proto.Unmarshal(p.ProtobufPayload, &msg)
+ case *pb.ConformanceRequest_JsonPayload:
+ err = jsonpb.UnmarshalString(p.JsonPayload, &msg)
+ if err != nil && err.Error() == "unmarshaling Any not supported yet" {
+ return &pb.ConformanceResponse{
+ Result: &pb.ConformanceResponse_Skipped{
+ Skipped: err.Error(),
+ },
+ }
+ }
+ default:
+ return &pb.ConformanceResponse{
+ Result: &pb.ConformanceResponse_RuntimeError{
+ RuntimeError: "unknown request payload type",
+ },
+ }
+ }
+ if err != nil {
+ return &pb.ConformanceResponse{
+ Result: &pb.ConformanceResponse_ParseError{
+ ParseError: err.Error(),
+ },
+ }
+ }
+ switch req.RequestedOutputFormat {
+ case pb.WireFormat_PROTOBUF:
+ p, err := proto.Marshal(&msg)
+ if err != nil {
+ return &pb.ConformanceResponse{
+ Result: &pb.ConformanceResponse_SerializeError{
+ SerializeError: err.Error(),
+ },
+ }
+ }
+ return &pb.ConformanceResponse{
+ Result: &pb.ConformanceResponse_ProtobufPayload{
+ ProtobufPayload: p,
+ },
+ }
+ case pb.WireFormat_JSON:
+ p, err := jsonMarshaler.MarshalToString(&msg)
+ if err != nil {
+ return &pb.ConformanceResponse{
+ Result: &pb.ConformanceResponse_SerializeError{
+ SerializeError: err.Error(),
+ },
+ }
+ }
+ return &pb.ConformanceResponse{
+ Result: &pb.ConformanceResponse_JsonPayload{
+ JsonPayload: p,
+ },
+ }
+ default:
+ return &pb.ConformanceResponse{
+ Result: &pb.ConformanceResponse_RuntimeError{
+ RuntimeError: "unknown output format",
+ },
+ }
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/_conformance/conformance_proto/conformance.pb.go b/vendor/github.com/golang/protobuf/_conformance/conformance_proto/conformance.pb.go
new file mode 100644
index 0000000..ec354ea
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/_conformance/conformance_proto/conformance.pb.go
@@ -0,0 +1,1885 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: conformance_proto/conformance.proto
+
+/*
+Package conformance is a generated protocol buffer package.
+
+It is generated from these files:
+ conformance_proto/conformance.proto
+
+It has these top-level messages:
+ ConformanceRequest
+ ConformanceResponse
+ TestAllTypes
+ ForeignMessage
+*/
+package conformance
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import google_protobuf "github.com/golang/protobuf/ptypes/any"
+import google_protobuf1 "github.com/golang/protobuf/ptypes/duration"
+import google_protobuf2 "google.golang.org/genproto/protobuf"
+import google_protobuf3 "github.com/golang/protobuf/ptypes/struct"
+import google_protobuf4 "github.com/golang/protobuf/ptypes/timestamp"
+import google_protobuf5 "github.com/golang/protobuf/ptypes/wrappers"
+
+// 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
+
+type WireFormat int32
+
+const (
+ WireFormat_UNSPECIFIED WireFormat = 0
+ WireFormat_PROTOBUF WireFormat = 1
+ WireFormat_JSON WireFormat = 2
+)
+
+var WireFormat_name = map[int32]string{
+ 0: "UNSPECIFIED",
+ 1: "PROTOBUF",
+ 2: "JSON",
+}
+var WireFormat_value = map[string]int32{
+ "UNSPECIFIED": 0,
+ "PROTOBUF": 1,
+ "JSON": 2,
+}
+
+func (x WireFormat) String() string {
+ return proto.EnumName(WireFormat_name, int32(x))
+}
+func (WireFormat) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+type ForeignEnum int32
+
+const (
+ ForeignEnum_FOREIGN_FOO ForeignEnum = 0
+ ForeignEnum_FOREIGN_BAR ForeignEnum = 1
+ ForeignEnum_FOREIGN_BAZ ForeignEnum = 2
+)
+
+var ForeignEnum_name = map[int32]string{
+ 0: "FOREIGN_FOO",
+ 1: "FOREIGN_BAR",
+ 2: "FOREIGN_BAZ",
+}
+var ForeignEnum_value = map[string]int32{
+ "FOREIGN_FOO": 0,
+ "FOREIGN_BAR": 1,
+ "FOREIGN_BAZ": 2,
+}
+
+func (x ForeignEnum) String() string {
+ return proto.EnumName(ForeignEnum_name, int32(x))
+}
+func (ForeignEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+type TestAllTypes_NestedEnum int32
+
+const (
+ TestAllTypes_FOO TestAllTypes_NestedEnum = 0
+ TestAllTypes_BAR TestAllTypes_NestedEnum = 1
+ TestAllTypes_BAZ TestAllTypes_NestedEnum = 2
+ TestAllTypes_NEG TestAllTypes_NestedEnum = -1
+)
+
+var TestAllTypes_NestedEnum_name = map[int32]string{
+ 0: "FOO",
+ 1: "BAR",
+ 2: "BAZ",
+ -1: "NEG",
+}
+var TestAllTypes_NestedEnum_value = map[string]int32{
+ "FOO": 0,
+ "BAR": 1,
+ "BAZ": 2,
+ "NEG": -1,
+}
+
+func (x TestAllTypes_NestedEnum) String() string {
+ return proto.EnumName(TestAllTypes_NestedEnum_name, int32(x))
+}
+func (TestAllTypes_NestedEnum) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} }
+
+// Represents a single test case's input. The testee should:
+//
+// 1. parse this proto (which should always succeed)
+// 2. parse the protobuf or JSON payload in "payload" (which may fail)
+// 3. if the parse succeeded, serialize the message in the requested format.
+type ConformanceRequest struct {
+ // The payload (whether protobuf of JSON) is always for a TestAllTypes proto
+ // (see below).
+ //
+ // Types that are valid to be assigned to Payload:
+ // *ConformanceRequest_ProtobufPayload
+ // *ConformanceRequest_JsonPayload
+ Payload isConformanceRequest_Payload `protobuf_oneof:"payload"`
+ // Which format should the testee serialize its message to?
+ RequestedOutputFormat WireFormat `protobuf:"varint,3,opt,name=requested_output_format,json=requestedOutputFormat,enum=conformance.WireFormat" json:"requested_output_format,omitempty"`
+}
+
+func (m *ConformanceRequest) Reset() { *m = ConformanceRequest{} }
+func (m *ConformanceRequest) String() string { return proto.CompactTextString(m) }
+func (*ConformanceRequest) ProtoMessage() {}
+func (*ConformanceRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+type isConformanceRequest_Payload interface {
+ isConformanceRequest_Payload()
+}
+
+type ConformanceRequest_ProtobufPayload struct {
+ ProtobufPayload []byte `protobuf:"bytes,1,opt,name=protobuf_payload,json=protobufPayload,proto3,oneof"`
+}
+type ConformanceRequest_JsonPayload struct {
+ JsonPayload string `protobuf:"bytes,2,opt,name=json_payload,json=jsonPayload,oneof"`
+}
+
+func (*ConformanceRequest_ProtobufPayload) isConformanceRequest_Payload() {}
+func (*ConformanceRequest_JsonPayload) isConformanceRequest_Payload() {}
+
+func (m *ConformanceRequest) GetPayload() isConformanceRequest_Payload {
+ if m != nil {
+ return m.Payload
+ }
+ return nil
+}
+
+func (m *ConformanceRequest) GetProtobufPayload() []byte {
+ if x, ok := m.GetPayload().(*ConformanceRequest_ProtobufPayload); ok {
+ return x.ProtobufPayload
+ }
+ return nil
+}
+
+func (m *ConformanceRequest) GetJsonPayload() string {
+ if x, ok := m.GetPayload().(*ConformanceRequest_JsonPayload); ok {
+ return x.JsonPayload
+ }
+ return ""
+}
+
+func (m *ConformanceRequest) GetRequestedOutputFormat() WireFormat {
+ if m != nil {
+ return m.RequestedOutputFormat
+ }
+ return WireFormat_UNSPECIFIED
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*ConformanceRequest) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _ConformanceRequest_OneofMarshaler, _ConformanceRequest_OneofUnmarshaler, _ConformanceRequest_OneofSizer, []interface{}{
+ (*ConformanceRequest_ProtobufPayload)(nil),
+ (*ConformanceRequest_JsonPayload)(nil),
+ }
+}
+
+func _ConformanceRequest_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*ConformanceRequest)
+ // payload
+ switch x := m.Payload.(type) {
+ case *ConformanceRequest_ProtobufPayload:
+ b.EncodeVarint(1<<3 | proto.WireBytes)
+ b.EncodeRawBytes(x.ProtobufPayload)
+ case *ConformanceRequest_JsonPayload:
+ b.EncodeVarint(2<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.JsonPayload)
+ case nil:
+ default:
+ return fmt.Errorf("ConformanceRequest.Payload has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _ConformanceRequest_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*ConformanceRequest)
+ switch tag {
+ case 1: // payload.protobuf_payload
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeRawBytes(true)
+ m.Payload = &ConformanceRequest_ProtobufPayload{x}
+ return true, err
+ case 2: // payload.json_payload
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Payload = &ConformanceRequest_JsonPayload{x}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _ConformanceRequest_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*ConformanceRequest)
+ // payload
+ switch x := m.Payload.(type) {
+ case *ConformanceRequest_ProtobufPayload:
+ n += proto.SizeVarint(1<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.ProtobufPayload)))
+ n += len(x.ProtobufPayload)
+ case *ConformanceRequest_JsonPayload:
+ n += proto.SizeVarint(2<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.JsonPayload)))
+ n += len(x.JsonPayload)
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// Represents a single test case's output.
+type ConformanceResponse struct {
+ // Types that are valid to be assigned to Result:
+ // *ConformanceResponse_ParseError
+ // *ConformanceResponse_SerializeError
+ // *ConformanceResponse_RuntimeError
+ // *ConformanceResponse_ProtobufPayload
+ // *ConformanceResponse_JsonPayload
+ // *ConformanceResponse_Skipped
+ Result isConformanceResponse_Result `protobuf_oneof:"result"`
+}
+
+func (m *ConformanceResponse) Reset() { *m = ConformanceResponse{} }
+func (m *ConformanceResponse) String() string { return proto.CompactTextString(m) }
+func (*ConformanceResponse) ProtoMessage() {}
+func (*ConformanceResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+type isConformanceResponse_Result interface {
+ isConformanceResponse_Result()
+}
+
+type ConformanceResponse_ParseError struct {
+ ParseError string `protobuf:"bytes,1,opt,name=parse_error,json=parseError,oneof"`
+}
+type ConformanceResponse_SerializeError struct {
+ SerializeError string `protobuf:"bytes,6,opt,name=serialize_error,json=serializeError,oneof"`
+}
+type ConformanceResponse_RuntimeError struct {
+ RuntimeError string `protobuf:"bytes,2,opt,name=runtime_error,json=runtimeError,oneof"`
+}
+type ConformanceResponse_ProtobufPayload struct {
+ ProtobufPayload []byte `protobuf:"bytes,3,opt,name=protobuf_payload,json=protobufPayload,proto3,oneof"`
+}
+type ConformanceResponse_JsonPayload struct {
+ JsonPayload string `protobuf:"bytes,4,opt,name=json_payload,json=jsonPayload,oneof"`
+}
+type ConformanceResponse_Skipped struct {
+ Skipped string `protobuf:"bytes,5,opt,name=skipped,oneof"`
+}
+
+func (*ConformanceResponse_ParseError) isConformanceResponse_Result() {}
+func (*ConformanceResponse_SerializeError) isConformanceResponse_Result() {}
+func (*ConformanceResponse_RuntimeError) isConformanceResponse_Result() {}
+func (*ConformanceResponse_ProtobufPayload) isConformanceResponse_Result() {}
+func (*ConformanceResponse_JsonPayload) isConformanceResponse_Result() {}
+func (*ConformanceResponse_Skipped) isConformanceResponse_Result() {}
+
+func (m *ConformanceResponse) GetResult() isConformanceResponse_Result {
+ if m != nil {
+ return m.Result
+ }
+ return nil
+}
+
+func (m *ConformanceResponse) GetParseError() string {
+ if x, ok := m.GetResult().(*ConformanceResponse_ParseError); ok {
+ return x.ParseError
+ }
+ return ""
+}
+
+func (m *ConformanceResponse) GetSerializeError() string {
+ if x, ok := m.GetResult().(*ConformanceResponse_SerializeError); ok {
+ return x.SerializeError
+ }
+ return ""
+}
+
+func (m *ConformanceResponse) GetRuntimeError() string {
+ if x, ok := m.GetResult().(*ConformanceResponse_RuntimeError); ok {
+ return x.RuntimeError
+ }
+ return ""
+}
+
+func (m *ConformanceResponse) GetProtobufPayload() []byte {
+ if x, ok := m.GetResult().(*ConformanceResponse_ProtobufPayload); ok {
+ return x.ProtobufPayload
+ }
+ return nil
+}
+
+func (m *ConformanceResponse) GetJsonPayload() string {
+ if x, ok := m.GetResult().(*ConformanceResponse_JsonPayload); ok {
+ return x.JsonPayload
+ }
+ return ""
+}
+
+func (m *ConformanceResponse) GetSkipped() string {
+ if x, ok := m.GetResult().(*ConformanceResponse_Skipped); ok {
+ return x.Skipped
+ }
+ return ""
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*ConformanceResponse) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _ConformanceResponse_OneofMarshaler, _ConformanceResponse_OneofUnmarshaler, _ConformanceResponse_OneofSizer, []interface{}{
+ (*ConformanceResponse_ParseError)(nil),
+ (*ConformanceResponse_SerializeError)(nil),
+ (*ConformanceResponse_RuntimeError)(nil),
+ (*ConformanceResponse_ProtobufPayload)(nil),
+ (*ConformanceResponse_JsonPayload)(nil),
+ (*ConformanceResponse_Skipped)(nil),
+ }
+}
+
+func _ConformanceResponse_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*ConformanceResponse)
+ // result
+ switch x := m.Result.(type) {
+ case *ConformanceResponse_ParseError:
+ b.EncodeVarint(1<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.ParseError)
+ case *ConformanceResponse_SerializeError:
+ b.EncodeVarint(6<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.SerializeError)
+ case *ConformanceResponse_RuntimeError:
+ b.EncodeVarint(2<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.RuntimeError)
+ case *ConformanceResponse_ProtobufPayload:
+ b.EncodeVarint(3<<3 | proto.WireBytes)
+ b.EncodeRawBytes(x.ProtobufPayload)
+ case *ConformanceResponse_JsonPayload:
+ b.EncodeVarint(4<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.JsonPayload)
+ case *ConformanceResponse_Skipped:
+ b.EncodeVarint(5<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.Skipped)
+ case nil:
+ default:
+ return fmt.Errorf("ConformanceResponse.Result has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _ConformanceResponse_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*ConformanceResponse)
+ switch tag {
+ case 1: // result.parse_error
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Result = &ConformanceResponse_ParseError{x}
+ return true, err
+ case 6: // result.serialize_error
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Result = &ConformanceResponse_SerializeError{x}
+ return true, err
+ case 2: // result.runtime_error
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Result = &ConformanceResponse_RuntimeError{x}
+ return true, err
+ case 3: // result.protobuf_payload
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeRawBytes(true)
+ m.Result = &ConformanceResponse_ProtobufPayload{x}
+ return true, err
+ case 4: // result.json_payload
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Result = &ConformanceResponse_JsonPayload{x}
+ return true, err
+ case 5: // result.skipped
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Result = &ConformanceResponse_Skipped{x}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _ConformanceResponse_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*ConformanceResponse)
+ // result
+ switch x := m.Result.(type) {
+ case *ConformanceResponse_ParseError:
+ n += proto.SizeVarint(1<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.ParseError)))
+ n += len(x.ParseError)
+ case *ConformanceResponse_SerializeError:
+ n += proto.SizeVarint(6<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.SerializeError)))
+ n += len(x.SerializeError)
+ case *ConformanceResponse_RuntimeError:
+ n += proto.SizeVarint(2<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.RuntimeError)))
+ n += len(x.RuntimeError)
+ case *ConformanceResponse_ProtobufPayload:
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.ProtobufPayload)))
+ n += len(x.ProtobufPayload)
+ case *ConformanceResponse_JsonPayload:
+ n += proto.SizeVarint(4<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.JsonPayload)))
+ n += len(x.JsonPayload)
+ case *ConformanceResponse_Skipped:
+ n += proto.SizeVarint(5<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Skipped)))
+ n += len(x.Skipped)
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// This proto includes every type of field in both singular and repeated
+// forms.
+type TestAllTypes struct {
+ // Singular
+ OptionalInt32 int32 `protobuf:"varint,1,opt,name=optional_int32,json=optionalInt32" json:"optional_int32,omitempty"`
+ OptionalInt64 int64 `protobuf:"varint,2,opt,name=optional_int64,json=optionalInt64" json:"optional_int64,omitempty"`
+ OptionalUint32 uint32 `protobuf:"varint,3,opt,name=optional_uint32,json=optionalUint32" json:"optional_uint32,omitempty"`
+ OptionalUint64 uint64 `protobuf:"varint,4,opt,name=optional_uint64,json=optionalUint64" json:"optional_uint64,omitempty"`
+ OptionalSint32 int32 `protobuf:"zigzag32,5,opt,name=optional_sint32,json=optionalSint32" json:"optional_sint32,omitempty"`
+ OptionalSint64 int64 `protobuf:"zigzag64,6,opt,name=optional_sint64,json=optionalSint64" json:"optional_sint64,omitempty"`
+ OptionalFixed32 uint32 `protobuf:"fixed32,7,opt,name=optional_fixed32,json=optionalFixed32" json:"optional_fixed32,omitempty"`
+ OptionalFixed64 uint64 `protobuf:"fixed64,8,opt,name=optional_fixed64,json=optionalFixed64" json:"optional_fixed64,omitempty"`
+ OptionalSfixed32 int32 `protobuf:"fixed32,9,opt,name=optional_sfixed32,json=optionalSfixed32" json:"optional_sfixed32,omitempty"`
+ OptionalSfixed64 int64 `protobuf:"fixed64,10,opt,name=optional_sfixed64,json=optionalSfixed64" json:"optional_sfixed64,omitempty"`
+ OptionalFloat float32 `protobuf:"fixed32,11,opt,name=optional_float,json=optionalFloat" json:"optional_float,omitempty"`
+ OptionalDouble float64 `protobuf:"fixed64,12,opt,name=optional_double,json=optionalDouble" json:"optional_double,omitempty"`
+ OptionalBool bool `protobuf:"varint,13,opt,name=optional_bool,json=optionalBool" json:"optional_bool,omitempty"`
+ OptionalString string `protobuf:"bytes,14,opt,name=optional_string,json=optionalString" json:"optional_string,omitempty"`
+ OptionalBytes []byte `protobuf:"bytes,15,opt,name=optional_bytes,json=optionalBytes,proto3" json:"optional_bytes,omitempty"`
+ OptionalNestedMessage *TestAllTypes_NestedMessage `protobuf:"bytes,18,opt,name=optional_nested_message,json=optionalNestedMessage" json:"optional_nested_message,omitempty"`
+ OptionalForeignMessage *ForeignMessage `protobuf:"bytes,19,opt,name=optional_foreign_message,json=optionalForeignMessage" json:"optional_foreign_message,omitempty"`
+ OptionalNestedEnum TestAllTypes_NestedEnum `protobuf:"varint,21,opt,name=optional_nested_enum,json=optionalNestedEnum,enum=conformance.TestAllTypes_NestedEnum" json:"optional_nested_enum,omitempty"`
+ OptionalForeignEnum ForeignEnum `protobuf:"varint,22,opt,name=optional_foreign_enum,json=optionalForeignEnum,enum=conformance.ForeignEnum" json:"optional_foreign_enum,omitempty"`
+ OptionalStringPiece string `protobuf:"bytes,24,opt,name=optional_string_piece,json=optionalStringPiece" json:"optional_string_piece,omitempty"`
+ OptionalCord string `protobuf:"bytes,25,opt,name=optional_cord,json=optionalCord" json:"optional_cord,omitempty"`
+ RecursiveMessage *TestAllTypes `protobuf:"bytes,27,opt,name=recursive_message,json=recursiveMessage" json:"recursive_message,omitempty"`
+ // Repeated
+ RepeatedInt32 []int32 `protobuf:"varint,31,rep,packed,name=repeated_int32,json=repeatedInt32" json:"repeated_int32,omitempty"`
+ RepeatedInt64 []int64 `protobuf:"varint,32,rep,packed,name=repeated_int64,json=repeatedInt64" json:"repeated_int64,omitempty"`
+ RepeatedUint32 []uint32 `protobuf:"varint,33,rep,packed,name=repeated_uint32,json=repeatedUint32" json:"repeated_uint32,omitempty"`
+ RepeatedUint64 []uint64 `protobuf:"varint,34,rep,packed,name=repeated_uint64,json=repeatedUint64" json:"repeated_uint64,omitempty"`
+ RepeatedSint32 []int32 `protobuf:"zigzag32,35,rep,packed,name=repeated_sint32,json=repeatedSint32" json:"repeated_sint32,omitempty"`
+ RepeatedSint64 []int64 `protobuf:"zigzag64,36,rep,packed,name=repeated_sint64,json=repeatedSint64" json:"repeated_sint64,omitempty"`
+ RepeatedFixed32 []uint32 `protobuf:"fixed32,37,rep,packed,name=repeated_fixed32,json=repeatedFixed32" json:"repeated_fixed32,omitempty"`
+ RepeatedFixed64 []uint64 `protobuf:"fixed64,38,rep,packed,name=repeated_fixed64,json=repeatedFixed64" json:"repeated_fixed64,omitempty"`
+ RepeatedSfixed32 []int32 `protobuf:"fixed32,39,rep,packed,name=repeated_sfixed32,json=repeatedSfixed32" json:"repeated_sfixed32,omitempty"`
+ RepeatedSfixed64 []int64 `protobuf:"fixed64,40,rep,packed,name=repeated_sfixed64,json=repeatedSfixed64" json:"repeated_sfixed64,omitempty"`
+ RepeatedFloat []float32 `protobuf:"fixed32,41,rep,packed,name=repeated_float,json=repeatedFloat" json:"repeated_float,omitempty"`
+ RepeatedDouble []float64 `protobuf:"fixed64,42,rep,packed,name=repeated_double,json=repeatedDouble" json:"repeated_double,omitempty"`
+ RepeatedBool []bool `protobuf:"varint,43,rep,packed,name=repeated_bool,json=repeatedBool" json:"repeated_bool,omitempty"`
+ RepeatedString []string `protobuf:"bytes,44,rep,name=repeated_string,json=repeatedString" json:"repeated_string,omitempty"`
+ RepeatedBytes [][]byte `protobuf:"bytes,45,rep,name=repeated_bytes,json=repeatedBytes,proto3" json:"repeated_bytes,omitempty"`
+ RepeatedNestedMessage []*TestAllTypes_NestedMessage `protobuf:"bytes,48,rep,name=repeated_nested_message,json=repeatedNestedMessage" json:"repeated_nested_message,omitempty"`
+ RepeatedForeignMessage []*ForeignMessage `protobuf:"bytes,49,rep,name=repeated_foreign_message,json=repeatedForeignMessage" json:"repeated_foreign_message,omitempty"`
+ RepeatedNestedEnum []TestAllTypes_NestedEnum `protobuf:"varint,51,rep,packed,name=repeated_nested_enum,json=repeatedNestedEnum,enum=conformance.TestAllTypes_NestedEnum" json:"repeated_nested_enum,omitempty"`
+ RepeatedForeignEnum []ForeignEnum `protobuf:"varint,52,rep,packed,name=repeated_foreign_enum,json=repeatedForeignEnum,enum=conformance.ForeignEnum" json:"repeated_foreign_enum,omitempty"`
+ RepeatedStringPiece []string `protobuf:"bytes,54,rep,name=repeated_string_piece,json=repeatedStringPiece" json:"repeated_string_piece,omitempty"`
+ RepeatedCord []string `protobuf:"bytes,55,rep,name=repeated_cord,json=repeatedCord" json:"repeated_cord,omitempty"`
+ // Map
+ MapInt32Int32 map[int32]int32 `protobuf:"bytes,56,rep,name=map_int32_int32,json=mapInt32Int32" json:"map_int32_int32,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+ MapInt64Int64 map[int64]int64 `protobuf:"bytes,57,rep,name=map_int64_int64,json=mapInt64Int64" json:"map_int64_int64,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+ MapUint32Uint32 map[uint32]uint32 `protobuf:"bytes,58,rep,name=map_uint32_uint32,json=mapUint32Uint32" json:"map_uint32_uint32,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+ MapUint64Uint64 map[uint64]uint64 `protobuf:"bytes,59,rep,name=map_uint64_uint64,json=mapUint64Uint64" json:"map_uint64_uint64,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+ MapSint32Sint32 map[int32]int32 `protobuf:"bytes,60,rep,name=map_sint32_sint32,json=mapSint32Sint32" json:"map_sint32_sint32,omitempty" protobuf_key:"zigzag32,1,opt,name=key" protobuf_val:"zigzag32,2,opt,name=value"`
+ MapSint64Sint64 map[int64]int64 `protobuf:"bytes,61,rep,name=map_sint64_sint64,json=mapSint64Sint64" json:"map_sint64_sint64,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"zigzag64,2,opt,name=value"`
+ MapFixed32Fixed32 map[uint32]uint32 `protobuf:"bytes,62,rep,name=map_fixed32_fixed32,json=mapFixed32Fixed32" json:"map_fixed32_fixed32,omitempty" protobuf_key:"fixed32,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"`
+ MapFixed64Fixed64 map[uint64]uint64 `protobuf:"bytes,63,rep,name=map_fixed64_fixed64,json=mapFixed64Fixed64" json:"map_fixed64_fixed64,omitempty" protobuf_key:"fixed64,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"`
+ MapSfixed32Sfixed32 map[int32]int32 `protobuf:"bytes,64,rep,name=map_sfixed32_sfixed32,json=mapSfixed32Sfixed32" json:"map_sfixed32_sfixed32,omitempty" protobuf_key:"fixed32,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"`
+ MapSfixed64Sfixed64 map[int64]int64 `protobuf:"bytes,65,rep,name=map_sfixed64_sfixed64,json=mapSfixed64Sfixed64" json:"map_sfixed64_sfixed64,omitempty" protobuf_key:"fixed64,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"`
+ MapInt32Float map[int32]float32 `protobuf:"bytes,66,rep,name=map_int32_float,json=mapInt32Float" json:"map_int32_float,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"fixed32,2,opt,name=value"`
+ MapInt32Double map[int32]float64 `protobuf:"bytes,67,rep,name=map_int32_double,json=mapInt32Double" json:"map_int32_double,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"fixed64,2,opt,name=value"`
+ MapBoolBool map[bool]bool `protobuf:"bytes,68,rep,name=map_bool_bool,json=mapBoolBool" json:"map_bool_bool,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+ MapStringString map[string]string `protobuf:"bytes,69,rep,name=map_string_string,json=mapStringString" json:"map_string_string,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ MapStringBytes map[string][]byte `protobuf:"bytes,70,rep,name=map_string_bytes,json=mapStringBytes" json:"map_string_bytes,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ MapStringNestedMessage map[string]*TestAllTypes_NestedMessage `protobuf:"bytes,71,rep,name=map_string_nested_message,json=mapStringNestedMessage" json:"map_string_nested_message,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ MapStringForeignMessage map[string]*ForeignMessage `protobuf:"bytes,72,rep,name=map_string_foreign_message,json=mapStringForeignMessage" json:"map_string_foreign_message,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ MapStringNestedEnum map[string]TestAllTypes_NestedEnum `protobuf:"bytes,73,rep,name=map_string_nested_enum,json=mapStringNestedEnum" json:"map_string_nested_enum,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=conformance.TestAllTypes_NestedEnum"`
+ MapStringForeignEnum map[string]ForeignEnum `protobuf:"bytes,74,rep,name=map_string_foreign_enum,json=mapStringForeignEnum" json:"map_string_foreign_enum,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=conformance.ForeignEnum"`
+ // Types that are valid to be assigned to OneofField:
+ // *TestAllTypes_OneofUint32
+ // *TestAllTypes_OneofNestedMessage
+ // *TestAllTypes_OneofString
+ // *TestAllTypes_OneofBytes
+ // *TestAllTypes_OneofBool
+ // *TestAllTypes_OneofUint64
+ // *TestAllTypes_OneofFloat
+ // *TestAllTypes_OneofDouble
+ // *TestAllTypes_OneofEnum
+ OneofField isTestAllTypes_OneofField `protobuf_oneof:"oneof_field"`
+ // Well-known types
+ OptionalBoolWrapper *google_protobuf5.BoolValue `protobuf:"bytes,201,opt,name=optional_bool_wrapper,json=optionalBoolWrapper" json:"optional_bool_wrapper,omitempty"`
+ OptionalInt32Wrapper *google_protobuf5.Int32Value `protobuf:"bytes,202,opt,name=optional_int32_wrapper,json=optionalInt32Wrapper" json:"optional_int32_wrapper,omitempty"`
+ OptionalInt64Wrapper *google_protobuf5.Int64Value `protobuf:"bytes,203,opt,name=optional_int64_wrapper,json=optionalInt64Wrapper" json:"optional_int64_wrapper,omitempty"`
+ OptionalUint32Wrapper *google_protobuf5.UInt32Value `protobuf:"bytes,204,opt,name=optional_uint32_wrapper,json=optionalUint32Wrapper" json:"optional_uint32_wrapper,omitempty"`
+ OptionalUint64Wrapper *google_protobuf5.UInt64Value `protobuf:"bytes,205,opt,name=optional_uint64_wrapper,json=optionalUint64Wrapper" json:"optional_uint64_wrapper,omitempty"`
+ OptionalFloatWrapper *google_protobuf5.FloatValue `protobuf:"bytes,206,opt,name=optional_float_wrapper,json=optionalFloatWrapper" json:"optional_float_wrapper,omitempty"`
+ OptionalDoubleWrapper *google_protobuf5.DoubleValue `protobuf:"bytes,207,opt,name=optional_double_wrapper,json=optionalDoubleWrapper" json:"optional_double_wrapper,omitempty"`
+ OptionalStringWrapper *google_protobuf5.StringValue `protobuf:"bytes,208,opt,name=optional_string_wrapper,json=optionalStringWrapper" json:"optional_string_wrapper,omitempty"`
+ OptionalBytesWrapper *google_protobuf5.BytesValue `protobuf:"bytes,209,opt,name=optional_bytes_wrapper,json=optionalBytesWrapper" json:"optional_bytes_wrapper,omitempty"`
+ RepeatedBoolWrapper []*google_protobuf5.BoolValue `protobuf:"bytes,211,rep,name=repeated_bool_wrapper,json=repeatedBoolWrapper" json:"repeated_bool_wrapper,omitempty"`
+ RepeatedInt32Wrapper []*google_protobuf5.Int32Value `protobuf:"bytes,212,rep,name=repeated_int32_wrapper,json=repeatedInt32Wrapper" json:"repeated_int32_wrapper,omitempty"`
+ RepeatedInt64Wrapper []*google_protobuf5.Int64Value `protobuf:"bytes,213,rep,name=repeated_int64_wrapper,json=repeatedInt64Wrapper" json:"repeated_int64_wrapper,omitempty"`
+ RepeatedUint32Wrapper []*google_protobuf5.UInt32Value `protobuf:"bytes,214,rep,name=repeated_uint32_wrapper,json=repeatedUint32Wrapper" json:"repeated_uint32_wrapper,omitempty"`
+ RepeatedUint64Wrapper []*google_protobuf5.UInt64Value `protobuf:"bytes,215,rep,name=repeated_uint64_wrapper,json=repeatedUint64Wrapper" json:"repeated_uint64_wrapper,omitempty"`
+ RepeatedFloatWrapper []*google_protobuf5.FloatValue `protobuf:"bytes,216,rep,name=repeated_float_wrapper,json=repeatedFloatWrapper" json:"repeated_float_wrapper,omitempty"`
+ RepeatedDoubleWrapper []*google_protobuf5.DoubleValue `protobuf:"bytes,217,rep,name=repeated_double_wrapper,json=repeatedDoubleWrapper" json:"repeated_double_wrapper,omitempty"`
+ RepeatedStringWrapper []*google_protobuf5.StringValue `protobuf:"bytes,218,rep,name=repeated_string_wrapper,json=repeatedStringWrapper" json:"repeated_string_wrapper,omitempty"`
+ RepeatedBytesWrapper []*google_protobuf5.BytesValue `protobuf:"bytes,219,rep,name=repeated_bytes_wrapper,json=repeatedBytesWrapper" json:"repeated_bytes_wrapper,omitempty"`
+ OptionalDuration *google_protobuf1.Duration `protobuf:"bytes,301,opt,name=optional_duration,json=optionalDuration" json:"optional_duration,omitempty"`
+ OptionalTimestamp *google_protobuf4.Timestamp `protobuf:"bytes,302,opt,name=optional_timestamp,json=optionalTimestamp" json:"optional_timestamp,omitempty"`
+ OptionalFieldMask *google_protobuf2.FieldMask `protobuf:"bytes,303,opt,name=optional_field_mask,json=optionalFieldMask" json:"optional_field_mask,omitempty"`
+ OptionalStruct *google_protobuf3.Struct `protobuf:"bytes,304,opt,name=optional_struct,json=optionalStruct" json:"optional_struct,omitempty"`
+ OptionalAny *google_protobuf.Any `protobuf:"bytes,305,opt,name=optional_any,json=optionalAny" json:"optional_any,omitempty"`
+ OptionalValue *google_protobuf3.Value `protobuf:"bytes,306,opt,name=optional_value,json=optionalValue" json:"optional_value,omitempty"`
+ RepeatedDuration []*google_protobuf1.Duration `protobuf:"bytes,311,rep,name=repeated_duration,json=repeatedDuration" json:"repeated_duration,omitempty"`
+ RepeatedTimestamp []*google_protobuf4.Timestamp `protobuf:"bytes,312,rep,name=repeated_timestamp,json=repeatedTimestamp" json:"repeated_timestamp,omitempty"`
+ RepeatedFieldmask []*google_protobuf2.FieldMask `protobuf:"bytes,313,rep,name=repeated_fieldmask,json=repeatedFieldmask" json:"repeated_fieldmask,omitempty"`
+ RepeatedStruct []*google_protobuf3.Struct `protobuf:"bytes,324,rep,name=repeated_struct,json=repeatedStruct" json:"repeated_struct,omitempty"`
+ RepeatedAny []*google_protobuf.Any `protobuf:"bytes,315,rep,name=repeated_any,json=repeatedAny" json:"repeated_any,omitempty"`
+ RepeatedValue []*google_protobuf3.Value `protobuf:"bytes,316,rep,name=repeated_value,json=repeatedValue" json:"repeated_value,omitempty"`
+ // Test field-name-to-JSON-name convention.
+ // (protobuf says names can be any valid C/C++ identifier.)
+ Fieldname1 int32 `protobuf:"varint,401,opt,name=fieldname1" json:"fieldname1,omitempty"`
+ FieldName2 int32 `protobuf:"varint,402,opt,name=field_name2,json=fieldName2" json:"field_name2,omitempty"`
+ XFieldName3 int32 `protobuf:"varint,403,opt,name=_field_name3,json=FieldName3" json:"_field_name3,omitempty"`
+ Field_Name4_ int32 `protobuf:"varint,404,opt,name=field__name4_,json=fieldName4" json:"field__name4_,omitempty"`
+ Field0Name5 int32 `protobuf:"varint,405,opt,name=field0name5" json:"field0name5,omitempty"`
+ Field_0Name6 int32 `protobuf:"varint,406,opt,name=field_0_name6,json=field0Name6" json:"field_0_name6,omitempty"`
+ FieldName7 int32 `protobuf:"varint,407,opt,name=fieldName7" json:"fieldName7,omitempty"`
+ FieldName8 int32 `protobuf:"varint,408,opt,name=FieldName8" json:"FieldName8,omitempty"`
+ Field_Name9 int32 `protobuf:"varint,409,opt,name=field_Name9,json=fieldName9" json:"field_Name9,omitempty"`
+ Field_Name10 int32 `protobuf:"varint,410,opt,name=Field_Name10,json=FieldName10" json:"Field_Name10,omitempty"`
+ FIELD_NAME11 int32 `protobuf:"varint,411,opt,name=FIELD_NAME11,json=FIELDNAME11" json:"FIELD_NAME11,omitempty"`
+ FIELDName12 int32 `protobuf:"varint,412,opt,name=FIELD_name12,json=FIELDName12" json:"FIELD_name12,omitempty"`
+ XFieldName13 int32 `protobuf:"varint,413,opt,name=__field_name13,json=FieldName13" json:"__field_name13,omitempty"`
+ X_FieldName14 int32 `protobuf:"varint,414,opt,name=__Field_name14,json=FieldName14" json:"__Field_name14,omitempty"`
+ Field_Name15 int32 `protobuf:"varint,415,opt,name=field__name15,json=fieldName15" json:"field__name15,omitempty"`
+ Field__Name16 int32 `protobuf:"varint,416,opt,name=field__Name16,json=fieldName16" json:"field__Name16,omitempty"`
+ FieldName17__ int32 `protobuf:"varint,417,opt,name=field_name17__,json=fieldName17" json:"field_name17__,omitempty"`
+ FieldName18__ int32 `protobuf:"varint,418,opt,name=Field_name18__,json=FieldName18" json:"Field_name18__,omitempty"`
+}
+
+func (m *TestAllTypes) Reset() { *m = TestAllTypes{} }
+func (m *TestAllTypes) String() string { return proto.CompactTextString(m) }
+func (*TestAllTypes) ProtoMessage() {}
+func (*TestAllTypes) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
+
+type isTestAllTypes_OneofField interface {
+ isTestAllTypes_OneofField()
+}
+
+type TestAllTypes_OneofUint32 struct {
+ OneofUint32 uint32 `protobuf:"varint,111,opt,name=oneof_uint32,json=oneofUint32,oneof"`
+}
+type TestAllTypes_OneofNestedMessage struct {
+ OneofNestedMessage *TestAllTypes_NestedMessage `protobuf:"bytes,112,opt,name=oneof_nested_message,json=oneofNestedMessage,oneof"`
+}
+type TestAllTypes_OneofString struct {
+ OneofString string `protobuf:"bytes,113,opt,name=oneof_string,json=oneofString,oneof"`
+}
+type TestAllTypes_OneofBytes struct {
+ OneofBytes []byte `protobuf:"bytes,114,opt,name=oneof_bytes,json=oneofBytes,proto3,oneof"`
+}
+type TestAllTypes_OneofBool struct {
+ OneofBool bool `protobuf:"varint,115,opt,name=oneof_bool,json=oneofBool,oneof"`
+}
+type TestAllTypes_OneofUint64 struct {
+ OneofUint64 uint64 `protobuf:"varint,116,opt,name=oneof_uint64,json=oneofUint64,oneof"`
+}
+type TestAllTypes_OneofFloat struct {
+ OneofFloat float32 `protobuf:"fixed32,117,opt,name=oneof_float,json=oneofFloat,oneof"`
+}
+type TestAllTypes_OneofDouble struct {
+ OneofDouble float64 `protobuf:"fixed64,118,opt,name=oneof_double,json=oneofDouble,oneof"`
+}
+type TestAllTypes_OneofEnum struct {
+ OneofEnum TestAllTypes_NestedEnum `protobuf:"varint,119,opt,name=oneof_enum,json=oneofEnum,enum=conformance.TestAllTypes_NestedEnum,oneof"`
+}
+
+func (*TestAllTypes_OneofUint32) isTestAllTypes_OneofField() {}
+func (*TestAllTypes_OneofNestedMessage) isTestAllTypes_OneofField() {}
+func (*TestAllTypes_OneofString) isTestAllTypes_OneofField() {}
+func (*TestAllTypes_OneofBytes) isTestAllTypes_OneofField() {}
+func (*TestAllTypes_OneofBool) isTestAllTypes_OneofField() {}
+func (*TestAllTypes_OneofUint64) isTestAllTypes_OneofField() {}
+func (*TestAllTypes_OneofFloat) isTestAllTypes_OneofField() {}
+func (*TestAllTypes_OneofDouble) isTestAllTypes_OneofField() {}
+func (*TestAllTypes_OneofEnum) isTestAllTypes_OneofField() {}
+
+func (m *TestAllTypes) GetOneofField() isTestAllTypes_OneofField {
+ if m != nil {
+ return m.OneofField
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalInt32() int32 {
+ if m != nil {
+ return m.OptionalInt32
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOptionalInt64() int64 {
+ if m != nil {
+ return m.OptionalInt64
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOptionalUint32() uint32 {
+ if m != nil {
+ return m.OptionalUint32
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOptionalUint64() uint64 {
+ if m != nil {
+ return m.OptionalUint64
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOptionalSint32() int32 {
+ if m != nil {
+ return m.OptionalSint32
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOptionalSint64() int64 {
+ if m != nil {
+ return m.OptionalSint64
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOptionalFixed32() uint32 {
+ if m != nil {
+ return m.OptionalFixed32
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOptionalFixed64() uint64 {
+ if m != nil {
+ return m.OptionalFixed64
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOptionalSfixed32() int32 {
+ if m != nil {
+ return m.OptionalSfixed32
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOptionalSfixed64() int64 {
+ if m != nil {
+ return m.OptionalSfixed64
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOptionalFloat() float32 {
+ if m != nil {
+ return m.OptionalFloat
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOptionalDouble() float64 {
+ if m != nil {
+ return m.OptionalDouble
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOptionalBool() bool {
+ if m != nil {
+ return m.OptionalBool
+ }
+ return false
+}
+
+func (m *TestAllTypes) GetOptionalString() string {
+ if m != nil {
+ return m.OptionalString
+ }
+ return ""
+}
+
+func (m *TestAllTypes) GetOptionalBytes() []byte {
+ if m != nil {
+ return m.OptionalBytes
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalNestedMessage() *TestAllTypes_NestedMessage {
+ if m != nil {
+ return m.OptionalNestedMessage
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalForeignMessage() *ForeignMessage {
+ if m != nil {
+ return m.OptionalForeignMessage
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalNestedEnum() TestAllTypes_NestedEnum {
+ if m != nil {
+ return m.OptionalNestedEnum
+ }
+ return TestAllTypes_FOO
+}
+
+func (m *TestAllTypes) GetOptionalForeignEnum() ForeignEnum {
+ if m != nil {
+ return m.OptionalForeignEnum
+ }
+ return ForeignEnum_FOREIGN_FOO
+}
+
+func (m *TestAllTypes) GetOptionalStringPiece() string {
+ if m != nil {
+ return m.OptionalStringPiece
+ }
+ return ""
+}
+
+func (m *TestAllTypes) GetOptionalCord() string {
+ if m != nil {
+ return m.OptionalCord
+ }
+ return ""
+}
+
+func (m *TestAllTypes) GetRecursiveMessage() *TestAllTypes {
+ if m != nil {
+ return m.RecursiveMessage
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedInt32() []int32 {
+ if m != nil {
+ return m.RepeatedInt32
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedInt64() []int64 {
+ if m != nil {
+ return m.RepeatedInt64
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedUint32() []uint32 {
+ if m != nil {
+ return m.RepeatedUint32
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedUint64() []uint64 {
+ if m != nil {
+ return m.RepeatedUint64
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedSint32() []int32 {
+ if m != nil {
+ return m.RepeatedSint32
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedSint64() []int64 {
+ if m != nil {
+ return m.RepeatedSint64
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedFixed32() []uint32 {
+ if m != nil {
+ return m.RepeatedFixed32
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedFixed64() []uint64 {
+ if m != nil {
+ return m.RepeatedFixed64
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedSfixed32() []int32 {
+ if m != nil {
+ return m.RepeatedSfixed32
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedSfixed64() []int64 {
+ if m != nil {
+ return m.RepeatedSfixed64
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedFloat() []float32 {
+ if m != nil {
+ return m.RepeatedFloat
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedDouble() []float64 {
+ if m != nil {
+ return m.RepeatedDouble
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedBool() []bool {
+ if m != nil {
+ return m.RepeatedBool
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedString() []string {
+ if m != nil {
+ return m.RepeatedString
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedBytes() [][]byte {
+ if m != nil {
+ return m.RepeatedBytes
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedNestedMessage() []*TestAllTypes_NestedMessage {
+ if m != nil {
+ return m.RepeatedNestedMessage
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedForeignMessage() []*ForeignMessage {
+ if m != nil {
+ return m.RepeatedForeignMessage
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedNestedEnum() []TestAllTypes_NestedEnum {
+ if m != nil {
+ return m.RepeatedNestedEnum
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedForeignEnum() []ForeignEnum {
+ if m != nil {
+ return m.RepeatedForeignEnum
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedStringPiece() []string {
+ if m != nil {
+ return m.RepeatedStringPiece
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedCord() []string {
+ if m != nil {
+ return m.RepeatedCord
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapInt32Int32() map[int32]int32 {
+ if m != nil {
+ return m.MapInt32Int32
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapInt64Int64() map[int64]int64 {
+ if m != nil {
+ return m.MapInt64Int64
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapUint32Uint32() map[uint32]uint32 {
+ if m != nil {
+ return m.MapUint32Uint32
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapUint64Uint64() map[uint64]uint64 {
+ if m != nil {
+ return m.MapUint64Uint64
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapSint32Sint32() map[int32]int32 {
+ if m != nil {
+ return m.MapSint32Sint32
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapSint64Sint64() map[int64]int64 {
+ if m != nil {
+ return m.MapSint64Sint64
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapFixed32Fixed32() map[uint32]uint32 {
+ if m != nil {
+ return m.MapFixed32Fixed32
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapFixed64Fixed64() map[uint64]uint64 {
+ if m != nil {
+ return m.MapFixed64Fixed64
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapSfixed32Sfixed32() map[int32]int32 {
+ if m != nil {
+ return m.MapSfixed32Sfixed32
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapSfixed64Sfixed64() map[int64]int64 {
+ if m != nil {
+ return m.MapSfixed64Sfixed64
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapInt32Float() map[int32]float32 {
+ if m != nil {
+ return m.MapInt32Float
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapInt32Double() map[int32]float64 {
+ if m != nil {
+ return m.MapInt32Double
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapBoolBool() map[bool]bool {
+ if m != nil {
+ return m.MapBoolBool
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapStringString() map[string]string {
+ if m != nil {
+ return m.MapStringString
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapStringBytes() map[string][]byte {
+ if m != nil {
+ return m.MapStringBytes
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapStringNestedMessage() map[string]*TestAllTypes_NestedMessage {
+ if m != nil {
+ return m.MapStringNestedMessage
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapStringForeignMessage() map[string]*ForeignMessage {
+ if m != nil {
+ return m.MapStringForeignMessage
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapStringNestedEnum() map[string]TestAllTypes_NestedEnum {
+ if m != nil {
+ return m.MapStringNestedEnum
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetMapStringForeignEnum() map[string]ForeignEnum {
+ if m != nil {
+ return m.MapStringForeignEnum
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOneofUint32() uint32 {
+ if x, ok := m.GetOneofField().(*TestAllTypes_OneofUint32); ok {
+ return x.OneofUint32
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOneofNestedMessage() *TestAllTypes_NestedMessage {
+ if x, ok := m.GetOneofField().(*TestAllTypes_OneofNestedMessage); ok {
+ return x.OneofNestedMessage
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOneofString() string {
+ if x, ok := m.GetOneofField().(*TestAllTypes_OneofString); ok {
+ return x.OneofString
+ }
+ return ""
+}
+
+func (m *TestAllTypes) GetOneofBytes() []byte {
+ if x, ok := m.GetOneofField().(*TestAllTypes_OneofBytes); ok {
+ return x.OneofBytes
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOneofBool() bool {
+ if x, ok := m.GetOneofField().(*TestAllTypes_OneofBool); ok {
+ return x.OneofBool
+ }
+ return false
+}
+
+func (m *TestAllTypes) GetOneofUint64() uint64 {
+ if x, ok := m.GetOneofField().(*TestAllTypes_OneofUint64); ok {
+ return x.OneofUint64
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOneofFloat() float32 {
+ if x, ok := m.GetOneofField().(*TestAllTypes_OneofFloat); ok {
+ return x.OneofFloat
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOneofDouble() float64 {
+ if x, ok := m.GetOneofField().(*TestAllTypes_OneofDouble); ok {
+ return x.OneofDouble
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetOneofEnum() TestAllTypes_NestedEnum {
+ if x, ok := m.GetOneofField().(*TestAllTypes_OneofEnum); ok {
+ return x.OneofEnum
+ }
+ return TestAllTypes_FOO
+}
+
+func (m *TestAllTypes) GetOptionalBoolWrapper() *google_protobuf5.BoolValue {
+ if m != nil {
+ return m.OptionalBoolWrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalInt32Wrapper() *google_protobuf5.Int32Value {
+ if m != nil {
+ return m.OptionalInt32Wrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalInt64Wrapper() *google_protobuf5.Int64Value {
+ if m != nil {
+ return m.OptionalInt64Wrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalUint32Wrapper() *google_protobuf5.UInt32Value {
+ if m != nil {
+ return m.OptionalUint32Wrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalUint64Wrapper() *google_protobuf5.UInt64Value {
+ if m != nil {
+ return m.OptionalUint64Wrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalFloatWrapper() *google_protobuf5.FloatValue {
+ if m != nil {
+ return m.OptionalFloatWrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalDoubleWrapper() *google_protobuf5.DoubleValue {
+ if m != nil {
+ return m.OptionalDoubleWrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalStringWrapper() *google_protobuf5.StringValue {
+ if m != nil {
+ return m.OptionalStringWrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalBytesWrapper() *google_protobuf5.BytesValue {
+ if m != nil {
+ return m.OptionalBytesWrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedBoolWrapper() []*google_protobuf5.BoolValue {
+ if m != nil {
+ return m.RepeatedBoolWrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedInt32Wrapper() []*google_protobuf5.Int32Value {
+ if m != nil {
+ return m.RepeatedInt32Wrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedInt64Wrapper() []*google_protobuf5.Int64Value {
+ if m != nil {
+ return m.RepeatedInt64Wrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedUint32Wrapper() []*google_protobuf5.UInt32Value {
+ if m != nil {
+ return m.RepeatedUint32Wrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedUint64Wrapper() []*google_protobuf5.UInt64Value {
+ if m != nil {
+ return m.RepeatedUint64Wrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedFloatWrapper() []*google_protobuf5.FloatValue {
+ if m != nil {
+ return m.RepeatedFloatWrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedDoubleWrapper() []*google_protobuf5.DoubleValue {
+ if m != nil {
+ return m.RepeatedDoubleWrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedStringWrapper() []*google_protobuf5.StringValue {
+ if m != nil {
+ return m.RepeatedStringWrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedBytesWrapper() []*google_protobuf5.BytesValue {
+ if m != nil {
+ return m.RepeatedBytesWrapper
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalDuration() *google_protobuf1.Duration {
+ if m != nil {
+ return m.OptionalDuration
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalTimestamp() *google_protobuf4.Timestamp {
+ if m != nil {
+ return m.OptionalTimestamp
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalFieldMask() *google_protobuf2.FieldMask {
+ if m != nil {
+ return m.OptionalFieldMask
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalStruct() *google_protobuf3.Struct {
+ if m != nil {
+ return m.OptionalStruct
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalAny() *google_protobuf.Any {
+ if m != nil {
+ return m.OptionalAny
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetOptionalValue() *google_protobuf3.Value {
+ if m != nil {
+ return m.OptionalValue
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedDuration() []*google_protobuf1.Duration {
+ if m != nil {
+ return m.RepeatedDuration
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedTimestamp() []*google_protobuf4.Timestamp {
+ if m != nil {
+ return m.RepeatedTimestamp
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedFieldmask() []*google_protobuf2.FieldMask {
+ if m != nil {
+ return m.RepeatedFieldmask
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedStruct() []*google_protobuf3.Struct {
+ if m != nil {
+ return m.RepeatedStruct
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedAny() []*google_protobuf.Any {
+ if m != nil {
+ return m.RepeatedAny
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetRepeatedValue() []*google_protobuf3.Value {
+ if m != nil {
+ return m.RepeatedValue
+ }
+ return nil
+}
+
+func (m *TestAllTypes) GetFieldname1() int32 {
+ if m != nil {
+ return m.Fieldname1
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetFieldName2() int32 {
+ if m != nil {
+ return m.FieldName2
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetXFieldName3() int32 {
+ if m != nil {
+ return m.XFieldName3
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetField_Name4_() int32 {
+ if m != nil {
+ return m.Field_Name4_
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetField0Name5() int32 {
+ if m != nil {
+ return m.Field0Name5
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetField_0Name6() int32 {
+ if m != nil {
+ return m.Field_0Name6
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetFieldName7() int32 {
+ if m != nil {
+ return m.FieldName7
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetFieldName8() int32 {
+ if m != nil {
+ return m.FieldName8
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetField_Name9() int32 {
+ if m != nil {
+ return m.Field_Name9
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetField_Name10() int32 {
+ if m != nil {
+ return m.Field_Name10
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetFIELD_NAME11() int32 {
+ if m != nil {
+ return m.FIELD_NAME11
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetFIELDName12() int32 {
+ if m != nil {
+ return m.FIELDName12
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetXFieldName13() int32 {
+ if m != nil {
+ return m.XFieldName13
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetX_FieldName14() int32 {
+ if m != nil {
+ return m.X_FieldName14
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetField_Name15() int32 {
+ if m != nil {
+ return m.Field_Name15
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetField__Name16() int32 {
+ if m != nil {
+ return m.Field__Name16
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetFieldName17__() int32 {
+ if m != nil {
+ return m.FieldName17__
+ }
+ return 0
+}
+
+func (m *TestAllTypes) GetFieldName18__() int32 {
+ if m != nil {
+ return m.FieldName18__
+ }
+ return 0
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*TestAllTypes) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _TestAllTypes_OneofMarshaler, _TestAllTypes_OneofUnmarshaler, _TestAllTypes_OneofSizer, []interface{}{
+ (*TestAllTypes_OneofUint32)(nil),
+ (*TestAllTypes_OneofNestedMessage)(nil),
+ (*TestAllTypes_OneofString)(nil),
+ (*TestAllTypes_OneofBytes)(nil),
+ (*TestAllTypes_OneofBool)(nil),
+ (*TestAllTypes_OneofUint64)(nil),
+ (*TestAllTypes_OneofFloat)(nil),
+ (*TestAllTypes_OneofDouble)(nil),
+ (*TestAllTypes_OneofEnum)(nil),
+ }
+}
+
+func _TestAllTypes_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*TestAllTypes)
+ // oneof_field
+ switch x := m.OneofField.(type) {
+ case *TestAllTypes_OneofUint32:
+ b.EncodeVarint(111<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.OneofUint32))
+ case *TestAllTypes_OneofNestedMessage:
+ b.EncodeVarint(112<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.OneofNestedMessage); err != nil {
+ return err
+ }
+ case *TestAllTypes_OneofString:
+ b.EncodeVarint(113<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.OneofString)
+ case *TestAllTypes_OneofBytes:
+ b.EncodeVarint(114<<3 | proto.WireBytes)
+ b.EncodeRawBytes(x.OneofBytes)
+ case *TestAllTypes_OneofBool:
+ t := uint64(0)
+ if x.OneofBool {
+ t = 1
+ }
+ b.EncodeVarint(115<<3 | proto.WireVarint)
+ b.EncodeVarint(t)
+ case *TestAllTypes_OneofUint64:
+ b.EncodeVarint(116<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.OneofUint64))
+ case *TestAllTypes_OneofFloat:
+ b.EncodeVarint(117<<3 | proto.WireFixed32)
+ b.EncodeFixed32(uint64(math.Float32bits(x.OneofFloat)))
+ case *TestAllTypes_OneofDouble:
+ b.EncodeVarint(118<<3 | proto.WireFixed64)
+ b.EncodeFixed64(math.Float64bits(x.OneofDouble))
+ case *TestAllTypes_OneofEnum:
+ b.EncodeVarint(119<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.OneofEnum))
+ case nil:
+ default:
+ return fmt.Errorf("TestAllTypes.OneofField has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _TestAllTypes_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*TestAllTypes)
+ switch tag {
+ case 111: // oneof_field.oneof_uint32
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.OneofField = &TestAllTypes_OneofUint32{uint32(x)}
+ return true, err
+ case 112: // oneof_field.oneof_nested_message
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(TestAllTypes_NestedMessage)
+ err := b.DecodeMessage(msg)
+ m.OneofField = &TestAllTypes_OneofNestedMessage{msg}
+ return true, err
+ case 113: // oneof_field.oneof_string
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.OneofField = &TestAllTypes_OneofString{x}
+ return true, err
+ case 114: // oneof_field.oneof_bytes
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeRawBytes(true)
+ m.OneofField = &TestAllTypes_OneofBytes{x}
+ return true, err
+ case 115: // oneof_field.oneof_bool
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.OneofField = &TestAllTypes_OneofBool{x != 0}
+ return true, err
+ case 116: // oneof_field.oneof_uint64
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.OneofField = &TestAllTypes_OneofUint64{x}
+ return true, err
+ case 117: // oneof_field.oneof_float
+ if wire != proto.WireFixed32 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed32()
+ m.OneofField = &TestAllTypes_OneofFloat{math.Float32frombits(uint32(x))}
+ return true, err
+ case 118: // oneof_field.oneof_double
+ if wire != proto.WireFixed64 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed64()
+ m.OneofField = &TestAllTypes_OneofDouble{math.Float64frombits(x)}
+ return true, err
+ case 119: // oneof_field.oneof_enum
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.OneofField = &TestAllTypes_OneofEnum{TestAllTypes_NestedEnum(x)}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _TestAllTypes_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*TestAllTypes)
+ // oneof_field
+ switch x := m.OneofField.(type) {
+ case *TestAllTypes_OneofUint32:
+ n += proto.SizeVarint(111<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.OneofUint32))
+ case *TestAllTypes_OneofNestedMessage:
+ s := proto.Size(x.OneofNestedMessage)
+ n += proto.SizeVarint(112<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *TestAllTypes_OneofString:
+ n += proto.SizeVarint(113<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.OneofString)))
+ n += len(x.OneofString)
+ case *TestAllTypes_OneofBytes:
+ n += proto.SizeVarint(114<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.OneofBytes)))
+ n += len(x.OneofBytes)
+ case *TestAllTypes_OneofBool:
+ n += proto.SizeVarint(115<<3 | proto.WireVarint)
+ n += 1
+ case *TestAllTypes_OneofUint64:
+ n += proto.SizeVarint(116<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.OneofUint64))
+ case *TestAllTypes_OneofFloat:
+ n += proto.SizeVarint(117<<3 | proto.WireFixed32)
+ n += 4
+ case *TestAllTypes_OneofDouble:
+ n += proto.SizeVarint(118<<3 | proto.WireFixed64)
+ n += 8
+ case *TestAllTypes_OneofEnum:
+ n += proto.SizeVarint(119<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.OneofEnum))
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+type TestAllTypes_NestedMessage struct {
+ A int32 `protobuf:"varint,1,opt,name=a" json:"a,omitempty"`
+ Corecursive *TestAllTypes `protobuf:"bytes,2,opt,name=corecursive" json:"corecursive,omitempty"`
+}
+
+func (m *TestAllTypes_NestedMessage) Reset() { *m = TestAllTypes_NestedMessage{} }
+func (m *TestAllTypes_NestedMessage) String() string { return proto.CompactTextString(m) }
+func (*TestAllTypes_NestedMessage) ProtoMessage() {}
+func (*TestAllTypes_NestedMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} }
+
+func (m *TestAllTypes_NestedMessage) GetA() int32 {
+ if m != nil {
+ return m.A
+ }
+ return 0
+}
+
+func (m *TestAllTypes_NestedMessage) GetCorecursive() *TestAllTypes {
+ if m != nil {
+ return m.Corecursive
+ }
+ return nil
+}
+
+type ForeignMessage struct {
+ C int32 `protobuf:"varint,1,opt,name=c" json:"c,omitempty"`
+}
+
+func (m *ForeignMessage) Reset() { *m = ForeignMessage{} }
+func (m *ForeignMessage) String() string { return proto.CompactTextString(m) }
+func (*ForeignMessage) ProtoMessage() {}
+func (*ForeignMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
+
+func (m *ForeignMessage) GetC() int32 {
+ if m != nil {
+ return m.C
+ }
+ return 0
+}
+
+func init() {
+ proto.RegisterType((*ConformanceRequest)(nil), "conformance.ConformanceRequest")
+ proto.RegisterType((*ConformanceResponse)(nil), "conformance.ConformanceResponse")
+ proto.RegisterType((*TestAllTypes)(nil), "conformance.TestAllTypes")
+ proto.RegisterType((*TestAllTypes_NestedMessage)(nil), "conformance.TestAllTypes.NestedMessage")
+ proto.RegisterType((*ForeignMessage)(nil), "conformance.ForeignMessage")
+ proto.RegisterEnum("conformance.WireFormat", WireFormat_name, WireFormat_value)
+ proto.RegisterEnum("conformance.ForeignEnum", ForeignEnum_name, ForeignEnum_value)
+ proto.RegisterEnum("conformance.TestAllTypes_NestedEnum", TestAllTypes_NestedEnum_name, TestAllTypes_NestedEnum_value)
+}
+
+func init() { proto.RegisterFile("conformance_proto/conformance.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 2737 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x5a, 0xd9, 0x72, 0xdb, 0xc8,
+ 0xd5, 0x16, 0x08, 0x59, 0x4b, 0x93, 0x92, 0xa8, 0xd6, 0xd6, 0x96, 0x5d, 0x63, 0x58, 0xb2, 0x7f,
+ 0xd3, 0xf6, 0x8c, 0xac, 0x05, 0x86, 0x65, 0xcf, 0x3f, 0x8e, 0x45, 0x9b, 0xb4, 0xe4, 0x8c, 0x25,
+ 0x17, 0x64, 0x8d, 0xab, 0x9c, 0x0b, 0x06, 0xa6, 0x20, 0x15, 0xc7, 0x24, 0xc1, 0x01, 0x48, 0x4f,
+ 0x94, 0xcb, 0xbc, 0x41, 0xf6, 0x7d, 0xbd, 0xcf, 0x7a, 0x93, 0xa4, 0x92, 0xab, 0x54, 0x6e, 0xb2,
+ 0x27, 0x95, 0x3d, 0x79, 0x85, 0xbc, 0x43, 0x52, 0xbd, 0xa2, 0xbb, 0x01, 0x50, 0xf4, 0x54, 0x0d,
+ 0x25, 0x1e, 0x7c, 0xfd, 0x9d, 0xd3, 0xe7, 0x1c, 0x7c, 0x2d, 0x1c, 0x18, 0x2c, 0xd7, 0x83, 0xf6,
+ 0x51, 0x10, 0xb6, 0xbc, 0x76, 0xdd, 0xaf, 0x75, 0xc2, 0xa0, 0x1b, 0xdc, 0x90, 0x2c, 0x2b, 0xc4,
+ 0x02, 0xf3, 0x92, 0x69, 0xf1, 0xec, 0x71, 0x10, 0x1c, 0x37, 0xfd, 0x1b, 0xe4, 0xd2, 0x8b, 0xde,
+ 0xd1, 0x0d, 0xaf, 0x7d, 0x42, 0x71, 0x8b, 0x6f, 0xe8, 0x97, 0x0e, 0x7b, 0xa1, 0xd7, 0x6d, 0x04,
+ 0x6d, 0x76, 0xdd, 0xd2, 0xaf, 0x1f, 0x35, 0xfc, 0xe6, 0x61, 0xad, 0xe5, 0x45, 0x2f, 0x19, 0xe2,
+ 0xbc, 0x8e, 0x88, 0xba, 0x61, 0xaf, 0xde, 0x65, 0x57, 0x2f, 0xe8, 0x57, 0xbb, 0x8d, 0x96, 0x1f,
+ 0x75, 0xbd, 0x56, 0x27, 0x2b, 0x80, 0x0f, 0x43, 0xaf, 0xd3, 0xf1, 0xc3, 0x88, 0x5e, 0x5f, 0xfa,
+ 0x85, 0x01, 0xe0, 0xfd, 0x78, 0x2f, 0xae, 0xff, 0x41, 0xcf, 0x8f, 0xba, 0xf0, 0x3a, 0x28, 0xf2,
+ 0x15, 0xb5, 0x8e, 0x77, 0xd2, 0x0c, 0xbc, 0x43, 0x64, 0x58, 0x46, 0xa9, 0xb0, 0x3d, 0xe4, 0x4e,
+ 0xf1, 0x2b, 0x4f, 0xe8, 0x05, 0xb8, 0x0c, 0x0a, 0xef, 0x47, 0x41, 0x5b, 0x00, 0x73, 0x96, 0x51,
+ 0x1a, 0xdf, 0x1e, 0x72, 0xf3, 0xd8, 0xca, 0x41, 0x7b, 0x60, 0x21, 0xa4, 0xe4, 0xfe, 0x61, 0x2d,
+ 0xe8, 0x75, 0x3b, 0xbd, 0x6e, 0x8d, 0x78, 0xed, 0x22, 0xd3, 0x32, 0x4a, 0x93, 0xeb, 0x0b, 0x2b,
+ 0x72, 0x9a, 0x9f, 0x35, 0x42, 0xbf, 0x4a, 0x2e, 0xbb, 0x73, 0x62, 0xdd, 0x1e, 0x59, 0x46, 0xcd,
+ 0xe5, 0x71, 0x30, 0xca, 0x1c, 0x2e, 0x7d, 0x2a, 0x07, 0x66, 0x94, 0x4d, 0x44, 0x9d, 0xa0, 0x1d,
+ 0xf9, 0xf0, 0x22, 0xc8, 0x77, 0xbc, 0x30, 0xf2, 0x6b, 0x7e, 0x18, 0x06, 0x21, 0xd9, 0x00, 0x8e,
+ 0x0b, 0x10, 0x63, 0x05, 0xdb, 0xe0, 0x55, 0x30, 0x15, 0xf9, 0x61, 0xc3, 0x6b, 0x36, 0x3e, 0xc9,
+ 0x61, 0x23, 0x0c, 0x36, 0x29, 0x2e, 0x50, 0xe8, 0x65, 0x30, 0x11, 0xf6, 0xda, 0x38, 0xc1, 0x0c,
+ 0xc8, 0xf7, 0x59, 0x60, 0x66, 0x0a, 0x4b, 0x4b, 0x9d, 0x39, 0x68, 0xea, 0x86, 0xd3, 0x52, 0xb7,
+ 0x08, 0x46, 0xa3, 0x97, 0x8d, 0x4e, 0xc7, 0x3f, 0x44, 0x67, 0xd8, 0x75, 0x6e, 0x28, 0x8f, 0x81,
+ 0x91, 0xd0, 0x8f, 0x7a, 0xcd, 0xee, 0xd2, 0x7f, 0xaa, 0xa0, 0xf0, 0xd4, 0x8f, 0xba, 0x5b, 0xcd,
+ 0xe6, 0xd3, 0x93, 0x8e, 0x1f, 0xc1, 0xcb, 0x60, 0x32, 0xe8, 0xe0, 0x5e, 0xf3, 0x9a, 0xb5, 0x46,
+ 0xbb, 0xbb, 0xb1, 0x4e, 0x12, 0x70, 0xc6, 0x9d, 0xe0, 0xd6, 0x1d, 0x6c, 0xd4, 0x61, 0x8e, 0x4d,
+ 0xf6, 0x65, 0x2a, 0x30, 0xc7, 0x86, 0x57, 0xc0, 0x94, 0x80, 0xf5, 0x28, 0x1d, 0xde, 0xd5, 0x84,
+ 0x2b, 0x56, 0x1f, 0x10, 0x6b, 0x02, 0xe8, 0xd8, 0x64, 0x57, 0xc3, 0x2a, 0x50, 0x63, 0x8c, 0x28,
+ 0x23, 0xde, 0xde, 0x74, 0x0c, 0xdc, 0x4f, 0x32, 0x46, 0x94, 0x11, 0xd7, 0x08, 0xaa, 0x40, 0xc7,
+ 0x86, 0x57, 0x41, 0x51, 0x00, 0x8f, 0x1a, 0x9f, 0xf0, 0x0f, 0x37, 0xd6, 0xd1, 0xa8, 0x65, 0x94,
+ 0x46, 0x5d, 0x41, 0x50, 0xa5, 0xe6, 0x24, 0xd4, 0xb1, 0xd1, 0x98, 0x65, 0x94, 0x46, 0x34, 0xa8,
+ 0x63, 0xc3, 0xeb, 0x60, 0x3a, 0x76, 0xcf, 0x69, 0xc7, 0x2d, 0xa3, 0x34, 0xe5, 0x0a, 0x8e, 0x7d,
+ 0x66, 0x4f, 0x01, 0x3b, 0x36, 0x02, 0x96, 0x51, 0x2a, 0xea, 0x60, 0xc7, 0x56, 0x52, 0x7f, 0xd4,
+ 0x0c, 0xbc, 0x2e, 0xca, 0x5b, 0x46, 0x29, 0x17, 0xa7, 0xbe, 0x8a, 0x8d, 0xca, 0xfe, 0x0f, 0x83,
+ 0xde, 0x8b, 0xa6, 0x8f, 0x0a, 0x96, 0x51, 0x32, 0xe2, 0xfd, 0x3f, 0x20, 0x56, 0xb8, 0x0c, 0xc4,
+ 0xca, 0xda, 0x8b, 0x20, 0x68, 0xa2, 0x09, 0xcb, 0x28, 0x8d, 0xb9, 0x05, 0x6e, 0x2c, 0x07, 0x41,
+ 0x53, 0xcd, 0x66, 0x37, 0x6c, 0xb4, 0x8f, 0xd1, 0x24, 0xee, 0x2a, 0x29, 0x9b, 0xc4, 0xaa, 0x44,
+ 0xf7, 0xe2, 0xa4, 0xeb, 0x47, 0x68, 0x0a, 0xb7, 0x71, 0x1c, 0x5d, 0x19, 0x1b, 0x61, 0x0d, 0x2c,
+ 0x08, 0x58, 0x9b, 0xde, 0xde, 0x2d, 0x3f, 0x8a, 0xbc, 0x63, 0x1f, 0x41, 0xcb, 0x28, 0xe5, 0xd7,
+ 0xaf, 0x28, 0x37, 0xb6, 0xdc, 0xa2, 0x2b, 0xbb, 0x04, 0xff, 0x98, 0xc2, 0xdd, 0x39, 0xce, 0xa3,
+ 0x98, 0xe1, 0x01, 0x40, 0x71, 0x96, 0x82, 0xd0, 0x6f, 0x1c, 0xb7, 0x85, 0x87, 0x19, 0xe2, 0xe1,
+ 0x9c, 0xe2, 0xa1, 0x4a, 0x31, 0x9c, 0x75, 0x5e, 0x24, 0x53, 0xb1, 0xc3, 0xf7, 0xc0, 0xac, 0x1e,
+ 0xb7, 0xdf, 0xee, 0xb5, 0xd0, 0x1c, 0x51, 0xa3, 0x4b, 0xa7, 0x05, 0x5d, 0x69, 0xf7, 0x5a, 0x2e,
+ 0x54, 0x23, 0xc6, 0x36, 0xf8, 0x2e, 0x98, 0x4b, 0x84, 0x4b, 0x88, 0xe7, 0x09, 0x31, 0x4a, 0x8b,
+ 0x95, 0x90, 0xcd, 0x68, 0x81, 0x12, 0x36, 0x47, 0x62, 0xa3, 0xd5, 0xaa, 0x75, 0x1a, 0x7e, 0xdd,
+ 0x47, 0x08, 0xd7, 0xac, 0x9c, 0x1b, 0xcb, 0xc5, 0xeb, 0x68, 0xdd, 0x9e, 0xe0, 0xcb, 0xf0, 0x8a,
+ 0xd4, 0x0a, 0xf5, 0x20, 0x3c, 0x44, 0x67, 0x19, 0xde, 0x88, 0xdb, 0xe1, 0x7e, 0x10, 0x1e, 0xc2,
+ 0x2a, 0x98, 0x0e, 0xfd, 0x7a, 0x2f, 0x8c, 0x1a, 0xaf, 0x7c, 0x91, 0xd6, 0x73, 0x24, 0xad, 0x67,
+ 0x33, 0x73, 0xe0, 0x16, 0xc5, 0x1a, 0x9e, 0xce, 0xcb, 0x60, 0x32, 0xf4, 0x3b, 0xbe, 0x87, 0xf3,
+ 0x48, 0x6f, 0xe6, 0x0b, 0x96, 0x89, 0xd5, 0x86, 0x5b, 0x85, 0xda, 0xc8, 0x30, 0xc7, 0x46, 0x96,
+ 0x65, 0x62, 0xb5, 0x91, 0x60, 0x54, 0x1b, 0x04, 0x8c, 0xa9, 0xcd, 0x45, 0xcb, 0xc4, 0x6a, 0xc3,
+ 0xcd, 0xb1, 0xda, 0x28, 0x40, 0xc7, 0x46, 0x4b, 0x96, 0x89, 0xd5, 0x46, 0x06, 0x6a, 0x8c, 0x4c,
+ 0x6d, 0x96, 0x2d, 0x13, 0xab, 0x0d, 0x37, 0xef, 0x27, 0x19, 0x99, 0xda, 0x5c, 0xb2, 0x4c, 0xac,
+ 0x36, 0x32, 0x90, 0xaa, 0x8d, 0x00, 0x72, 0x59, 0xb8, 0x6c, 0x99, 0x58, 0x6d, 0xb8, 0x5d, 0x52,
+ 0x1b, 0x15, 0xea, 0xd8, 0xe8, 0xff, 0x2c, 0x13, 0xab, 0x8d, 0x02, 0xa5, 0x6a, 0x13, 0xbb, 0xe7,
+ 0xb4, 0x57, 0x2c, 0x13, 0xab, 0x8d, 0x08, 0x40, 0x52, 0x1b, 0x0d, 0xec, 0xd8, 0xa8, 0x64, 0x99,
+ 0x58, 0x6d, 0x54, 0x30, 0x55, 0x9b, 0x38, 0x08, 0xa2, 0x36, 0x57, 0x2d, 0x13, 0xab, 0x8d, 0x08,
+ 0x81, 0xab, 0x8d, 0x80, 0x31, 0xb5, 0xb9, 0x66, 0x99, 0x58, 0x6d, 0xb8, 0x39, 0x56, 0x1b, 0x01,
+ 0x24, 0x6a, 0x73, 0xdd, 0x32, 0xb1, 0xda, 0x70, 0x23, 0x57, 0x9b, 0x38, 0x42, 0xaa, 0x36, 0x6f,
+ 0x5a, 0x26, 0x56, 0x1b, 0x11, 0x9f, 0x50, 0x9b, 0x98, 0x8d, 0xa8, 0xcd, 0x5b, 0x96, 0x89, 0xd5,
+ 0x46, 0xd0, 0x71, 0xb5, 0x11, 0x30, 0x4d, 0x6d, 0x56, 0x2d, 0xf3, 0xb5, 0xd4, 0x86, 0xf3, 0x24,
+ 0xd4, 0x26, 0xce, 0x92, 0xa6, 0x36, 0x6b, 0xc4, 0x43, 0x7f, 0xb5, 0x11, 0xc9, 0x4c, 0xa8, 0x8d,
+ 0x1e, 0x37, 0x11, 0x85, 0x0d, 0xcb, 0x1c, 0x5c, 0x6d, 0xd4, 0x88, 0xb9, 0xda, 0x24, 0xc2, 0x25,
+ 0xc4, 0x36, 0x21, 0xee, 0xa3, 0x36, 0x5a, 0xa0, 0x5c, 0x6d, 0xb4, 0x6a, 0x31, 0xb5, 0x71, 0x70,
+ 0xcd, 0xa8, 0xda, 0xa8, 0x75, 0x13, 0x6a, 0x23, 0xd6, 0x11, 0xb5, 0xb9, 0xc5, 0xf0, 0x46, 0xdc,
+ 0x0e, 0x44, 0x6d, 0x9e, 0x82, 0xa9, 0x96, 0xd7, 0xa1, 0x02, 0xc1, 0x64, 0x62, 0x93, 0x24, 0xf5,
+ 0xcd, 0xec, 0x0c, 0x3c, 0xf6, 0x3a, 0x44, 0x3b, 0xc8, 0x47, 0xa5, 0xdd, 0x0d, 0x4f, 0xdc, 0x89,
+ 0x96, 0x6c, 0x93, 0x58, 0x1d, 0x9b, 0xa9, 0xca, 0xed, 0xc1, 0x58, 0x1d, 0x9b, 0x7c, 0x28, 0xac,
+ 0xcc, 0x06, 0x9f, 0x83, 0x69, 0xcc, 0x4a, 0xe5, 0x87, 0xab, 0xd0, 0x1d, 0xc2, 0xbb, 0xd2, 0x97,
+ 0x97, 0x4a, 0x13, 0xfd, 0xa4, 0xcc, 0x38, 0x3c, 0xd9, 0x2a, 0x73, 0x3b, 0x36, 0x17, 0xae, 0xb7,
+ 0x07, 0xe4, 0x76, 0x6c, 0xfa, 0xa9, 0x72, 0x73, 0x2b, 0xe7, 0xa6, 0x22, 0xc7, 0xb5, 0xee, 0xff,
+ 0x07, 0xe0, 0xa6, 0x02, 0xb8, 0xaf, 0xc5, 0x2d, 0x5b, 0x65, 0x6e, 0xc7, 0xe6, 0xf2, 0xf8, 0xce,
+ 0x80, 0xdc, 0x8e, 0xbd, 0xaf, 0xc5, 0x2d, 0x5b, 0xe1, 0xc7, 0xc1, 0x0c, 0xe6, 0x66, 0xda, 0x26,
+ 0x24, 0xf5, 0x2e, 0x61, 0x5f, 0xed, 0xcb, 0xce, 0x74, 0x96, 0xfd, 0xa0, 0xfc, 0x38, 0x50, 0xd5,
+ 0xae, 0x78, 0x70, 0x6c, 0xa1, 0xc4, 0x1f, 0x19, 0xd4, 0x83, 0x63, 0xb3, 0x1f, 0x9a, 0x07, 0x61,
+ 0x87, 0x47, 0x60, 0x8e, 0xe4, 0x87, 0x6f, 0x42, 0x28, 0xf8, 0x3d, 0xe2, 0x63, 0xbd, 0x7f, 0x8e,
+ 0x18, 0x98, 0xff, 0xa4, 0x5e, 0x70, 0xc8, 0xfa, 0x15, 0xd5, 0x0f, 0xae, 0x04, 0xdf, 0xcb, 0xd6,
+ 0xc0, 0x7e, 0x1c, 0x9b, 0xff, 0xd4, 0xfd, 0xc4, 0x57, 0xd4, 0xfb, 0x95, 0x1e, 0x1a, 0xe5, 0x41,
+ 0xef, 0x57, 0x72, 0x9c, 0x68, 0xf7, 0x2b, 0x3d, 0x62, 0x9e, 0x81, 0x62, 0xcc, 0xca, 0xce, 0x98,
+ 0xfb, 0x84, 0xf6, 0xad, 0xd3, 0x69, 0xe9, 0xe9, 0x43, 0x79, 0x27, 0x5b, 0x8a, 0x11, 0xee, 0x02,
+ 0xec, 0x89, 0x9c, 0x46, 0xf4, 0x48, 0x7a, 0x40, 0x58, 0xaf, 0xf5, 0x65, 0xc5, 0xe7, 0x14, 0xfe,
+ 0x9f, 0x52, 0xe6, 0x5b, 0xb1, 0x45, 0xb4, 0x3b, 0x95, 0x42, 0x76, 0x7e, 0x55, 0x06, 0x69, 0x77,
+ 0x02, 0xa5, 0x9f, 0x52, 0xbb, 0x4b, 0x56, 0x9e, 0x04, 0xc6, 0x4d, 0x8f, 0xbc, 0xea, 0x00, 0x49,
+ 0xa0, 0xcb, 0xc9, 0x69, 0x18, 0x27, 0x41, 0x32, 0xc2, 0x0e, 0x38, 0x2b, 0x11, 0x6b, 0x87, 0xe4,
+ 0x43, 0xe2, 0xe1, 0xe6, 0x00, 0x1e, 0x94, 0x63, 0x91, 0x7a, 0x9a, 0x6f, 0xa5, 0x5e, 0x84, 0x11,
+ 0x58, 0x94, 0x3c, 0xea, 0xa7, 0xe6, 0x36, 0x71, 0xe9, 0x0c, 0xe0, 0x52, 0x3d, 0x33, 0xa9, 0xcf,
+ 0x85, 0x56, 0xfa, 0x55, 0x78, 0x0c, 0xe6, 0x93, 0xdb, 0x24, 0x47, 0xdf, 0xce, 0x20, 0xf7, 0x80,
+ 0xb4, 0x0d, 0x7c, 0xf4, 0x49, 0xf7, 0x80, 0x76, 0x05, 0xbe, 0x0f, 0x16, 0x52, 0x76, 0x47, 0x3c,
+ 0x3d, 0x22, 0x9e, 0x36, 0x06, 0xdf, 0x5a, 0xec, 0x6a, 0xb6, 0x95, 0x72, 0x09, 0x2e, 0x83, 0x42,
+ 0xd0, 0xf6, 0x83, 0x23, 0x7e, 0xdc, 0x04, 0xf8, 0x11, 0x7b, 0x7b, 0xc8, 0xcd, 0x13, 0x2b, 0x3b,
+ 0x3c, 0x3e, 0x06, 0x66, 0x29, 0x48, 0xab, 0x6d, 0xe7, 0xb5, 0x1e, 0xb7, 0xb6, 0x87, 0x5c, 0x48,
+ 0x68, 0xd4, 0x5a, 0x8a, 0x08, 0x58, 0xb7, 0x7f, 0xc0, 0x27, 0x12, 0xc4, 0xca, 0x7a, 0xf7, 0x22,
+ 0xa0, 0x5f, 0x59, 0xdb, 0x86, 0x6c, 0xbc, 0x01, 0x88, 0x91, 0x76, 0xe1, 0x05, 0x00, 0x18, 0x04,
+ 0xdf, 0x87, 0x11, 0x7e, 0x10, 0xdd, 0x1e, 0x72, 0xc7, 0x29, 0x02, 0xdf, 0x5b, 0xca, 0x56, 0x1d,
+ 0x1b, 0x75, 0x2d, 0xa3, 0x34, 0xac, 0x6c, 0xd5, 0xb1, 0x63, 0x47, 0x54, 0x7b, 0x7a, 0xf8, 0xf1,
+ 0x58, 0x38, 0xa2, 0x62, 0x22, 0x78, 0x98, 0x90, 0xbc, 0xc2, 0x8f, 0xc6, 0x82, 0x87, 0x09, 0x43,
+ 0x85, 0x47, 0x43, 0xca, 0xf6, 0xe1, 0xe0, 0x8f, 0x78, 0x22, 0x66, 0x52, 0x9e, 0x3d, 0xe9, 0x69,
+ 0x8c, 0x88, 0x0c, 0x9b, 0xa6, 0xa1, 0x5f, 0x19, 0x24, 0xf7, 0x8b, 0x2b, 0x74, 0xdc, 0xb6, 0xc2,
+ 0xe7, 0x3c, 0x2b, 0x78, 0xab, 0xef, 0x79, 0xcd, 0x9e, 0x1f, 0x3f, 0xa6, 0x61, 0xd3, 0x33, 0xba,
+ 0x0e, 0xba, 0x60, 0x5e, 0x9d, 0xd1, 0x08, 0xc6, 0x5f, 0x1b, 0xec, 0xd1, 0x56, 0x67, 0x24, 0x7a,
+ 0x47, 0x29, 0x67, 0x95, 0x49, 0x4e, 0x06, 0xa7, 0x63, 0x0b, 0xce, 0xdf, 0xf4, 0xe1, 0x74, 0xec,
+ 0x24, 0xa7, 0x63, 0x73, 0xce, 0x03, 0xe9, 0x21, 0xbf, 0xa7, 0x06, 0xfa, 0x5b, 0x4a, 0x7a, 0x3e,
+ 0x41, 0x7a, 0x20, 0x45, 0x3a, 0xa7, 0x0e, 0x89, 0xb2, 0x68, 0xa5, 0x58, 0x7f, 0xd7, 0x8f, 0x96,
+ 0x07, 0x3b, 0xa7, 0x8e, 0x94, 0xd2, 0x32, 0x40, 0x1a, 0x47, 0xb0, 0xfe, 0x3e, 0x2b, 0x03, 0xa4,
+ 0x97, 0xb4, 0x0c, 0x10, 0x5b, 0x5a, 0xa8, 0xb4, 0xd3, 0x04, 0xe9, 0x1f, 0xb2, 0x42, 0xa5, 0xcd,
+ 0xa7, 0x85, 0x4a, 0x8d, 0x69, 0xb4, 0x4c, 0x61, 0x38, 0xed, 0x1f, 0xb3, 0x68, 0xe9, 0x4d, 0xa8,
+ 0xd1, 0x52, 0x63, 0x5a, 0x06, 0xc8, 0x3d, 0x2a, 0x58, 0xff, 0x94, 0x95, 0x01, 0x72, 0xdb, 0x6a,
+ 0x19, 0x20, 0x36, 0xce, 0xb9, 0x27, 0x3d, 0x1c, 0x28, 0xcd, 0xff, 0x67, 0x83, 0xc8, 0x60, 0xdf,
+ 0xe6, 0x97, 0x1f, 0x0a, 0xa5, 0x20, 0xd5, 0x91, 0x81, 0x60, 0xfc, 0x8b, 0xc1, 0x9e, 0xb4, 0xfa,
+ 0x35, 0xbf, 0x32, 0x58, 0xc8, 0xe0, 0x94, 0x1a, 0xea, 0xaf, 0x7d, 0x38, 0x45, 0xf3, 0x2b, 0x53,
+ 0x08, 0xa9, 0x46, 0xda, 0x30, 0x42, 0x90, 0xfe, 0x8d, 0x92, 0x9e, 0xd2, 0xfc, 0xea, 0xcc, 0x22,
+ 0x8b, 0x56, 0x8a, 0xf5, 0xef, 0xfd, 0x68, 0x45, 0xf3, 0xab, 0x13, 0x8e, 0xb4, 0x0c, 0xa8, 0xcd,
+ 0xff, 0x8f, 0xac, 0x0c, 0xc8, 0xcd, 0xaf, 0x0c, 0x03, 0xd2, 0x42, 0xd5, 0x9a, 0xff, 0x9f, 0x59,
+ 0xa1, 0x2a, 0xcd, 0xaf, 0x8e, 0x0e, 0xd2, 0x68, 0xb5, 0xe6, 0xff, 0x57, 0x16, 0xad, 0xd2, 0xfc,
+ 0xea, 0xb3, 0x68, 0x5a, 0x06, 0xd4, 0xe6, 0xff, 0x77, 0x56, 0x06, 0xe4, 0xe6, 0x57, 0x06, 0x0e,
+ 0x9c, 0xf3, 0xa1, 0x34, 0xd7, 0xe5, 0xef, 0x70, 0xd0, 0x77, 0x73, 0x6c, 0x4e, 0x96, 0xd8, 0x3b,
+ 0x43, 0xc4, 0x33, 0x5f, 0x6e, 0x81, 0x8f, 0x80, 0x18, 0x1a, 0xd6, 0xc4, 0xcb, 0x1a, 0xf4, 0xbd,
+ 0x5c, 0xc6, 0xf9, 0xf1, 0x94, 0x43, 0x5c, 0xe1, 0x5f, 0x98, 0xe0, 0x47, 0xc1, 0x8c, 0x34, 0xc4,
+ 0xe6, 0x2f, 0x8e, 0xd0, 0xf7, 0xb3, 0xc8, 0xaa, 0x18, 0xf3, 0xd8, 0x8b, 0x5e, 0xc6, 0x64, 0xc2,
+ 0x04, 0xb7, 0xd4, 0xb9, 0x70, 0xaf, 0xde, 0x45, 0x3f, 0xa0, 0x44, 0x0b, 0x69, 0x45, 0xe8, 0xd5,
+ 0xbb, 0xca, 0xc4, 0xb8, 0x57, 0xef, 0xc2, 0x4d, 0x20, 0x66, 0x8b, 0x35, 0xaf, 0x7d, 0x82, 0x7e,
+ 0x48, 0xd7, 0xcf, 0x26, 0xd6, 0x6f, 0xb5, 0x4f, 0xdc, 0x3c, 0x87, 0x6e, 0xb5, 0x4f, 0xe0, 0x5d,
+ 0x69, 0xd6, 0xfc, 0x0a, 0x97, 0x01, 0xfd, 0x88, 0xae, 0x9d, 0x4f, 0xac, 0xa5, 0x55, 0x12, 0xd3,
+ 0x4d, 0xf2, 0x15, 0x97, 0x27, 0x6e, 0x50, 0x5e, 0x9e, 0x1f, 0xe7, 0x48, 0xb5, 0xfb, 0x95, 0x47,
+ 0xf4, 0xa5, 0x54, 0x1e, 0x41, 0x14, 0x97, 0xe7, 0x27, 0xb9, 0x0c, 0x85, 0x93, 0xca, 0xc3, 0x97,
+ 0xc5, 0xe5, 0x91, 0xb9, 0x48, 0x79, 0x48, 0x75, 0x7e, 0x9a, 0xc5, 0x25, 0x55, 0x27, 0x1e, 0x0a,
+ 0xb2, 0x55, 0xb8, 0x3a, 0xf2, 0xad, 0x82, 0xab, 0xf3, 0x4b, 0x4a, 0x94, 0x5d, 0x1d, 0xe9, 0xee,
+ 0x60, 0xd5, 0x11, 0x14, 0xb8, 0x3a, 0x3f, 0xa3, 0xeb, 0x33, 0xaa, 0xc3, 0xa1, 0xac, 0x3a, 0x62,
+ 0x25, 0xad, 0xce, 0xcf, 0xe9, 0xda, 0xcc, 0xea, 0x70, 0x38, 0xad, 0xce, 0x05, 0x00, 0xc8, 0xfe,
+ 0xdb, 0x5e, 0xcb, 0x5f, 0x43, 0x9f, 0x36, 0xc9, 0x6b, 0x28, 0xc9, 0x04, 0x2d, 0x90, 0xa7, 0xfd,
+ 0x8b, 0xbf, 0xae, 0xa3, 0xcf, 0xc8, 0x88, 0x5d, 0x6c, 0x82, 0x17, 0x41, 0xa1, 0x16, 0x43, 0x36,
+ 0xd0, 0x67, 0x19, 0xa4, 0xca, 0x21, 0x1b, 0x70, 0x09, 0x4c, 0x50, 0x04, 0x81, 0xd8, 0x35, 0xf4,
+ 0x39, 0x9d, 0x86, 0xfc, 0x3d, 0x49, 0xbe, 0xad, 0x62, 0xc8, 0x4d, 0xf4, 0x79, 0x8a, 0x90, 0x6d,
+ 0x70, 0x99, 0xd3, 0xac, 0x12, 0x1e, 0x07, 0x7d, 0x41, 0x01, 0x61, 0x1e, 0x47, 0xec, 0x08, 0x7f,
+ 0xbb, 0x85, 0xbe, 0xa8, 0x3b, 0xba, 0x85, 0x01, 0x22, 0xb4, 0x4d, 0xf4, 0x25, 0x3d, 0xda, 0xcd,
+ 0x78, 0xcb, 0xf8, 0xeb, 0x6d, 0xf4, 0x65, 0x9d, 0xe2, 0x36, 0x5c, 0x02, 0x85, 0xaa, 0x40, 0xac,
+ 0xad, 0xa2, 0xaf, 0xb0, 0x38, 0x04, 0xc9, 0xda, 0x2a, 0xc1, 0xec, 0x54, 0xde, 0x7d, 0x50, 0xdb,
+ 0xdd, 0x7a, 0x5c, 0x59, 0x5b, 0x43, 0x5f, 0xe5, 0x18, 0x6c, 0xa4, 0xb6, 0x18, 0x43, 0x72, 0xbd,
+ 0x8e, 0xbe, 0xa6, 0x60, 0x88, 0x0d, 0x5e, 0x02, 0x93, 0x35, 0x29, 0xbf, 0x6b, 0x1b, 0xe8, 0xeb,
+ 0x09, 0x6f, 0x1b, 0x14, 0x55, 0x8d, 0x51, 0x36, 0xfa, 0x46, 0x02, 0x65, 0xc7, 0x09, 0xa4, 0xa0,
+ 0x9b, 0xe8, 0x9b, 0x72, 0x02, 0x09, 0x48, 0xca, 0x32, 0xdd, 0x9d, 0x83, 0xbe, 0x95, 0x00, 0x39,
+ 0xd8, 0x9f, 0x14, 0xd3, 0xad, 0x5a, 0x0d, 0x7d, 0x3b, 0x81, 0xba, 0x85, 0x51, 0x52, 0x4c, 0x9b,
+ 0xb5, 0x1a, 0xfa, 0x4e, 0x22, 0xaa, 0xcd, 0xc5, 0xe7, 0x60, 0x42, 0x7d, 0xd0, 0x29, 0x00, 0xc3,
+ 0x63, 0x6f, 0x44, 0x0d, 0x0f, 0xbe, 0x0d, 0xf2, 0xf5, 0x40, 0xbc, 0xd4, 0x40, 0xb9, 0xd3, 0x5e,
+ 0x80, 0xc8, 0xe8, 0xc5, 0x7b, 0x00, 0x26, 0x87, 0x94, 0xb0, 0x08, 0xcc, 0x97, 0xfe, 0x09, 0x73,
+ 0x81, 0x7f, 0x85, 0xb3, 0xe0, 0x0c, 0xbd, 0x7d, 0x72, 0xc4, 0x46, 0xbf, 0xdc, 0xc9, 0x6d, 0x1a,
+ 0x31, 0x83, 0x3c, 0x90, 0x94, 0x19, 0xcc, 0x14, 0x06, 0x53, 0x66, 0x28, 0x83, 0xd9, 0xb4, 0xd1,
+ 0xa3, 0xcc, 0x31, 0x91, 0xc2, 0x31, 0x91, 0xce, 0xa1, 0x8c, 0x18, 0x65, 0x8e, 0xe1, 0x14, 0x8e,
+ 0xe1, 0x24, 0x47, 0x62, 0x94, 0x28, 0x73, 0x4c, 0xa7, 0x70, 0x4c, 0xa7, 0x73, 0x28, 0x23, 0x43,
+ 0x99, 0x03, 0xa6, 0x70, 0x40, 0x99, 0xe3, 0x01, 0x98, 0x4f, 0x1f, 0x0c, 0xca, 0x2c, 0xa3, 0x29,
+ 0x2c, 0xa3, 0x19, 0x2c, 0xea, 0xf0, 0x4f, 0x66, 0x19, 0x49, 0x61, 0x19, 0x91, 0x59, 0xaa, 0x00,
+ 0x65, 0x8d, 0xf7, 0x64, 0x9e, 0xa9, 0x14, 0x9e, 0xa9, 0x2c, 0x1e, 0x6d, 0x7c, 0x27, 0xf3, 0x14,
+ 0x53, 0x78, 0x8a, 0xa9, 0xdd, 0x26, 0x0f, 0xe9, 0x4e, 0xeb, 0xd7, 0x9c, 0xcc, 0xb0, 0x05, 0x66,
+ 0x52, 0xe6, 0x71, 0xa7, 0x51, 0x18, 0x32, 0xc5, 0x5d, 0x50, 0xd4, 0x87, 0x6f, 0xf2, 0xfa, 0xb1,
+ 0x94, 0xf5, 0x63, 0x29, 0x4d, 0xa2, 0x0f, 0xda, 0x64, 0x8e, 0xf1, 0x14, 0x8e, 0xf1, 0xe4, 0x36,
+ 0xf4, 0x89, 0xda, 0x69, 0x14, 0x05, 0x99, 0x22, 0x04, 0xe7, 0xfa, 0x8c, 0xcc, 0x52, 0xa8, 0xde,
+ 0x91, 0xa9, 0x5e, 0xe3, 0x7d, 0x95, 0xe4, 0xf3, 0x18, 0x9c, 0xef, 0x37, 0x33, 0x4b, 0x71, 0xba,
+ 0xa6, 0x3a, 0xed, 0xfb, 0x0a, 0x4b, 0x72, 0xd4, 0xa4, 0x0d, 0x97, 0x36, 0x2b, 0x4b, 0x71, 0x72,
+ 0x47, 0x76, 0x32, 0xe8, 0x4b, 0x2d, 0xc9, 0x9b, 0x07, 0xce, 0x66, 0xce, 0xcb, 0x52, 0xdc, 0xad,
+ 0xa8, 0xee, 0xb2, 0x5f, 0x75, 0xc5, 0x2e, 0x96, 0x6e, 0x03, 0x20, 0x4d, 0xf6, 0x46, 0x81, 0x59,
+ 0xdd, 0xdb, 0x2b, 0x0e, 0xe1, 0x5f, 0xca, 0x5b, 0x6e, 0xd1, 0xa0, 0xbf, 0x3c, 0x2f, 0xe6, 0xb0,
+ 0xbb, 0xdd, 0xca, 0xc3, 0xe2, 0x7f, 0xf9, 0x7f, 0x46, 0x79, 0x42, 0x8c, 0xa2, 0xf0, 0xa9, 0xb2,
+ 0xf4, 0x06, 0x98, 0xd4, 0x06, 0x92, 0x05, 0x60, 0xd4, 0xf9, 0x81, 0x52, 0xbf, 0x76, 0x13, 0x80,
+ 0xf8, 0xdf, 0x30, 0xc1, 0x29, 0x90, 0x3f, 0xd8, 0xdd, 0x7f, 0x52, 0xb9, 0xbf, 0x53, 0xdd, 0xa9,
+ 0x3c, 0x28, 0x0e, 0xc1, 0x02, 0x18, 0x7b, 0xe2, 0xee, 0x3d, 0xdd, 0x2b, 0x1f, 0x54, 0x8b, 0x06,
+ 0x1c, 0x03, 0xc3, 0x8f, 0xf6, 0xf7, 0x76, 0x8b, 0xb9, 0x6b, 0xf7, 0x40, 0x5e, 0x9e, 0x07, 0x4e,
+ 0x81, 0x7c, 0x75, 0xcf, 0xad, 0xec, 0x3c, 0xdc, 0xad, 0xd1, 0x48, 0x25, 0x03, 0x8d, 0x58, 0x31,
+ 0x3c, 0x2f, 0xe6, 0xca, 0x17, 0xc1, 0x85, 0x7a, 0xd0, 0x4a, 0xfc, 0x61, 0x26, 0x25, 0xe7, 0xc5,
+ 0x08, 0xb1, 0x6e, 0xfc, 0x2f, 0x00, 0x00, 0xff, 0xff, 0x33, 0xc2, 0x0c, 0xb6, 0xeb, 0x26, 0x00,
+ 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/_conformance/conformance_proto/conformance.proto b/vendor/github.com/golang/protobuf/_conformance/conformance_proto/conformance.proto
new file mode 100644
index 0000000..95a8fd1
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/_conformance/conformance_proto/conformance.proto
@@ -0,0 +1,285 @@
+// 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.
+
+syntax = "proto3";
+package conformance;
+option java_package = "com.google.protobuf.conformance";
+
+import "google/protobuf/any.proto";
+import "google/protobuf/duration.proto";
+import "google/protobuf/field_mask.proto";
+import "google/protobuf/struct.proto";
+import "google/protobuf/timestamp.proto";
+import "google/protobuf/wrappers.proto";
+
+// This defines the conformance testing protocol. This protocol exists between
+// the conformance test suite itself and the code being tested. For each test,
+// the suite will send a ConformanceRequest message and expect a
+// ConformanceResponse message.
+//
+// You can either run the tests in two different ways:
+//
+// 1. in-process (using the interface in conformance_test.h).
+//
+// 2. as a sub-process communicating over a pipe. Information about how to
+// do this is in conformance_test_runner.cc.
+//
+// Pros/cons of the two approaches:
+//
+// - running as a sub-process is much simpler for languages other than C/C++.
+//
+// - running as a sub-process may be more tricky in unusual environments like
+// iOS apps, where fork/stdin/stdout are not available.
+
+enum WireFormat {
+ UNSPECIFIED = 0;
+ PROTOBUF = 1;
+ JSON = 2;
+}
+
+// Represents a single test case's input. The testee should:
+//
+// 1. parse this proto (which should always succeed)
+// 2. parse the protobuf or JSON payload in "payload" (which may fail)
+// 3. if the parse succeeded, serialize the message in the requested format.
+message ConformanceRequest {
+ // The payload (whether protobuf of JSON) is always for a TestAllTypes proto
+ // (see below).
+ oneof payload {
+ bytes protobuf_payload = 1;
+ string json_payload = 2;
+ }
+
+ // Which format should the testee serialize its message to?
+ WireFormat requested_output_format = 3;
+}
+
+// Represents a single test case's output.
+message ConformanceResponse {
+ oneof result {
+ // This string should be set to indicate parsing failed. The string can
+ // provide more information about the parse error if it is available.
+ //
+ // Setting this string does not necessarily mean the testee failed the
+ // test. Some of the test cases are intentionally invalid input.
+ string parse_error = 1;
+
+ // If the input was successfully parsed but errors occurred when
+ // serializing it to the requested output format, set the error message in
+ // this field.
+ string serialize_error = 6;
+
+ // This should be set if some other error occurred. This will always
+ // indicate that the test failed. The string can provide more information
+ // about the failure.
+ string runtime_error = 2;
+
+ // If the input was successfully parsed and the requested output was
+ // protobuf, serialize it to protobuf and set it in this field.
+ bytes protobuf_payload = 3;
+
+ // If the input was successfully parsed and the requested output was JSON,
+ // serialize to JSON and set it in this field.
+ string json_payload = 4;
+
+ // For when the testee skipped the test, likely because a certain feature
+ // wasn't supported, like JSON input/output.
+ string skipped = 5;
+ }
+}
+
+// This proto includes every type of field in both singular and repeated
+// forms.
+message TestAllTypes {
+ message NestedMessage {
+ int32 a = 1;
+ TestAllTypes corecursive = 2;
+ }
+
+ enum NestedEnum {
+ FOO = 0;
+ BAR = 1;
+ BAZ = 2;
+ NEG = -1; // Intentionally negative.
+ }
+
+ // Singular
+ int32 optional_int32 = 1;
+ int64 optional_int64 = 2;
+ uint32 optional_uint32 = 3;
+ uint64 optional_uint64 = 4;
+ sint32 optional_sint32 = 5;
+ sint64 optional_sint64 = 6;
+ fixed32 optional_fixed32 = 7;
+ fixed64 optional_fixed64 = 8;
+ sfixed32 optional_sfixed32 = 9;
+ sfixed64 optional_sfixed64 = 10;
+ float optional_float = 11;
+ double optional_double = 12;
+ bool optional_bool = 13;
+ string optional_string = 14;
+ bytes optional_bytes = 15;
+
+ NestedMessage optional_nested_message = 18;
+ ForeignMessage optional_foreign_message = 19;
+
+ NestedEnum optional_nested_enum = 21;
+ ForeignEnum optional_foreign_enum = 22;
+
+ string optional_string_piece = 24 [ctype=STRING_PIECE];
+ string optional_cord = 25 [ctype=CORD];
+
+ TestAllTypes recursive_message = 27;
+
+ // Repeated
+ repeated int32 repeated_int32 = 31;
+ repeated int64 repeated_int64 = 32;
+ repeated uint32 repeated_uint32 = 33;
+ repeated uint64 repeated_uint64 = 34;
+ repeated sint32 repeated_sint32 = 35;
+ repeated sint64 repeated_sint64 = 36;
+ repeated fixed32 repeated_fixed32 = 37;
+ repeated fixed64 repeated_fixed64 = 38;
+ repeated sfixed32 repeated_sfixed32 = 39;
+ repeated sfixed64 repeated_sfixed64 = 40;
+ repeated float repeated_float = 41;
+ repeated double repeated_double = 42;
+ repeated bool repeated_bool = 43;
+ repeated string repeated_string = 44;
+ repeated bytes repeated_bytes = 45;
+
+ repeated NestedMessage repeated_nested_message = 48;
+ repeated ForeignMessage repeated_foreign_message = 49;
+
+ repeated NestedEnum repeated_nested_enum = 51;
+ repeated ForeignEnum repeated_foreign_enum = 52;
+
+ repeated string repeated_string_piece = 54 [ctype=STRING_PIECE];
+ repeated string repeated_cord = 55 [ctype=CORD];
+
+ // Map
+ map < int32, int32> map_int32_int32 = 56;
+ map < int64, int64> map_int64_int64 = 57;
+ map < uint32, uint32> map_uint32_uint32 = 58;
+ map < uint64, uint64> map_uint64_uint64 = 59;
+ map < sint32, sint32> map_sint32_sint32 = 60;
+ map < sint64, sint64> map_sint64_sint64 = 61;
+ map < fixed32, fixed32> map_fixed32_fixed32 = 62;
+ map < fixed64, fixed64> map_fixed64_fixed64 = 63;
+ map map_sfixed32_sfixed32 = 64;
+ map map_sfixed64_sfixed64 = 65;
+ map < int32, float> map_int32_float = 66;
+ map < int32, double> map_int32_double = 67;
+ map < bool, bool> map_bool_bool = 68;
+ map < string, string> map_string_string = 69;
+ map < string, bytes> map_string_bytes = 70;
+ map < string, NestedMessage> map_string_nested_message = 71;
+ map < string, ForeignMessage> map_string_foreign_message = 72;
+ map < string, NestedEnum> map_string_nested_enum = 73;
+ map < string, ForeignEnum> map_string_foreign_enum = 74;
+
+ oneof oneof_field {
+ uint32 oneof_uint32 = 111;
+ NestedMessage oneof_nested_message = 112;
+ string oneof_string = 113;
+ bytes oneof_bytes = 114;
+ bool oneof_bool = 115;
+ uint64 oneof_uint64 = 116;
+ float oneof_float = 117;
+ double oneof_double = 118;
+ NestedEnum oneof_enum = 119;
+ }
+
+ // Well-known types
+ google.protobuf.BoolValue optional_bool_wrapper = 201;
+ google.protobuf.Int32Value optional_int32_wrapper = 202;
+ google.protobuf.Int64Value optional_int64_wrapper = 203;
+ google.protobuf.UInt32Value optional_uint32_wrapper = 204;
+ google.protobuf.UInt64Value optional_uint64_wrapper = 205;
+ google.protobuf.FloatValue optional_float_wrapper = 206;
+ google.protobuf.DoubleValue optional_double_wrapper = 207;
+ google.protobuf.StringValue optional_string_wrapper = 208;
+ google.protobuf.BytesValue optional_bytes_wrapper = 209;
+
+ repeated google.protobuf.BoolValue repeated_bool_wrapper = 211;
+ repeated google.protobuf.Int32Value repeated_int32_wrapper = 212;
+ repeated google.protobuf.Int64Value repeated_int64_wrapper = 213;
+ repeated google.protobuf.UInt32Value repeated_uint32_wrapper = 214;
+ repeated google.protobuf.UInt64Value repeated_uint64_wrapper = 215;
+ repeated google.protobuf.FloatValue repeated_float_wrapper = 216;
+ repeated google.protobuf.DoubleValue repeated_double_wrapper = 217;
+ repeated google.protobuf.StringValue repeated_string_wrapper = 218;
+ repeated google.protobuf.BytesValue repeated_bytes_wrapper = 219;
+
+ google.protobuf.Duration optional_duration = 301;
+ google.protobuf.Timestamp optional_timestamp = 302;
+ google.protobuf.FieldMask optional_field_mask = 303;
+ google.protobuf.Struct optional_struct = 304;
+ google.protobuf.Any optional_any = 305;
+ google.protobuf.Value optional_value = 306;
+
+ repeated google.protobuf.Duration repeated_duration = 311;
+ repeated google.protobuf.Timestamp repeated_timestamp = 312;
+ repeated google.protobuf.FieldMask repeated_fieldmask = 313;
+ repeated google.protobuf.Struct repeated_struct = 324;
+ repeated google.protobuf.Any repeated_any = 315;
+ repeated google.protobuf.Value repeated_value = 316;
+
+ // Test field-name-to-JSON-name convention.
+ // (protobuf says names can be any valid C/C++ identifier.)
+ int32 fieldname1 = 401;
+ int32 field_name2 = 402;
+ int32 _field_name3 = 403;
+ int32 field__name4_ = 404;
+ int32 field0name5 = 405;
+ int32 field_0_name6 = 406;
+ int32 fieldName7 = 407;
+ int32 FieldName8 = 408;
+ int32 field_Name9 = 409;
+ int32 Field_Name10 = 410;
+ int32 FIELD_NAME11 = 411;
+ int32 FIELD_name12 = 412;
+ int32 __field_name13 = 413;
+ int32 __Field_name14 = 414;
+ int32 field__name15 = 415;
+ int32 field__Name16 = 416;
+ int32 field_name17__ = 417;
+ int32 Field_name18__ = 418;
+}
+
+message ForeignMessage {
+ int32 c = 1;
+}
+
+enum ForeignEnum {
+ FOREIGN_FOO = 0;
+ FOREIGN_BAR = 1;
+ FOREIGN_BAZ = 2;
+}
diff --git a/vendor/github.com/golang/protobuf/descriptor/descriptor.go b/vendor/github.com/golang/protobuf/descriptor/descriptor.go
new file mode 100644
index 0000000..ac7e51b
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/descriptor/descriptor.go
@@ -0,0 +1,93 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 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 descriptor provides functions for obtaining protocol buffer
+// descriptors for generated Go types.
+//
+// These functions cannot go in package proto because they depend on the
+// generated protobuf descriptor messages, which themselves depend on proto.
+package descriptor
+
+import (
+ "bytes"
+ "compress/gzip"
+ "fmt"
+ "io/ioutil"
+
+ "github.com/golang/protobuf/proto"
+ protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
+)
+
+// extractFile extracts a FileDescriptorProto from a gzip'd buffer.
+func extractFile(gz []byte) (*protobuf.FileDescriptorProto, error) {
+ r, err := gzip.NewReader(bytes.NewReader(gz))
+ if err != nil {
+ return nil, fmt.Errorf("failed to open gzip reader: %v", err)
+ }
+ defer r.Close()
+
+ b, err := ioutil.ReadAll(r)
+ if err != nil {
+ return nil, fmt.Errorf("failed to uncompress descriptor: %v", err)
+ }
+
+ fd := new(protobuf.FileDescriptorProto)
+ if err := proto.Unmarshal(b, fd); err != nil {
+ return nil, fmt.Errorf("malformed FileDescriptorProto: %v", err)
+ }
+
+ return fd, nil
+}
+
+// Message is a proto.Message with a method to return its descriptor.
+//
+// Message types generated by the protocol compiler always satisfy
+// the Message interface.
+type Message interface {
+ proto.Message
+ Descriptor() ([]byte, []int)
+}
+
+// ForMessage returns a FileDescriptorProto and a DescriptorProto from within it
+// describing the given message.
+func ForMessage(msg Message) (fd *protobuf.FileDescriptorProto, md *protobuf.DescriptorProto) {
+ gz, path := msg.Descriptor()
+ fd, err := extractFile(gz)
+ if err != nil {
+ panic(fmt.Sprintf("invalid FileDescriptorProto for %T: %v", msg, err))
+ }
+
+ md = fd.MessageType[path[0]]
+ for _, i := range path[1:] {
+ md = md.NestedType[i]
+ }
+ return fd, md
+}
diff --git a/vendor/github.com/golang/protobuf/descriptor/descriptor_test.go b/vendor/github.com/golang/protobuf/descriptor/descriptor_test.go
new file mode 100644
index 0000000..27b0729
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/descriptor/descriptor_test.go
@@ -0,0 +1,32 @@
+package descriptor_test
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/golang/protobuf/descriptor"
+ tpb "github.com/golang/protobuf/proto/testdata"
+ protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
+)
+
+func TestMessage(t *testing.T) {
+ var msg *protobuf.DescriptorProto
+ fd, md := descriptor.ForMessage(msg)
+ if pkg, want := fd.GetPackage(), "google.protobuf"; pkg != want {
+ t.Errorf("descriptor.ForMessage(%T).GetPackage() = %q; want %q", msg, pkg, want)
+ }
+ if name, want := md.GetName(), "DescriptorProto"; name != want {
+ t.Fatalf("descriptor.ForMessage(%T).GetName() = %q; want %q", msg, name, want)
+ }
+}
+
+func Example_Options() {
+ var msg *tpb.MyMessageSet
+ _, md := descriptor.ForMessage(msg)
+ if md.GetOptions().GetMessageSetWireFormat() {
+ fmt.Printf("%v uses option message_set_wire_format.\n", md.GetName())
+ }
+
+ // Output:
+ // MyMessageSet uses option message_set_wire_format.
+}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb.go b/vendor/github.com/golang/protobuf/jsonpb/jsonpb.go
new file mode 100644
index 0000000..110ae13
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/jsonpb/jsonpb.go
@@ -0,0 +1,1083 @@
+// 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 jsonpb provides marshaling and unmarshaling between protocol buffers and JSON.
+It follows the specification at https://developers.google.com/protocol-buffers/docs/proto3#json.
+
+This package produces a different output than the standard "encoding/json" package,
+which does not operate correctly on protocol buffers.
+*/
+package jsonpb
+
+import (
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "reflect"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/golang/protobuf/proto"
+
+ stpb "github.com/golang/protobuf/ptypes/struct"
+)
+
+// Marshaler is a configurable object for converting between
+// protocol buffer objects and a JSON representation for them.
+type Marshaler struct {
+ // Whether to render enum values as integers, as opposed to string values.
+ EnumsAsInts bool
+
+ // Whether to render fields with zero values.
+ EmitDefaults bool
+
+ // A string to indent each level by. The presence of this field will
+ // also cause a space to appear between the field separator and
+ // value, and for newlines to be appear between fields and array
+ // elements.
+ Indent string
+
+ // Whether to use the original (.proto) name for fields.
+ OrigName bool
+
+ // A custom URL resolver to use when marshaling Any messages to JSON.
+ // If unset, the default resolution strategy is to extract the
+ // fully-qualified type name from the type URL and pass that to
+ // proto.MessageType(string).
+ AnyResolver AnyResolver
+}
+
+// AnyResolver takes a type URL, present in an Any message, and resolves it into
+// an instance of the associated message.
+type AnyResolver interface {
+ Resolve(typeUrl string) (proto.Message, error)
+}
+
+func defaultResolveAny(typeUrl string) (proto.Message, error) {
+ // Only the part of typeUrl after the last slash is relevant.
+ mname := typeUrl
+ if slash := strings.LastIndex(mname, "/"); slash >= 0 {
+ mname = mname[slash+1:]
+ }
+ mt := proto.MessageType(mname)
+ if mt == nil {
+ return nil, fmt.Errorf("unknown message type %q", mname)
+ }
+ return reflect.New(mt.Elem()).Interface().(proto.Message), nil
+}
+
+// JSONPBMarshaler is implemented by protobuf messages that customize the
+// way they are marshaled to JSON. Messages that implement this should
+// also implement JSONPBUnmarshaler so that the custom format can be
+// parsed.
+type JSONPBMarshaler interface {
+ MarshalJSONPB(*Marshaler) ([]byte, error)
+}
+
+// JSONPBUnmarshaler is implemented by protobuf messages that customize
+// the way they are unmarshaled from JSON. Messages that implement this
+// should also implement JSONPBMarshaler so that the custom format can be
+// produced.
+type JSONPBUnmarshaler interface {
+ UnmarshalJSONPB(*Unmarshaler, []byte) error
+}
+
+// Marshal marshals a protocol buffer into JSON.
+func (m *Marshaler) Marshal(out io.Writer, pb proto.Message) error {
+ writer := &errWriter{writer: out}
+ return m.marshalObject(writer, pb, "", "")
+}
+
+// MarshalToString converts a protocol buffer object to JSON string.
+func (m *Marshaler) MarshalToString(pb proto.Message) (string, error) {
+ var buf bytes.Buffer
+ if err := m.Marshal(&buf, pb); err != nil {
+ return "", err
+ }
+ return buf.String(), nil
+}
+
+type int32Slice []int32
+
+var nonFinite = map[string]float64{
+ `"NaN"`: math.NaN(),
+ `"Infinity"`: math.Inf(1),
+ `"-Infinity"`: math.Inf(-1),
+}
+
+// For sorting extensions ids to ensure stable output.
+func (s int32Slice) Len() int { return len(s) }
+func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
+func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+
+type wkt interface {
+ XXX_WellKnownType() string
+}
+
+// marshalObject writes a struct to the Writer.
+func (m *Marshaler) marshalObject(out *errWriter, v proto.Message, indent, typeURL string) error {
+ if jsm, ok := v.(JSONPBMarshaler); ok {
+ b, err := jsm.MarshalJSONPB(m)
+ if err != nil {
+ return err
+ }
+ if typeURL != "" {
+ // we are marshaling this object to an Any type
+ var js map[string]*json.RawMessage
+ if err = json.Unmarshal(b, &js); err != nil {
+ return fmt.Errorf("type %T produced invalid JSON: %v", v, err)
+ }
+ turl, err := json.Marshal(typeURL)
+ if err != nil {
+ return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err)
+ }
+ js["@type"] = (*json.RawMessage)(&turl)
+ if b, err = json.Marshal(js); err != nil {
+ return err
+ }
+ }
+
+ out.write(string(b))
+ return out.err
+ }
+
+ s := reflect.ValueOf(v).Elem()
+
+ // Handle well-known types.
+ if wkt, ok := v.(wkt); ok {
+ switch wkt.XXX_WellKnownType() {
+ case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value",
+ "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue":
+ // "Wrappers use the same representation in JSON
+ // as the wrapped primitive type, ..."
+ sprop := proto.GetProperties(s.Type())
+ return m.marshalValue(out, sprop.Prop[0], s.Field(0), indent)
+ case "Any":
+ // Any is a bit more involved.
+ return m.marshalAny(out, v, indent)
+ case "Duration":
+ // "Generated output always contains 3, 6, or 9 fractional digits,
+ // depending on required precision."
+ s, ns := s.Field(0).Int(), s.Field(1).Int()
+ d := time.Duration(s)*time.Second + time.Duration(ns)*time.Nanosecond
+ x := fmt.Sprintf("%.9f", d.Seconds())
+ x = strings.TrimSuffix(x, "000")
+ x = strings.TrimSuffix(x, "000")
+ out.write(`"`)
+ out.write(x)
+ out.write(`s"`)
+ return out.err
+ case "Struct", "ListValue":
+ // Let marshalValue handle the `Struct.fields` map or the `ListValue.values` slice.
+ // TODO: pass the correct Properties if needed.
+ return m.marshalValue(out, &proto.Properties{}, s.Field(0), indent)
+ case "Timestamp":
+ // "RFC 3339, where generated output will always be Z-normalized
+ // and uses 3, 6 or 9 fractional digits."
+ s, ns := s.Field(0).Int(), s.Field(1).Int()
+ t := time.Unix(s, ns).UTC()
+ // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits).
+ x := t.Format("2006-01-02T15:04:05.000000000")
+ x = strings.TrimSuffix(x, "000")
+ x = strings.TrimSuffix(x, "000")
+ out.write(`"`)
+ out.write(x)
+ out.write(`Z"`)
+ return out.err
+ case "Value":
+ // Value has a single oneof.
+ kind := s.Field(0)
+ if kind.IsNil() {
+ // "absence of any variant indicates an error"
+ return errors.New("nil Value")
+ }
+ // oneof -> *T -> T -> T.F
+ x := kind.Elem().Elem().Field(0)
+ // TODO: pass the correct Properties if needed.
+ return m.marshalValue(out, &proto.Properties{}, x, indent)
+ }
+ }
+
+ out.write("{")
+ if m.Indent != "" {
+ out.write("\n")
+ }
+
+ firstField := true
+
+ if typeURL != "" {
+ if err := m.marshalTypeURL(out, indent, typeURL); err != nil {
+ return err
+ }
+ firstField = false
+ }
+
+ for i := 0; i < s.NumField(); i++ {
+ value := s.Field(i)
+ valueField := s.Type().Field(i)
+ if strings.HasPrefix(valueField.Name, "XXX_") {
+ continue
+ }
+
+ // IsNil will panic on most value kinds.
+ switch value.Kind() {
+ case reflect.Chan, reflect.Func, reflect.Interface:
+ if value.IsNil() {
+ continue
+ }
+ }
+
+ if !m.EmitDefaults {
+ switch value.Kind() {
+ case reflect.Bool:
+ if !value.Bool() {
+ continue
+ }
+ case reflect.Int32, reflect.Int64:
+ if value.Int() == 0 {
+ continue
+ }
+ case reflect.Uint32, reflect.Uint64:
+ if value.Uint() == 0 {
+ continue
+ }
+ case reflect.Float32, reflect.Float64:
+ if value.Float() == 0 {
+ continue
+ }
+ case reflect.String:
+ if value.Len() == 0 {
+ continue
+ }
+ case reflect.Map, reflect.Ptr, reflect.Slice:
+ if value.IsNil() {
+ continue
+ }
+ }
+ }
+
+ // Oneof fields need special handling.
+ if valueField.Tag.Get("protobuf_oneof") != "" {
+ // value is an interface containing &T{real_value}.
+ sv := value.Elem().Elem() // interface -> *T -> T
+ value = sv.Field(0)
+ valueField = sv.Type().Field(0)
+ }
+ prop := jsonProperties(valueField, m.OrigName)
+ if !firstField {
+ m.writeSep(out)
+ }
+ if err := m.marshalField(out, prop, value, indent); err != nil {
+ return err
+ }
+ firstField = false
+ }
+
+ // Handle proto2 extensions.
+ if ep, ok := v.(proto.Message); ok {
+ extensions := proto.RegisteredExtensions(v)
+ // Sort extensions for stable output.
+ ids := make([]int32, 0, len(extensions))
+ for id, desc := range extensions {
+ if !proto.HasExtension(ep, desc) {
+ continue
+ }
+ ids = append(ids, id)
+ }
+ sort.Sort(int32Slice(ids))
+ for _, id := range ids {
+ desc := extensions[id]
+ if desc == nil {
+ // unknown extension
+ continue
+ }
+ ext, extErr := proto.GetExtension(ep, desc)
+ if extErr != nil {
+ return extErr
+ }
+ value := reflect.ValueOf(ext)
+ var prop proto.Properties
+ prop.Parse(desc.Tag)
+ prop.JSONName = fmt.Sprintf("[%s]", desc.Name)
+ if !firstField {
+ m.writeSep(out)
+ }
+ if err := m.marshalField(out, &prop, value, indent); err != nil {
+ return err
+ }
+ firstField = false
+ }
+
+ }
+
+ if m.Indent != "" {
+ out.write("\n")
+ out.write(indent)
+ }
+ out.write("}")
+ return out.err
+}
+
+func (m *Marshaler) writeSep(out *errWriter) {
+ if m.Indent != "" {
+ out.write(",\n")
+ } else {
+ out.write(",")
+ }
+}
+
+func (m *Marshaler) marshalAny(out *errWriter, any proto.Message, indent string) error {
+ // "If the Any contains a value that has a special JSON mapping,
+ // it will be converted as follows: {"@type": xxx, "value": yyy}.
+ // Otherwise, the value will be converted into a JSON object,
+ // and the "@type" field will be inserted to indicate the actual data type."
+ v := reflect.ValueOf(any).Elem()
+ turl := v.Field(0).String()
+ val := v.Field(1).Bytes()
+
+ var msg proto.Message
+ var err error
+ if m.AnyResolver != nil {
+ msg, err = m.AnyResolver.Resolve(turl)
+ } else {
+ msg, err = defaultResolveAny(turl)
+ }
+ if err != nil {
+ return err
+ }
+
+ if err := proto.Unmarshal(val, msg); err != nil {
+ return err
+ }
+
+ if _, ok := msg.(wkt); ok {
+ out.write("{")
+ if m.Indent != "" {
+ out.write("\n")
+ }
+ if err := m.marshalTypeURL(out, indent, turl); err != nil {
+ return err
+ }
+ m.writeSep(out)
+ if m.Indent != "" {
+ out.write(indent)
+ out.write(m.Indent)
+ out.write(`"value": `)
+ } else {
+ out.write(`"value":`)
+ }
+ if err := m.marshalObject(out, msg, indent+m.Indent, ""); err != nil {
+ return err
+ }
+ if m.Indent != "" {
+ out.write("\n")
+ out.write(indent)
+ }
+ out.write("}")
+ return out.err
+ }
+
+ return m.marshalObject(out, msg, indent, turl)
+}
+
+func (m *Marshaler) marshalTypeURL(out *errWriter, indent, typeURL string) error {
+ if m.Indent != "" {
+ out.write(indent)
+ out.write(m.Indent)
+ }
+ out.write(`"@type":`)
+ if m.Indent != "" {
+ out.write(" ")
+ }
+ b, err := json.Marshal(typeURL)
+ if err != nil {
+ return err
+ }
+ out.write(string(b))
+ return out.err
+}
+
+// marshalField writes field description and value to the Writer.
+func (m *Marshaler) marshalField(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
+ if m.Indent != "" {
+ out.write(indent)
+ out.write(m.Indent)
+ }
+ out.write(`"`)
+ out.write(prop.JSONName)
+ out.write(`":`)
+ if m.Indent != "" {
+ out.write(" ")
+ }
+ if err := m.marshalValue(out, prop, v, indent); err != nil {
+ return err
+ }
+ return nil
+}
+
+// marshalValue writes the value to the Writer.
+func (m *Marshaler) marshalValue(out *errWriter, prop *proto.Properties, v reflect.Value, indent string) error {
+ var err error
+ v = reflect.Indirect(v)
+
+ // Handle nil pointer
+ if v.Kind() == reflect.Invalid {
+ out.write("null")
+ return out.err
+ }
+
+ // Handle repeated elements.
+ if v.Kind() == reflect.Slice && v.Type().Elem().Kind() != reflect.Uint8 {
+ out.write("[")
+ comma := ""
+ for i := 0; i < v.Len(); i++ {
+ sliceVal := v.Index(i)
+ out.write(comma)
+ if m.Indent != "" {
+ out.write("\n")
+ out.write(indent)
+ out.write(m.Indent)
+ out.write(m.Indent)
+ }
+ if err := m.marshalValue(out, prop, sliceVal, indent+m.Indent); err != nil {
+ return err
+ }
+ comma = ","
+ }
+ if m.Indent != "" {
+ out.write("\n")
+ out.write(indent)
+ out.write(m.Indent)
+ }
+ out.write("]")
+ return out.err
+ }
+
+ // Handle well-known types.
+ // Most are handled up in marshalObject (because 99% are messages).
+ if wkt, ok := v.Interface().(wkt); ok {
+ switch wkt.XXX_WellKnownType() {
+ case "NullValue":
+ out.write("null")
+ return out.err
+ }
+ }
+
+ // Handle enumerations.
+ if !m.EnumsAsInts && prop.Enum != "" {
+ // Unknown enum values will are stringified by the proto library as their
+ // value. Such values should _not_ be quoted or they will be interpreted
+ // as an enum string instead of their value.
+ enumStr := v.Interface().(fmt.Stringer).String()
+ var valStr string
+ if v.Kind() == reflect.Ptr {
+ valStr = strconv.Itoa(int(v.Elem().Int()))
+ } else {
+ valStr = strconv.Itoa(int(v.Int()))
+ }
+ isKnownEnum := enumStr != valStr
+ if isKnownEnum {
+ out.write(`"`)
+ }
+ out.write(enumStr)
+ if isKnownEnum {
+ out.write(`"`)
+ }
+ return out.err
+ }
+
+ // Handle nested messages.
+ if v.Kind() == reflect.Struct {
+ return m.marshalObject(out, v.Addr().Interface().(proto.Message), indent+m.Indent, "")
+ }
+
+ // Handle maps.
+ // Since Go randomizes map iteration, we sort keys for stable output.
+ if v.Kind() == reflect.Map {
+ out.write(`{`)
+ keys := v.MapKeys()
+ sort.Sort(mapKeys(keys))
+ for i, k := range keys {
+ if i > 0 {
+ out.write(`,`)
+ }
+ if m.Indent != "" {
+ out.write("\n")
+ out.write(indent)
+ out.write(m.Indent)
+ out.write(m.Indent)
+ }
+
+ b, err := json.Marshal(k.Interface())
+ if err != nil {
+ return err
+ }
+ s := string(b)
+
+ // If the JSON is not a string value, encode it again to make it one.
+ if !strings.HasPrefix(s, `"`) {
+ b, err := json.Marshal(s)
+ if err != nil {
+ return err
+ }
+ s = string(b)
+ }
+
+ out.write(s)
+ out.write(`:`)
+ if m.Indent != "" {
+ out.write(` `)
+ }
+
+ if err := m.marshalValue(out, prop, v.MapIndex(k), indent+m.Indent); err != nil {
+ return err
+ }
+ }
+ if m.Indent != "" {
+ out.write("\n")
+ out.write(indent)
+ out.write(m.Indent)
+ }
+ out.write(`}`)
+ return out.err
+ }
+
+ // Handle non-finite floats, e.g. NaN, Infinity and -Infinity.
+ if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
+ f := v.Float()
+ var sval string
+ switch {
+ case math.IsInf(f, 1):
+ sval = `"Infinity"`
+ case math.IsInf(f, -1):
+ sval = `"-Infinity"`
+ case math.IsNaN(f):
+ sval = `"NaN"`
+ }
+ if sval != "" {
+ out.write(sval)
+ return out.err
+ }
+ }
+
+ // Default handling defers to the encoding/json library.
+ b, err := json.Marshal(v.Interface())
+ if err != nil {
+ return err
+ }
+ needToQuote := string(b[0]) != `"` && (v.Kind() == reflect.Int64 || v.Kind() == reflect.Uint64)
+ if needToQuote {
+ out.write(`"`)
+ }
+ out.write(string(b))
+ if needToQuote {
+ out.write(`"`)
+ }
+ return out.err
+}
+
+// Unmarshaler is a configurable object for converting from a JSON
+// representation to a protocol buffer object.
+type Unmarshaler struct {
+ // Whether to allow messages to contain unknown fields, as opposed to
+ // failing to unmarshal.
+ AllowUnknownFields bool
+
+ // A custom URL resolver to use when unmarshaling Any messages from JSON.
+ // If unset, the default resolution strategy is to extract the
+ // fully-qualified type name from the type URL and pass that to
+ // proto.MessageType(string).
+ AnyResolver AnyResolver
+}
+
+// UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
+// This function is lenient and will decode any options permutations of the
+// related Marshaler.
+func (u *Unmarshaler) UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
+ inputValue := json.RawMessage{}
+ if err := dec.Decode(&inputValue); err != nil {
+ return err
+ }
+ return u.unmarshalValue(reflect.ValueOf(pb).Elem(), inputValue, nil)
+}
+
+// Unmarshal unmarshals a JSON object stream into a protocol
+// buffer. This function is lenient and will decode any options
+// permutations of the related Marshaler.
+func (u *Unmarshaler) Unmarshal(r io.Reader, pb proto.Message) error {
+ dec := json.NewDecoder(r)
+ return u.UnmarshalNext(dec, pb)
+}
+
+// UnmarshalNext unmarshals the next protocol buffer from a JSON object stream.
+// This function is lenient and will decode any options permutations of the
+// related Marshaler.
+func UnmarshalNext(dec *json.Decoder, pb proto.Message) error {
+ return new(Unmarshaler).UnmarshalNext(dec, pb)
+}
+
+// Unmarshal unmarshals a JSON object stream into a protocol
+// buffer. This function is lenient and will decode any options
+// permutations of the related Marshaler.
+func Unmarshal(r io.Reader, pb proto.Message) error {
+ return new(Unmarshaler).Unmarshal(r, pb)
+}
+
+// UnmarshalString will populate the fields of a protocol buffer based
+// on a JSON string. This function is lenient and will decode any options
+// permutations of the related Marshaler.
+func UnmarshalString(str string, pb proto.Message) error {
+ return new(Unmarshaler).Unmarshal(strings.NewReader(str), pb)
+}
+
+// unmarshalValue converts/copies a value into the target.
+// prop may be nil.
+func (u *Unmarshaler) unmarshalValue(target reflect.Value, inputValue json.RawMessage, prop *proto.Properties) error {
+ targetType := target.Type()
+
+ // Allocate memory for pointer fields.
+ if targetType.Kind() == reflect.Ptr {
+ // If input value is "null" and target is a pointer type, then the field should be treated as not set
+ // UNLESS the target is structpb.Value, in which case it should be set to structpb.NullValue.
+ _, isJSONPBUnmarshaler := target.Interface().(JSONPBUnmarshaler)
+ if string(inputValue) == "null" && targetType != reflect.TypeOf(&stpb.Value{}) && !isJSONPBUnmarshaler {
+ return nil
+ }
+ target.Set(reflect.New(targetType.Elem()))
+
+ return u.unmarshalValue(target.Elem(), inputValue, prop)
+ }
+
+ if jsu, ok := target.Addr().Interface().(JSONPBUnmarshaler); ok {
+ return jsu.UnmarshalJSONPB(u, []byte(inputValue))
+ }
+
+ // Handle well-known types that are not pointers.
+ if w, ok := target.Addr().Interface().(wkt); ok {
+ switch w.XXX_WellKnownType() {
+ case "DoubleValue", "FloatValue", "Int64Value", "UInt64Value",
+ "Int32Value", "UInt32Value", "BoolValue", "StringValue", "BytesValue":
+ return u.unmarshalValue(target.Field(0), inputValue, prop)
+ case "Any":
+ // Use json.RawMessage pointer type instead of value to support pre-1.8 version.
+ // 1.8 changed RawMessage.MarshalJSON from pointer type to value type, see
+ // https://github.com/golang/go/issues/14493
+ var jsonFields map[string]*json.RawMessage
+ if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
+ return err
+ }
+
+ val, ok := jsonFields["@type"]
+ if !ok || val == nil {
+ return errors.New("Any JSON doesn't have '@type'")
+ }
+
+ var turl string
+ if err := json.Unmarshal([]byte(*val), &turl); err != nil {
+ return fmt.Errorf("can't unmarshal Any's '@type': %q", *val)
+ }
+ target.Field(0).SetString(turl)
+
+ var m proto.Message
+ var err error
+ if u.AnyResolver != nil {
+ m, err = u.AnyResolver.Resolve(turl)
+ } else {
+ m, err = defaultResolveAny(turl)
+ }
+ if err != nil {
+ return err
+ }
+
+ if _, ok := m.(wkt); ok {
+ val, ok := jsonFields["value"]
+ if !ok {
+ return errors.New("Any JSON doesn't have 'value'")
+ }
+
+ if err := u.unmarshalValue(reflect.ValueOf(m).Elem(), *val, nil); err != nil {
+ return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
+ }
+ } else {
+ delete(jsonFields, "@type")
+ nestedProto, err := json.Marshal(jsonFields)
+ if err != nil {
+ return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", err)
+ }
+
+ if err = u.unmarshalValue(reflect.ValueOf(m).Elem(), nestedProto, nil); err != nil {
+ return fmt.Errorf("can't unmarshal Any nested proto %T: %v", m, err)
+ }
+ }
+
+ b, err := proto.Marshal(m)
+ if err != nil {
+ return fmt.Errorf("can't marshal proto %T into Any.Value: %v", m, err)
+ }
+ target.Field(1).SetBytes(b)
+
+ return nil
+ case "Duration":
+ unq, err := strconv.Unquote(string(inputValue))
+ if err != nil {
+ return err
+ }
+
+ d, err := time.ParseDuration(unq)
+ if err != nil {
+ return fmt.Errorf("bad Duration: %v", err)
+ }
+
+ ns := d.Nanoseconds()
+ s := ns / 1e9
+ ns %= 1e9
+ target.Field(0).SetInt(s)
+ target.Field(1).SetInt(ns)
+ return nil
+ case "Timestamp":
+ unq, err := strconv.Unquote(string(inputValue))
+ if err != nil {
+ return err
+ }
+
+ t, err := time.Parse(time.RFC3339Nano, unq)
+ if err != nil {
+ return fmt.Errorf("bad Timestamp: %v", err)
+ }
+
+ target.Field(0).SetInt(t.Unix())
+ target.Field(1).SetInt(int64(t.Nanosecond()))
+ return nil
+ case "Struct":
+ var m map[string]json.RawMessage
+ if err := json.Unmarshal(inputValue, &m); err != nil {
+ return fmt.Errorf("bad StructValue: %v", err)
+ }
+
+ target.Field(0).Set(reflect.ValueOf(map[string]*stpb.Value{}))
+ for k, jv := range m {
+ pv := &stpb.Value{}
+ if err := u.unmarshalValue(reflect.ValueOf(pv).Elem(), jv, prop); err != nil {
+ return fmt.Errorf("bad value in StructValue for key %q: %v", k, err)
+ }
+ target.Field(0).SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(pv))
+ }
+ return nil
+ case "ListValue":
+ var s []json.RawMessage
+ if err := json.Unmarshal(inputValue, &s); err != nil {
+ return fmt.Errorf("bad ListValue: %v", err)
+ }
+
+ target.Field(0).Set(reflect.ValueOf(make([]*stpb.Value, len(s), len(s))))
+ for i, sv := range s {
+ if err := u.unmarshalValue(target.Field(0).Index(i), sv, prop); err != nil {
+ return err
+ }
+ }
+ return nil
+ case "Value":
+ ivStr := string(inputValue)
+ if ivStr == "null" {
+ target.Field(0).Set(reflect.ValueOf(&stpb.Value_NullValue{}))
+ } else if v, err := strconv.ParseFloat(ivStr, 0); err == nil {
+ target.Field(0).Set(reflect.ValueOf(&stpb.Value_NumberValue{v}))
+ } else if v, err := strconv.Unquote(ivStr); err == nil {
+ target.Field(0).Set(reflect.ValueOf(&stpb.Value_StringValue{v}))
+ } else if v, err := strconv.ParseBool(ivStr); err == nil {
+ target.Field(0).Set(reflect.ValueOf(&stpb.Value_BoolValue{v}))
+ } else if err := json.Unmarshal(inputValue, &[]json.RawMessage{}); err == nil {
+ lv := &stpb.ListValue{}
+ target.Field(0).Set(reflect.ValueOf(&stpb.Value_ListValue{lv}))
+ return u.unmarshalValue(reflect.ValueOf(lv).Elem(), inputValue, prop)
+ } else if err := json.Unmarshal(inputValue, &map[string]json.RawMessage{}); err == nil {
+ sv := &stpb.Struct{}
+ target.Field(0).Set(reflect.ValueOf(&stpb.Value_StructValue{sv}))
+ return u.unmarshalValue(reflect.ValueOf(sv).Elem(), inputValue, prop)
+ } else {
+ return fmt.Errorf("unrecognized type for Value %q", ivStr)
+ }
+ return nil
+ }
+ }
+
+ // Handle enums, which have an underlying type of int32,
+ // and may appear as strings.
+ // The case of an enum appearing as a number is handled
+ // at the bottom of this function.
+ if inputValue[0] == '"' && prop != nil && prop.Enum != "" {
+ vmap := proto.EnumValueMap(prop.Enum)
+ // Don't need to do unquoting; valid enum names
+ // are from a limited character set.
+ s := inputValue[1 : len(inputValue)-1]
+ n, ok := vmap[string(s)]
+ if !ok {
+ return fmt.Errorf("unknown value %q for enum %s", s, prop.Enum)
+ }
+ if target.Kind() == reflect.Ptr { // proto2
+ target.Set(reflect.New(targetType.Elem()))
+ target = target.Elem()
+ }
+ target.SetInt(int64(n))
+ return nil
+ }
+
+ // Handle nested messages.
+ if targetType.Kind() == reflect.Struct {
+ var jsonFields map[string]json.RawMessage
+ if err := json.Unmarshal(inputValue, &jsonFields); err != nil {
+ return err
+ }
+
+ consumeField := func(prop *proto.Properties) (json.RawMessage, bool) {
+ // Be liberal in what names we accept; both orig_name and camelName are okay.
+ fieldNames := acceptedJSONFieldNames(prop)
+
+ vOrig, okOrig := jsonFields[fieldNames.orig]
+ vCamel, okCamel := jsonFields[fieldNames.camel]
+ if !okOrig && !okCamel {
+ return nil, false
+ }
+ // If, for some reason, both are present in the data, favour the camelName.
+ var raw json.RawMessage
+ if okOrig {
+ raw = vOrig
+ delete(jsonFields, fieldNames.orig)
+ }
+ if okCamel {
+ raw = vCamel
+ delete(jsonFields, fieldNames.camel)
+ }
+ return raw, true
+ }
+
+ sprops := proto.GetProperties(targetType)
+ for i := 0; i < target.NumField(); i++ {
+ ft := target.Type().Field(i)
+ if strings.HasPrefix(ft.Name, "XXX_") {
+ continue
+ }
+
+ valueForField, ok := consumeField(sprops.Prop[i])
+ if !ok {
+ continue
+ }
+
+ if err := u.unmarshalValue(target.Field(i), valueForField, sprops.Prop[i]); err != nil {
+ return err
+ }
+ }
+ // Check for any oneof fields.
+ if len(jsonFields) > 0 {
+ for _, oop := range sprops.OneofTypes {
+ raw, ok := consumeField(oop.Prop)
+ if !ok {
+ continue
+ }
+ nv := reflect.New(oop.Type.Elem())
+ target.Field(oop.Field).Set(nv)
+ if err := u.unmarshalValue(nv.Elem().Field(0), raw, oop.Prop); err != nil {
+ return err
+ }
+ }
+ }
+ // Handle proto2 extensions.
+ if len(jsonFields) > 0 {
+ if ep, ok := target.Addr().Interface().(proto.Message); ok {
+ for _, ext := range proto.RegisteredExtensions(ep) {
+ name := fmt.Sprintf("[%s]", ext.Name)
+ raw, ok := jsonFields[name]
+ if !ok {
+ continue
+ }
+ delete(jsonFields, name)
+ nv := reflect.New(reflect.TypeOf(ext.ExtensionType).Elem())
+ if err := u.unmarshalValue(nv.Elem(), raw, nil); err != nil {
+ return err
+ }
+ if err := proto.SetExtension(ep, ext, nv.Interface()); err != nil {
+ return err
+ }
+ }
+ }
+ }
+ if !u.AllowUnknownFields && len(jsonFields) > 0 {
+ // Pick any field to be the scapegoat.
+ var f string
+ for fname := range jsonFields {
+ f = fname
+ break
+ }
+ return fmt.Errorf("unknown field %q in %v", f, targetType)
+ }
+ return nil
+ }
+
+ // Handle arrays (which aren't encoded bytes)
+ if targetType.Kind() == reflect.Slice && targetType.Elem().Kind() != reflect.Uint8 {
+ var slc []json.RawMessage
+ if err := json.Unmarshal(inputValue, &slc); err != nil {
+ return err
+ }
+ if slc != nil {
+ l := len(slc)
+ target.Set(reflect.MakeSlice(targetType, l, l))
+ for i := 0; i < l; i++ {
+ if err := u.unmarshalValue(target.Index(i), slc[i], prop); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+ }
+
+ // Handle maps (whose keys are always strings)
+ if targetType.Kind() == reflect.Map {
+ var mp map[string]json.RawMessage
+ if err := json.Unmarshal(inputValue, &mp); err != nil {
+ return err
+ }
+ if mp != nil {
+ target.Set(reflect.MakeMap(targetType))
+ var keyprop, valprop *proto.Properties
+ if prop != nil {
+ // These could still be nil if the protobuf metadata is broken somehow.
+ // TODO: This won't work because the fields are unexported.
+ // We should probably just reparse them.
+ //keyprop, valprop = prop.mkeyprop, prop.mvalprop
+ }
+ for ks, raw := range mp {
+ // Unmarshal map key. The core json library already decoded the key into a
+ // string, so we handle that specially. Other types were quoted post-serialization.
+ var k reflect.Value
+ if targetType.Key().Kind() == reflect.String {
+ k = reflect.ValueOf(ks)
+ } else {
+ k = reflect.New(targetType.Key()).Elem()
+ if err := u.unmarshalValue(k, json.RawMessage(ks), keyprop); err != nil {
+ return err
+ }
+ }
+
+ // Unmarshal map value.
+ v := reflect.New(targetType.Elem()).Elem()
+ if err := u.unmarshalValue(v, raw, valprop); err != nil {
+ return err
+ }
+ target.SetMapIndex(k, v)
+ }
+ }
+ return nil
+ }
+
+ // 64-bit integers can be encoded as strings. In this case we drop
+ // the quotes and proceed as normal.
+ isNum := targetType.Kind() == reflect.Int64 || targetType.Kind() == reflect.Uint64
+ if isNum && strings.HasPrefix(string(inputValue), `"`) {
+ inputValue = inputValue[1 : len(inputValue)-1]
+ }
+
+ // Non-finite numbers can be encoded as strings.
+ isFloat := targetType.Kind() == reflect.Float32 || targetType.Kind() == reflect.Float64
+ if isFloat {
+ if num, ok := nonFinite[string(inputValue)]; ok {
+ target.SetFloat(num)
+ return nil
+ }
+ }
+
+ // Use the encoding/json for parsing other value types.
+ return json.Unmarshal(inputValue, target.Addr().Interface())
+}
+
+// jsonProperties returns parsed proto.Properties for the field and corrects JSONName attribute.
+func jsonProperties(f reflect.StructField, origName bool) *proto.Properties {
+ var prop proto.Properties
+ prop.Init(f.Type, f.Name, f.Tag.Get("protobuf"), &f)
+ if origName || prop.JSONName == "" {
+ prop.JSONName = prop.OrigName
+ }
+ return &prop
+}
+
+type fieldNames struct {
+ orig, camel string
+}
+
+func acceptedJSONFieldNames(prop *proto.Properties) fieldNames {
+ opts := fieldNames{orig: prop.OrigName, camel: prop.OrigName}
+ if prop.JSONName != "" {
+ opts.camel = prop.JSONName
+ }
+ return opts
+}
+
+// Writer wrapper inspired by https://blog.golang.org/errors-are-values
+type errWriter struct {
+ writer io.Writer
+ err error
+}
+
+func (w *errWriter) write(str string) {
+ if w.err != nil {
+ return
+ }
+ _, w.err = w.writer.Write([]byte(str))
+}
+
+// Map fields may have key types of non-float scalars, strings and enums.
+// The easiest way to sort them in some deterministic order is to use fmt.
+// If this turns out to be inefficient we can always consider other options,
+// such as doing a Schwartzian transform.
+//
+// Numeric keys are sorted in numeric order per
+// https://developers.google.com/protocol-buffers/docs/proto#maps.
+type mapKeys []reflect.Value
+
+func (s mapKeys) Len() int { return len(s) }
+func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+func (s mapKeys) Less(i, j int) bool {
+ if k := s[i].Kind(); k == s[j].Kind() {
+ switch k {
+ case reflect.Int32, reflect.Int64:
+ return s[i].Int() < s[j].Int()
+ case reflect.Uint32, reflect.Uint64:
+ return s[i].Uint() < s[j].Uint()
+ }
+ }
+ return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface())
+}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go
new file mode 100644
index 0000000..2428d05
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test.go
@@ -0,0 +1,896 @@
+// 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 jsonpb
+
+import (
+ "bytes"
+ "encoding/json"
+ "io"
+ "math"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/golang/protobuf/proto"
+
+ pb "github.com/golang/protobuf/jsonpb/jsonpb_test_proto"
+ proto3pb "github.com/golang/protobuf/proto/proto3_proto"
+ "github.com/golang/protobuf/ptypes"
+ anypb "github.com/golang/protobuf/ptypes/any"
+ durpb "github.com/golang/protobuf/ptypes/duration"
+ stpb "github.com/golang/protobuf/ptypes/struct"
+ tspb "github.com/golang/protobuf/ptypes/timestamp"
+ wpb "github.com/golang/protobuf/ptypes/wrappers"
+)
+
+var (
+ marshaler = Marshaler{}
+
+ marshalerAllOptions = Marshaler{
+ Indent: " ",
+ }
+
+ simpleObject = &pb.Simple{
+ OInt32: proto.Int32(-32),
+ OInt64: proto.Int64(-6400000000),
+ OUint32: proto.Uint32(32),
+ OUint64: proto.Uint64(6400000000),
+ OSint32: proto.Int32(-13),
+ OSint64: proto.Int64(-2600000000),
+ OFloat: proto.Float32(3.14),
+ ODouble: proto.Float64(6.02214179e23),
+ OBool: proto.Bool(true),
+ OString: proto.String("hello \"there\""),
+ OBytes: []byte("beep boop"),
+ }
+
+ simpleObjectJSON = `{` +
+ `"oBool":true,` +
+ `"oInt32":-32,` +
+ `"oInt64":"-6400000000",` +
+ `"oUint32":32,` +
+ `"oUint64":"6400000000",` +
+ `"oSint32":-13,` +
+ `"oSint64":"-2600000000",` +
+ `"oFloat":3.14,` +
+ `"oDouble":6.02214179e+23,` +
+ `"oString":"hello \"there\"",` +
+ `"oBytes":"YmVlcCBib29w"` +
+ `}`
+
+ simpleObjectPrettyJSON = `{
+ "oBool": true,
+ "oInt32": -32,
+ "oInt64": "-6400000000",
+ "oUint32": 32,
+ "oUint64": "6400000000",
+ "oSint32": -13,
+ "oSint64": "-2600000000",
+ "oFloat": 3.14,
+ "oDouble": 6.02214179e+23,
+ "oString": "hello \"there\"",
+ "oBytes": "YmVlcCBib29w"
+}`
+
+ repeatsObject = &pb.Repeats{
+ RBool: []bool{true, false, true},
+ RInt32: []int32{-3, -4, -5},
+ RInt64: []int64{-123456789, -987654321},
+ RUint32: []uint32{1, 2, 3},
+ RUint64: []uint64{6789012345, 3456789012},
+ RSint32: []int32{-1, -2, -3},
+ RSint64: []int64{-6789012345, -3456789012},
+ RFloat: []float32{3.14, 6.28},
+ RDouble: []float64{299792458 * 1e20, 6.62606957e-34},
+ RString: []string{"happy", "days"},
+ RBytes: [][]byte{[]byte("skittles"), []byte("m&m's")},
+ }
+
+ repeatsObjectJSON = `{` +
+ `"rBool":[true,false,true],` +
+ `"rInt32":[-3,-4,-5],` +
+ `"rInt64":["-123456789","-987654321"],` +
+ `"rUint32":[1,2,3],` +
+ `"rUint64":["6789012345","3456789012"],` +
+ `"rSint32":[-1,-2,-3],` +
+ `"rSint64":["-6789012345","-3456789012"],` +
+ `"rFloat":[3.14,6.28],` +
+ `"rDouble":[2.99792458e+28,6.62606957e-34],` +
+ `"rString":["happy","days"],` +
+ `"rBytes":["c2tpdHRsZXM=","bSZtJ3M="]` +
+ `}`
+
+ repeatsObjectPrettyJSON = `{
+ "rBool": [
+ true,
+ false,
+ true
+ ],
+ "rInt32": [
+ -3,
+ -4,
+ -5
+ ],
+ "rInt64": [
+ "-123456789",
+ "-987654321"
+ ],
+ "rUint32": [
+ 1,
+ 2,
+ 3
+ ],
+ "rUint64": [
+ "6789012345",
+ "3456789012"
+ ],
+ "rSint32": [
+ -1,
+ -2,
+ -3
+ ],
+ "rSint64": [
+ "-6789012345",
+ "-3456789012"
+ ],
+ "rFloat": [
+ 3.14,
+ 6.28
+ ],
+ "rDouble": [
+ 2.99792458e+28,
+ 6.62606957e-34
+ ],
+ "rString": [
+ "happy",
+ "days"
+ ],
+ "rBytes": [
+ "c2tpdHRsZXM=",
+ "bSZtJ3M="
+ ]
+}`
+
+ innerSimple = &pb.Simple{OInt32: proto.Int32(-32)}
+ innerSimple2 = &pb.Simple{OInt64: proto.Int64(25)}
+ innerRepeats = &pb.Repeats{RString: []string{"roses", "red"}}
+ innerRepeats2 = &pb.Repeats{RString: []string{"violets", "blue"}}
+ complexObject = &pb.Widget{
+ Color: pb.Widget_GREEN.Enum(),
+ RColor: []pb.Widget_Color{pb.Widget_RED, pb.Widget_GREEN, pb.Widget_BLUE},
+ Simple: innerSimple,
+ RSimple: []*pb.Simple{innerSimple, innerSimple2},
+ Repeats: innerRepeats,
+ RRepeats: []*pb.Repeats{innerRepeats, innerRepeats2},
+ }
+
+ complexObjectJSON = `{"color":"GREEN",` +
+ `"rColor":["RED","GREEN","BLUE"],` +
+ `"simple":{"oInt32":-32},` +
+ `"rSimple":[{"oInt32":-32},{"oInt64":"25"}],` +
+ `"repeats":{"rString":["roses","red"]},` +
+ `"rRepeats":[{"rString":["roses","red"]},{"rString":["violets","blue"]}]` +
+ `}`
+
+ complexObjectPrettyJSON = `{
+ "color": "GREEN",
+ "rColor": [
+ "RED",
+ "GREEN",
+ "BLUE"
+ ],
+ "simple": {
+ "oInt32": -32
+ },
+ "rSimple": [
+ {
+ "oInt32": -32
+ },
+ {
+ "oInt64": "25"
+ }
+ ],
+ "repeats": {
+ "rString": [
+ "roses",
+ "red"
+ ]
+ },
+ "rRepeats": [
+ {
+ "rString": [
+ "roses",
+ "red"
+ ]
+ },
+ {
+ "rString": [
+ "violets",
+ "blue"
+ ]
+ }
+ ]
+}`
+
+ colorPrettyJSON = `{
+ "color": 2
+}`
+
+ colorListPrettyJSON = `{
+ "color": 1000,
+ "rColor": [
+ "RED"
+ ]
+}`
+
+ nummyPrettyJSON = `{
+ "nummy": {
+ "1": 2,
+ "3": 4
+ }
+}`
+
+ objjyPrettyJSON = `{
+ "objjy": {
+ "1": {
+ "dub": 1
+ }
+ }
+}`
+ realNumber = &pb.Real{Value: proto.Float64(3.14159265359)}
+ realNumberName = "Pi"
+ complexNumber = &pb.Complex{Imaginary: proto.Float64(0.5772156649)}
+ realNumberJSON = `{` +
+ `"value":3.14159265359,` +
+ `"[jsonpb.Complex.real_extension]":{"imaginary":0.5772156649},` +
+ `"[jsonpb.name]":"Pi"` +
+ `}`
+
+ anySimple = &pb.KnownTypes{
+ An: &anypb.Any{
+ TypeUrl: "something.example.com/jsonpb.Simple",
+ Value: []byte{
+ // &pb.Simple{OBool:true}
+ 1 << 3, 1,
+ },
+ },
+ }
+ anySimpleJSON = `{"an":{"@type":"something.example.com/jsonpb.Simple","oBool":true}}`
+ anySimplePrettyJSON = `{
+ "an": {
+ "@type": "something.example.com/jsonpb.Simple",
+ "oBool": true
+ }
+}`
+
+ anyWellKnown = &pb.KnownTypes{
+ An: &anypb.Any{
+ TypeUrl: "type.googleapis.com/google.protobuf.Duration",
+ Value: []byte{
+ // &durpb.Duration{Seconds: 1, Nanos: 212000000 }
+ 1 << 3, 1, // seconds
+ 2 << 3, 0x80, 0xba, 0x8b, 0x65, // nanos
+ },
+ },
+ }
+ anyWellKnownJSON = `{"an":{"@type":"type.googleapis.com/google.protobuf.Duration","value":"1.212s"}}`
+ anyWellKnownPrettyJSON = `{
+ "an": {
+ "@type": "type.googleapis.com/google.protobuf.Duration",
+ "value": "1.212s"
+ }
+}`
+
+ nonFinites = &pb.NonFinites{
+ FNan: proto.Float32(float32(math.NaN())),
+ FPinf: proto.Float32(float32(math.Inf(1))),
+ FNinf: proto.Float32(float32(math.Inf(-1))),
+ DNan: proto.Float64(float64(math.NaN())),
+ DPinf: proto.Float64(float64(math.Inf(1))),
+ DNinf: proto.Float64(float64(math.Inf(-1))),
+ }
+ nonFinitesJSON = `{` +
+ `"fNan":"NaN",` +
+ `"fPinf":"Infinity",` +
+ `"fNinf":"-Infinity",` +
+ `"dNan":"NaN",` +
+ `"dPinf":"Infinity",` +
+ `"dNinf":"-Infinity"` +
+ `}`
+)
+
+func init() {
+ if err := proto.SetExtension(realNumber, pb.E_Name, &realNumberName); err != nil {
+ panic(err)
+ }
+ if err := proto.SetExtension(realNumber, pb.E_Complex_RealExtension, complexNumber); err != nil {
+ panic(err)
+ }
+}
+
+var marshalingTests = []struct {
+ desc string
+ marshaler Marshaler
+ pb proto.Message
+ json string
+}{
+ {"simple flat object", marshaler, simpleObject, simpleObjectJSON},
+ {"simple pretty object", marshalerAllOptions, simpleObject, simpleObjectPrettyJSON},
+ {"non-finite floats fields object", marshaler, nonFinites, nonFinitesJSON},
+ {"repeated fields flat object", marshaler, repeatsObject, repeatsObjectJSON},
+ {"repeated fields pretty object", marshalerAllOptions, repeatsObject, repeatsObjectPrettyJSON},
+ {"nested message/enum flat object", marshaler, complexObject, complexObjectJSON},
+ {"nested message/enum pretty object", marshalerAllOptions, complexObject, complexObjectPrettyJSON},
+ {"enum-string flat object", Marshaler{},
+ &pb.Widget{Color: pb.Widget_BLUE.Enum()}, `{"color":"BLUE"}`},
+ {"enum-value pretty object", Marshaler{EnumsAsInts: true, Indent: " "},
+ &pb.Widget{Color: pb.Widget_BLUE.Enum()}, colorPrettyJSON},
+ {"unknown enum value object", marshalerAllOptions,
+ &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}, colorListPrettyJSON},
+ {"repeated proto3 enum", Marshaler{},
+ &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
+ proto3pb.Message_PUNS,
+ proto3pb.Message_SLAPSTICK,
+ }},
+ `{"rFunny":["PUNS","SLAPSTICK"]}`},
+ {"repeated proto3 enum as int", Marshaler{EnumsAsInts: true},
+ &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
+ proto3pb.Message_PUNS,
+ proto3pb.Message_SLAPSTICK,
+ }},
+ `{"rFunny":[1,2]}`},
+ {"empty value", marshaler, &pb.Simple3{}, `{}`},
+ {"empty value emitted", Marshaler{EmitDefaults: true}, &pb.Simple3{}, `{"dub":0}`},
+ {"empty repeated emitted", Marshaler{EmitDefaults: true}, &pb.SimpleSlice3{}, `{"slices":[]}`},
+ {"empty map emitted", Marshaler{EmitDefaults: true}, &pb.SimpleMap3{}, `{"stringy":{}}`},
+ {"nested struct null", Marshaler{EmitDefaults: true}, &pb.SimpleNull3{}, `{"simple":null}`},
+ {"map", marshaler, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, `{"nummy":{"1":2,"3":4}}`},
+ {"map", marshalerAllOptions, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}, nummyPrettyJSON},
+ {"map", marshaler,
+ &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}},
+ `{"strry":{"\"one\"":"two","three":"four"}}`},
+ {"map", marshaler,
+ &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, `{"objjy":{"1":{"dub":1}}}`},
+ {"map", marshalerAllOptions,
+ &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}, objjyPrettyJSON},
+ {"map", marshaler, &pb.Mappy{Buggy: map[int64]string{1234: "yup"}},
+ `{"buggy":{"1234":"yup"}}`},
+ {"map", marshaler, &pb.Mappy{Booly: map[bool]bool{false: true}}, `{"booly":{"false":true}}`},
+ // TODO: This is broken.
+ //{"map", marshaler, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":"ROMAN"}`},
+ {"map", Marshaler{EnumsAsInts: true}, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}, `{"enumy":{"XIV":2}}`},
+ {"map", marshaler, &pb.Mappy{S32Booly: map[int32]bool{1: true, 3: false, 10: true, 12: false}}, `{"s32booly":{"1":true,"3":false,"10":true,"12":false}}`},
+ {"map", marshaler, &pb.Mappy{S64Booly: map[int64]bool{1: true, 3: false, 10: true, 12: false}}, `{"s64booly":{"1":true,"3":false,"10":true,"12":false}}`},
+ {"map", marshaler, &pb.Mappy{U32Booly: map[uint32]bool{1: true, 3: false, 10: true, 12: false}}, `{"u32booly":{"1":true,"3":false,"10":true,"12":false}}`},
+ {"map", marshaler, &pb.Mappy{U64Booly: map[uint64]bool{1: true, 3: false, 10: true, 12: false}}, `{"u64booly":{"1":true,"3":false,"10":true,"12":false}}`},
+ {"proto2 map", marshaler, &pb.Maps{MInt64Str: map[int64]string{213: "cat"}},
+ `{"mInt64Str":{"213":"cat"}}`},
+ {"proto2 map", marshaler,
+ &pb.Maps{MBoolSimple: map[bool]*pb.Simple{true: {OInt32: proto.Int32(1)}}},
+ `{"mBoolSimple":{"true":{"oInt32":1}}}`},
+ {"oneof, not set", marshaler, &pb.MsgWithOneof{}, `{}`},
+ {"oneof, set", marshaler, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Title{"Grand Poobah"}}, `{"title":"Grand Poobah"}`},
+ {"force orig_name", Marshaler{OrigName: true}, &pb.Simple{OInt32: proto.Int32(4)},
+ `{"o_int32":4}`},
+ {"proto2 extension", marshaler, realNumber, realNumberJSON},
+ {"Any with message", marshaler, anySimple, anySimpleJSON},
+ {"Any with message and indent", marshalerAllOptions, anySimple, anySimplePrettyJSON},
+ {"Any with WKT", marshaler, anyWellKnown, anyWellKnownJSON},
+ {"Any with WKT and indent", marshalerAllOptions, anyWellKnown, anyWellKnownPrettyJSON},
+ {"Duration", marshaler, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}, `{"dur":"3.000s"}`},
+ {"Struct", marshaler, &pb.KnownTypes{St: &stpb.Struct{
+ Fields: map[string]*stpb.Value{
+ "one": {Kind: &stpb.Value_StringValue{"loneliest number"}},
+ "two": {Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}},
+ },
+ }}, `{"st":{"one":"loneliest number","two":null}}`},
+ {"empty ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{}}, `{"lv":[]}`},
+ {"basic ListValue", marshaler, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{
+ {Kind: &stpb.Value_StringValue{"x"}},
+ {Kind: &stpb.Value_NullValue{}},
+ {Kind: &stpb.Value_NumberValue{3}},
+ {Kind: &stpb.Value_BoolValue{true}},
+ }}}, `{"lv":["x",null,3,true]}`},
+ {"Timestamp", marshaler, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}, `{"ts":"2014-05-13T16:53:20.021Z"}`},
+ {"number Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}, `{"val":1}`},
+ {"null Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}, `{"val":null}`},
+ {"string number value", marshaler, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}, `{"val":"9223372036854775807"}`},
+ {"list of lists Value", marshaler, &pb.KnownTypes{Val: &stpb.Value{
+ Kind: &stpb.Value_ListValue{&stpb.ListValue{
+ Values: []*stpb.Value{
+ {Kind: &stpb.Value_StringValue{"x"}},
+ {Kind: &stpb.Value_ListValue{&stpb.ListValue{
+ Values: []*stpb.Value{
+ {Kind: &stpb.Value_ListValue{&stpb.ListValue{
+ Values: []*stpb.Value{{Kind: &stpb.Value_StringValue{"y"}}},
+ }}},
+ {Kind: &stpb.Value_StringValue{"z"}},
+ },
+ }}},
+ },
+ }},
+ }}, `{"val":["x",[["y"],"z"]]}`},
+
+ {"DoubleValue", marshaler, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}, `{"dbl":1.2}`},
+ {"FloatValue", marshaler, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}, `{"flt":1.2}`},
+ {"Int64Value", marshaler, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}, `{"i64":"-3"}`},
+ {"UInt64Value", marshaler, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}, `{"u64":"3"}`},
+ {"Int32Value", marshaler, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}, `{"i32":-4}`},
+ {"UInt32Value", marshaler, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}, `{"u32":4}`},
+ {"BoolValue", marshaler, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}, `{"bool":true}`},
+ {"StringValue", marshaler, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}, `{"str":"plush"}`},
+ {"BytesValue", marshaler, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}, `{"bytes":"d293"}`},
+}
+
+func TestMarshaling(t *testing.T) {
+ for _, tt := range marshalingTests {
+ json, err := tt.marshaler.MarshalToString(tt.pb)
+ if err != nil {
+ t.Errorf("%s: marshaling error: %v", tt.desc, err)
+ } else if tt.json != json {
+ t.Errorf("%s: got [%v] want [%v]", tt.desc, json, tt.json)
+ }
+ }
+}
+
+func TestMarshalJSONPBMarshaler(t *testing.T) {
+ rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }`
+ msg := dynamicMessage{rawJson: rawJson}
+ str, err := new(Marshaler).MarshalToString(&msg)
+ if err != nil {
+ t.Errorf("an unexpected error occurred when marshalling JSONPBMarshaler: %v", err)
+ }
+ if str != rawJson {
+ t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, rawJson)
+ }
+}
+
+func TestMarshalAnyJSONPBMarshaler(t *testing.T) {
+ msg := dynamicMessage{rawJson: `{ "foo": "bar", "baz": [0, 1, 2, 3] }`}
+ a, err := ptypes.MarshalAny(&msg)
+ if err != nil {
+ t.Errorf("an unexpected error occurred when marshalling to Any: %v", err)
+ }
+ str, err := new(Marshaler).MarshalToString(a)
+ if err != nil {
+ t.Errorf("an unexpected error occurred when marshalling Any to JSON: %v", err)
+ }
+ // after custom marshaling, it's round-tripped through JSON decoding/encoding already,
+ // so the keys are sorted, whitespace is compacted, and "@type" key has been added
+ expected := `{"@type":"type.googleapis.com/` + dynamicMessageName + `","baz":[0,1,2,3],"foo":"bar"}`
+ if str != expected {
+ t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", str, expected)
+ }
+}
+
+var unmarshalingTests = []struct {
+ desc string
+ unmarshaler Unmarshaler
+ json string
+ pb proto.Message
+}{
+ {"simple flat object", Unmarshaler{}, simpleObjectJSON, simpleObject},
+ {"simple pretty object", Unmarshaler{}, simpleObjectPrettyJSON, simpleObject},
+ {"repeated fields flat object", Unmarshaler{}, repeatsObjectJSON, repeatsObject},
+ {"repeated fields pretty object", Unmarshaler{}, repeatsObjectPrettyJSON, repeatsObject},
+ {"nested message/enum flat object", Unmarshaler{}, complexObjectJSON, complexObject},
+ {"nested message/enum pretty object", Unmarshaler{}, complexObjectPrettyJSON, complexObject},
+ {"enum-string object", Unmarshaler{}, `{"color":"BLUE"}`, &pb.Widget{Color: pb.Widget_BLUE.Enum()}},
+ {"enum-value object", Unmarshaler{}, "{\n \"color\": 2\n}", &pb.Widget{Color: pb.Widget_BLUE.Enum()}},
+ {"unknown field with allowed option", Unmarshaler{AllowUnknownFields: true}, `{"unknown": "foo"}`, new(pb.Simple)},
+ {"proto3 enum string", Unmarshaler{}, `{"hilarity":"PUNS"}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}},
+ {"proto3 enum value", Unmarshaler{}, `{"hilarity":1}`, &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}},
+ {"unknown enum value object",
+ Unmarshaler{},
+ "{\n \"color\": 1000,\n \"r_color\": [\n \"RED\"\n ]\n}",
+ &pb.Widget{Color: pb.Widget_Color(1000).Enum(), RColor: []pb.Widget_Color{pb.Widget_RED}}},
+ {"repeated proto3 enum", Unmarshaler{}, `{"rFunny":["PUNS","SLAPSTICK"]}`,
+ &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
+ proto3pb.Message_PUNS,
+ proto3pb.Message_SLAPSTICK,
+ }}},
+ {"repeated proto3 enum as int", Unmarshaler{}, `{"rFunny":[1,2]}`,
+ &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
+ proto3pb.Message_PUNS,
+ proto3pb.Message_SLAPSTICK,
+ }}},
+ {"repeated proto3 enum as mix of strings and ints", Unmarshaler{}, `{"rFunny":["PUNS",2]}`,
+ &proto3pb.Message{RFunny: []proto3pb.Message_Humour{
+ proto3pb.Message_PUNS,
+ proto3pb.Message_SLAPSTICK,
+ }}},
+ {"unquoted int64 object", Unmarshaler{}, `{"oInt64":-314}`, &pb.Simple{OInt64: proto.Int64(-314)}},
+ {"unquoted uint64 object", Unmarshaler{}, `{"oUint64":123}`, &pb.Simple{OUint64: proto.Uint64(123)}},
+ {"NaN", Unmarshaler{}, `{"oDouble":"NaN"}`, &pb.Simple{ODouble: proto.Float64(math.NaN())}},
+ {"Inf", Unmarshaler{}, `{"oFloat":"Infinity"}`, &pb.Simple{OFloat: proto.Float32(float32(math.Inf(1)))}},
+ {"-Inf", Unmarshaler{}, `{"oDouble":"-Infinity"}`, &pb.Simple{ODouble: proto.Float64(math.Inf(-1))}},
+ {"map", Unmarshaler{}, `{"nummy":{"1":2,"3":4}}`, &pb.Mappy{Nummy: map[int64]int32{1: 2, 3: 4}}},
+ {"map", Unmarshaler{}, `{"strry":{"\"one\"":"two","three":"four"}}`, &pb.Mappy{Strry: map[string]string{`"one"`: "two", "three": "four"}}},
+ {"map", Unmarshaler{}, `{"objjy":{"1":{"dub":1}}}`, &pb.Mappy{Objjy: map[int32]*pb.Simple3{1: {Dub: 1}}}},
+ {"proto2 extension", Unmarshaler{}, realNumberJSON, realNumber},
+ {"Any with message", Unmarshaler{}, anySimpleJSON, anySimple},
+ {"Any with message and indent", Unmarshaler{}, anySimplePrettyJSON, anySimple},
+ {"Any with WKT", Unmarshaler{}, anyWellKnownJSON, anyWellKnown},
+ {"Any with WKT and indent", Unmarshaler{}, anyWellKnownPrettyJSON, anyWellKnown},
+ // TODO: This is broken.
+ //{"map", Unmarshaler{}, `{"enumy":{"XIV":"ROMAN"}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}},
+ {"map", Unmarshaler{}, `{"enumy":{"XIV":2}}`, &pb.Mappy{Enumy: map[string]pb.Numeral{"XIV": pb.Numeral_ROMAN}}},
+ {"oneof", Unmarshaler{}, `{"salary":31000}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Salary{31000}}},
+ {"oneof spec name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}},
+ {"oneof orig_name", Unmarshaler{}, `{"Country":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_Country{"Australia"}}},
+ {"oneof spec name2", Unmarshaler{}, `{"homeAddress":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}},
+ {"oneof orig_name2", Unmarshaler{}, `{"home_address":"Australia"}`, &pb.MsgWithOneof{Union: &pb.MsgWithOneof_HomeAddress{"Australia"}}},
+ {"orig_name input", Unmarshaler{}, `{"o_bool":true}`, &pb.Simple{OBool: proto.Bool(true)}},
+ {"camelName input", Unmarshaler{}, `{"oBool":true}`, &pb.Simple{OBool: proto.Bool(true)}},
+
+ {"Duration", Unmarshaler{}, `{"dur":"3.000s"}`, &pb.KnownTypes{Dur: &durpb.Duration{Seconds: 3}}},
+ {"null Duration", Unmarshaler{}, `{"dur":null}`, &pb.KnownTypes{Dur: nil}},
+ {"Timestamp", Unmarshaler{}, `{"ts":"2014-05-13T16:53:20.021Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: 14e8, Nanos: 21e6}}},
+ {"PreEpochTimestamp", Unmarshaler{}, `{"ts":"1969-12-31T23:59:58.999999995Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -2, Nanos: 999999995}}},
+ {"ZeroTimeTimestamp", Unmarshaler{}, `{"ts":"0001-01-01T00:00:00Z"}`, &pb.KnownTypes{Ts: &tspb.Timestamp{Seconds: -62135596800, Nanos: 0}}},
+ {"null Timestamp", Unmarshaler{}, `{"ts":null}`, &pb.KnownTypes{Ts: nil}},
+ {"null Struct", Unmarshaler{}, `{"st": null}`, &pb.KnownTypes{St: nil}},
+ {"empty Struct", Unmarshaler{}, `{"st": {}}`, &pb.KnownTypes{St: &stpb.Struct{}}},
+ {"basic Struct", Unmarshaler{}, `{"st": {"a": "x", "b": null, "c": 3, "d": true}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{
+ "a": {Kind: &stpb.Value_StringValue{"x"}},
+ "b": {Kind: &stpb.Value_NullValue{}},
+ "c": {Kind: &stpb.Value_NumberValue{3}},
+ "d": {Kind: &stpb.Value_BoolValue{true}},
+ }}}},
+ {"nested Struct", Unmarshaler{}, `{"st": {"a": {"b": 1, "c": [{"d": true}, "f"]}}}`, &pb.KnownTypes{St: &stpb.Struct{Fields: map[string]*stpb.Value{
+ "a": {Kind: &stpb.Value_StructValue{&stpb.Struct{Fields: map[string]*stpb.Value{
+ "b": {Kind: &stpb.Value_NumberValue{1}},
+ "c": {Kind: &stpb.Value_ListValue{&stpb.ListValue{Values: []*stpb.Value{
+ {Kind: &stpb.Value_StructValue{&stpb.Struct{Fields: map[string]*stpb.Value{"d": {Kind: &stpb.Value_BoolValue{true}}}}}},
+ {Kind: &stpb.Value_StringValue{"f"}},
+ }}}},
+ }}}},
+ }}}},
+ {"null ListValue", Unmarshaler{}, `{"lv": null}`, &pb.KnownTypes{Lv: nil}},
+ {"empty ListValue", Unmarshaler{}, `{"lv": []}`, &pb.KnownTypes{Lv: &stpb.ListValue{}}},
+ {"basic ListValue", Unmarshaler{}, `{"lv": ["x", null, 3, true]}`, &pb.KnownTypes{Lv: &stpb.ListValue{Values: []*stpb.Value{
+ {Kind: &stpb.Value_StringValue{"x"}},
+ {Kind: &stpb.Value_NullValue{}},
+ {Kind: &stpb.Value_NumberValue{3}},
+ {Kind: &stpb.Value_BoolValue{true}},
+ }}}},
+ {"number Value", Unmarshaler{}, `{"val":1}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NumberValue{1}}}},
+ {"null Value", Unmarshaler{}, `{"val":null}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_NullValue{stpb.NullValue_NULL_VALUE}}}},
+ {"bool Value", Unmarshaler{}, `{"val":true}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_BoolValue{true}}}},
+ {"string Value", Unmarshaler{}, `{"val":"x"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"x"}}}},
+ {"string number value", Unmarshaler{}, `{"val":"9223372036854775807"}`, &pb.KnownTypes{Val: &stpb.Value{Kind: &stpb.Value_StringValue{"9223372036854775807"}}}},
+ {"list of lists Value", Unmarshaler{}, `{"val":["x", [["y"], "z"]]}`, &pb.KnownTypes{Val: &stpb.Value{
+ Kind: &stpb.Value_ListValue{&stpb.ListValue{
+ Values: []*stpb.Value{
+ {Kind: &stpb.Value_StringValue{"x"}},
+ {Kind: &stpb.Value_ListValue{&stpb.ListValue{
+ Values: []*stpb.Value{
+ {Kind: &stpb.Value_ListValue{&stpb.ListValue{
+ Values: []*stpb.Value{{Kind: &stpb.Value_StringValue{"y"}}},
+ }}},
+ {Kind: &stpb.Value_StringValue{"z"}},
+ },
+ }}},
+ },
+ }}}}},
+
+ {"DoubleValue", Unmarshaler{}, `{"dbl":1.2}`, &pb.KnownTypes{Dbl: &wpb.DoubleValue{Value: 1.2}}},
+ {"FloatValue", Unmarshaler{}, `{"flt":1.2}`, &pb.KnownTypes{Flt: &wpb.FloatValue{Value: 1.2}}},
+ {"Int64Value", Unmarshaler{}, `{"i64":"-3"}`, &pb.KnownTypes{I64: &wpb.Int64Value{Value: -3}}},
+ {"UInt64Value", Unmarshaler{}, `{"u64":"3"}`, &pb.KnownTypes{U64: &wpb.UInt64Value{Value: 3}}},
+ {"Int32Value", Unmarshaler{}, `{"i32":-4}`, &pb.KnownTypes{I32: &wpb.Int32Value{Value: -4}}},
+ {"UInt32Value", Unmarshaler{}, `{"u32":4}`, &pb.KnownTypes{U32: &wpb.UInt32Value{Value: 4}}},
+ {"BoolValue", Unmarshaler{}, `{"bool":true}`, &pb.KnownTypes{Bool: &wpb.BoolValue{Value: true}}},
+ {"StringValue", Unmarshaler{}, `{"str":"plush"}`, &pb.KnownTypes{Str: &wpb.StringValue{Value: "plush"}}},
+ {"BytesValue", Unmarshaler{}, `{"bytes":"d293"}`, &pb.KnownTypes{Bytes: &wpb.BytesValue{Value: []byte("wow")}}},
+
+ // Ensure that `null` as a value ends up with a nil pointer instead of a [type]Value struct.
+ {"null DoubleValue", Unmarshaler{}, `{"dbl":null}`, &pb.KnownTypes{Dbl: nil}},
+ {"null FloatValue", Unmarshaler{}, `{"flt":null}`, &pb.KnownTypes{Flt: nil}},
+ {"null Int64Value", Unmarshaler{}, `{"i64":null}`, &pb.KnownTypes{I64: nil}},
+ {"null UInt64Value", Unmarshaler{}, `{"u64":null}`, &pb.KnownTypes{U64: nil}},
+ {"null Int32Value", Unmarshaler{}, `{"i32":null}`, &pb.KnownTypes{I32: nil}},
+ {"null UInt32Value", Unmarshaler{}, `{"u32":null}`, &pb.KnownTypes{U32: nil}},
+ {"null BoolValue", Unmarshaler{}, `{"bool":null}`, &pb.KnownTypes{Bool: nil}},
+ {"null StringValue", Unmarshaler{}, `{"str":null}`, &pb.KnownTypes{Str: nil}},
+ {"null BytesValue", Unmarshaler{}, `{"bytes":null}`, &pb.KnownTypes{Bytes: nil}},
+}
+
+func TestUnmarshaling(t *testing.T) {
+ for _, tt := range unmarshalingTests {
+ // Make a new instance of the type of our expected object.
+ p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message)
+
+ err := tt.unmarshaler.Unmarshal(strings.NewReader(tt.json), p)
+ if err != nil {
+ t.Errorf("%s: %v", tt.desc, err)
+ continue
+ }
+
+ // For easier diffs, compare text strings of the protos.
+ exp := proto.MarshalTextString(tt.pb)
+ act := proto.MarshalTextString(p)
+ if string(exp) != string(act) {
+ t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp)
+ }
+ }
+}
+
+func TestUnmarshalNullArray(t *testing.T) {
+ var repeats pb.Repeats
+ if err := UnmarshalString(`{"rBool":null}`, &repeats); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(repeats, pb.Repeats{}) {
+ t.Errorf("got non-nil fields in [%#v]", repeats)
+ }
+}
+
+func TestUnmarshalNullObject(t *testing.T) {
+ var maps pb.Maps
+ if err := UnmarshalString(`{"mInt64Str":null}`, &maps); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(maps, pb.Maps{}) {
+ t.Errorf("got non-nil fields in [%#v]", maps)
+ }
+}
+
+func TestUnmarshalNext(t *testing.T) {
+ // We only need to check against a few, not all of them.
+ tests := unmarshalingTests[:5]
+
+ // Create a buffer with many concatenated JSON objects.
+ var b bytes.Buffer
+ for _, tt := range tests {
+ b.WriteString(tt.json)
+ }
+
+ dec := json.NewDecoder(&b)
+ for _, tt := range tests {
+ // Make a new instance of the type of our expected object.
+ p := reflect.New(reflect.TypeOf(tt.pb).Elem()).Interface().(proto.Message)
+
+ err := tt.unmarshaler.UnmarshalNext(dec, p)
+ if err != nil {
+ t.Errorf("%s: %v", tt.desc, err)
+ continue
+ }
+
+ // For easier diffs, compare text strings of the protos.
+ exp := proto.MarshalTextString(tt.pb)
+ act := proto.MarshalTextString(p)
+ if string(exp) != string(act) {
+ t.Errorf("%s: got [%s] want [%s]", tt.desc, act, exp)
+ }
+ }
+
+ p := &pb.Simple{}
+ err := new(Unmarshaler).UnmarshalNext(dec, p)
+ if err != io.EOF {
+ t.Errorf("eof: got %v, expected io.EOF", err)
+ }
+}
+
+var unmarshalingShouldError = []struct {
+ desc string
+ in string
+ pb proto.Message
+}{
+ {"a value", "666", new(pb.Simple)},
+ {"gibberish", "{adskja123;l23=-=", new(pb.Simple)},
+ {"unknown field", `{"unknown": "foo"}`, new(pb.Simple)},
+ {"unknown enum name", `{"hilarity":"DAVE"}`, new(proto3pb.Message)},
+}
+
+func TestUnmarshalingBadInput(t *testing.T) {
+ for _, tt := range unmarshalingShouldError {
+ err := UnmarshalString(tt.in, tt.pb)
+ if err == nil {
+ t.Errorf("an error was expected when parsing %q instead of an object", tt.desc)
+ }
+ }
+}
+
+type funcResolver func(turl string) (proto.Message, error)
+
+func (fn funcResolver) Resolve(turl string) (proto.Message, error) {
+ return fn(turl)
+}
+
+func TestAnyWithCustomResolver(t *testing.T) {
+ var resolvedTypeUrls []string
+ resolver := funcResolver(func(turl string) (proto.Message, error) {
+ resolvedTypeUrls = append(resolvedTypeUrls, turl)
+ return new(pb.Simple), nil
+ })
+ msg := &pb.Simple{
+ OBytes: []byte{1, 2, 3, 4},
+ OBool: proto.Bool(true),
+ OString: proto.String("foobar"),
+ OInt64: proto.Int64(1020304),
+ }
+ msgBytes, err := proto.Marshal(msg)
+ if err != nil {
+ t.Errorf("an unexpected error occurred when marshaling message: %v", err)
+ }
+ // make an Any with a type URL that won't resolve w/out custom resolver
+ any := &anypb.Any{
+ TypeUrl: "https://foobar.com/some.random.MessageKind",
+ Value: msgBytes,
+ }
+
+ m := Marshaler{AnyResolver: resolver}
+ js, err := m.MarshalToString(any)
+ if err != nil {
+ t.Errorf("an unexpected error occurred when marshaling any to JSON: %v", err)
+ }
+ if len(resolvedTypeUrls) != 1 {
+ t.Errorf("custom resolver was not invoked during marshaling")
+ } else if resolvedTypeUrls[0] != "https://foobar.com/some.random.MessageKind" {
+ t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[0], "https://foobar.com/some.random.MessageKind")
+ }
+ wanted := `{"@type":"https://foobar.com/some.random.MessageKind","oBool":true,"oInt64":"1020304","oString":"foobar","oBytes":"AQIDBA=="}`
+ if js != wanted {
+ t.Errorf("marshalling JSON produced incorrect output: got %s, wanted %s", js, wanted)
+ }
+
+ u := Unmarshaler{AnyResolver: resolver}
+ roundTrip := &anypb.Any{}
+ err = u.Unmarshal(bytes.NewReader([]byte(js)), roundTrip)
+ if err != nil {
+ t.Errorf("an unexpected error occurred when unmarshaling any from JSON: %v", err)
+ }
+ if len(resolvedTypeUrls) != 2 {
+ t.Errorf("custom resolver was not invoked during marshaling")
+ } else if resolvedTypeUrls[1] != "https://foobar.com/some.random.MessageKind" {
+ t.Errorf("custom resolver was invoked with wrong URL: got %q, wanted %q", resolvedTypeUrls[1], "https://foobar.com/some.random.MessageKind")
+ }
+ if !proto.Equal(any, roundTrip) {
+ t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", roundTrip, any)
+ }
+}
+
+func TestUnmarshalJSONPBUnmarshaler(t *testing.T) {
+ rawJson := `{ "foo": "bar", "baz": [0, 1, 2, 3] }`
+ var msg dynamicMessage
+ if err := Unmarshal(strings.NewReader(rawJson), &msg); err != nil {
+ t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err)
+ }
+ if msg.rawJson != rawJson {
+ t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", msg.rawJson, rawJson)
+ }
+}
+
+func TestUnmarshalNullWithJSONPBUnmarshaler(t *testing.T) {
+ rawJson := `{"stringField":null}`
+ var ptrFieldMsg ptrFieldMessage
+ if err := Unmarshal(strings.NewReader(rawJson), &ptrFieldMsg); err != nil {
+ t.Errorf("unmarshal error: %v", err)
+ }
+
+ want := ptrFieldMessage{StringField: &stringField{IsSet: true, StringValue: "null"}}
+ if !proto.Equal(&ptrFieldMsg, &want) {
+ t.Errorf("unmarshal result StringField: got %v, want %v", ptrFieldMsg, want)
+ }
+}
+
+func TestUnmarshalAnyJSONPBUnmarshaler(t *testing.T) {
+ rawJson := `{ "@type": "blah.com/` + dynamicMessageName + `", "foo": "bar", "baz": [0, 1, 2, 3] }`
+ var got anypb.Any
+ if err := Unmarshal(strings.NewReader(rawJson), &got); err != nil {
+ t.Errorf("an unexpected error occurred when parsing into JSONPBUnmarshaler: %v", err)
+ }
+
+ dm := &dynamicMessage{rawJson: `{"baz":[0,1,2,3],"foo":"bar"}`}
+ var want anypb.Any
+ if b, err := proto.Marshal(dm); err != nil {
+ t.Errorf("an unexpected error occurred when marshaling message: %v", err)
+ } else {
+ want.TypeUrl = "blah.com/" + dynamicMessageName
+ want.Value = b
+ }
+
+ if !proto.Equal(&got, &want) {
+ t.Errorf("message contents not set correctly after unmarshalling JSON: got %s, wanted %s", got, want)
+ }
+}
+
+const (
+ dynamicMessageName = "google.protobuf.jsonpb.testing.dynamicMessage"
+)
+
+func init() {
+ // we register the custom type below so that we can use it in Any types
+ proto.RegisterType((*dynamicMessage)(nil), dynamicMessageName)
+}
+
+type ptrFieldMessage struct {
+ StringField *stringField `protobuf:"bytes,1,opt,name=stringField"`
+}
+
+func (m *ptrFieldMessage) Reset() {
+}
+
+func (m *ptrFieldMessage) String() string {
+ return m.StringField.StringValue
+}
+
+func (m *ptrFieldMessage) ProtoMessage() {
+}
+
+type stringField struct {
+ IsSet bool `protobuf:"varint,1,opt,name=isSet"`
+ StringValue string `protobuf:"bytes,2,opt,name=stringValue"`
+}
+
+func (s *stringField) Reset() {
+}
+
+func (s *stringField) String() string {
+ return s.StringValue
+}
+
+func (s *stringField) ProtoMessage() {
+}
+
+func (s *stringField) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error {
+ s.IsSet = true
+ s.StringValue = string(js)
+ return nil
+}
+
+// dynamicMessage implements protobuf.Message but is not a normal generated message type.
+// It provides implementations of JSONPBMarshaler and JSONPBUnmarshaler for JSON support.
+type dynamicMessage struct {
+ rawJson string `protobuf:"bytes,1,opt,name=rawJson"`
+}
+
+func (m *dynamicMessage) Reset() {
+ m.rawJson = "{}"
+}
+
+func (m *dynamicMessage) String() string {
+ return m.rawJson
+}
+
+func (m *dynamicMessage) ProtoMessage() {
+}
+
+func (m *dynamicMessage) MarshalJSONPB(jm *Marshaler) ([]byte, error) {
+ return []byte(m.rawJson), nil
+}
+
+func (m *dynamicMessage) UnmarshalJSONPB(jum *Unmarshaler, js []byte) error {
+ m.rawJson = string(js)
+ return nil
+}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/Makefile b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/Makefile
new file mode 100644
index 0000000..eeda8ae
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/Makefile
@@ -0,0 +1,33 @@
+# 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.
+
+regenerate:
+ protoc --go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any,Mgoogle/protobuf/duration.proto=github.com/golang/protobuf/ptypes/duration,Mgoogle/protobuf/struct.proto=github.com/golang/protobuf/ptypes/struct,Mgoogle/protobuf/timestamp.proto=github.com/golang/protobuf/ptypes/timestamp,Mgoogle/protobuf/wrappers.proto=github.com/golang/protobuf/ptypes/wrappers:. *.proto
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go
new file mode 100644
index 0000000..ebb180e
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.pb.go
@@ -0,0 +1,266 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: more_test_objects.proto
+
+/*
+Package jsonpb is a generated protocol buffer package.
+
+It is generated from these files:
+ more_test_objects.proto
+ test_objects.proto
+
+It has these top-level messages:
+ Simple3
+ SimpleSlice3
+ SimpleMap3
+ SimpleNull3
+ Mappy
+ Simple
+ NonFinites
+ Repeats
+ Widget
+ Maps
+ MsgWithOneof
+ Real
+ Complex
+ KnownTypes
+*/
+package jsonpb
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+type Numeral int32
+
+const (
+ Numeral_UNKNOWN Numeral = 0
+ Numeral_ARABIC Numeral = 1
+ Numeral_ROMAN Numeral = 2
+)
+
+var Numeral_name = map[int32]string{
+ 0: "UNKNOWN",
+ 1: "ARABIC",
+ 2: "ROMAN",
+}
+var Numeral_value = map[string]int32{
+ "UNKNOWN": 0,
+ "ARABIC": 1,
+ "ROMAN": 2,
+}
+
+func (x Numeral) String() string {
+ return proto.EnumName(Numeral_name, int32(x))
+}
+func (Numeral) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+type Simple3 struct {
+ Dub float64 `protobuf:"fixed64,1,opt,name=dub" json:"dub,omitempty"`
+}
+
+func (m *Simple3) Reset() { *m = Simple3{} }
+func (m *Simple3) String() string { return proto.CompactTextString(m) }
+func (*Simple3) ProtoMessage() {}
+func (*Simple3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+func (m *Simple3) GetDub() float64 {
+ if m != nil {
+ return m.Dub
+ }
+ return 0
+}
+
+type SimpleSlice3 struct {
+ Slices []string `protobuf:"bytes,1,rep,name=slices" json:"slices,omitempty"`
+}
+
+func (m *SimpleSlice3) Reset() { *m = SimpleSlice3{} }
+func (m *SimpleSlice3) String() string { return proto.CompactTextString(m) }
+func (*SimpleSlice3) ProtoMessage() {}
+func (*SimpleSlice3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+func (m *SimpleSlice3) GetSlices() []string {
+ if m != nil {
+ return m.Slices
+ }
+ return nil
+}
+
+type SimpleMap3 struct {
+ Stringy map[string]string `protobuf:"bytes,1,rep,name=stringy" json:"stringy,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+}
+
+func (m *SimpleMap3) Reset() { *m = SimpleMap3{} }
+func (m *SimpleMap3) String() string { return proto.CompactTextString(m) }
+func (*SimpleMap3) ProtoMessage() {}
+func (*SimpleMap3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
+
+func (m *SimpleMap3) GetStringy() map[string]string {
+ if m != nil {
+ return m.Stringy
+ }
+ return nil
+}
+
+type SimpleNull3 struct {
+ Simple *Simple3 `protobuf:"bytes,1,opt,name=simple" json:"simple,omitempty"`
+}
+
+func (m *SimpleNull3) Reset() { *m = SimpleNull3{} }
+func (m *SimpleNull3) String() string { return proto.CompactTextString(m) }
+func (*SimpleNull3) ProtoMessage() {}
+func (*SimpleNull3) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
+
+func (m *SimpleNull3) GetSimple() *Simple3 {
+ if m != nil {
+ return m.Simple
+ }
+ return nil
+}
+
+type Mappy struct {
+ Nummy map[int64]int32 `protobuf:"bytes,1,rep,name=nummy" json:"nummy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+ Strry map[string]string `protobuf:"bytes,2,rep,name=strry" json:"strry,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Objjy map[int32]*Simple3 `protobuf:"bytes,3,rep,name=objjy" json:"objjy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Buggy map[int64]string `protobuf:"bytes,4,rep,name=buggy" json:"buggy,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Booly map[bool]bool `protobuf:"bytes,5,rep,name=booly" json:"booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+ Enumy map[string]Numeral `protobuf:"bytes,6,rep,name=enumy" json:"enumy,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"varint,2,opt,name=value,enum=jsonpb.Numeral"`
+ S32Booly map[int32]bool `protobuf:"bytes,7,rep,name=s32booly" json:"s32booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+ S64Booly map[int64]bool `protobuf:"bytes,8,rep,name=s64booly" json:"s64booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+ U32Booly map[uint32]bool `protobuf:"bytes,9,rep,name=u32booly" json:"u32booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+ U64Booly map[uint64]bool `protobuf:"bytes,10,rep,name=u64booly" json:"u64booly,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+}
+
+func (m *Mappy) Reset() { *m = Mappy{} }
+func (m *Mappy) String() string { return proto.CompactTextString(m) }
+func (*Mappy) ProtoMessage() {}
+func (*Mappy) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
+
+func (m *Mappy) GetNummy() map[int64]int32 {
+ if m != nil {
+ return m.Nummy
+ }
+ return nil
+}
+
+func (m *Mappy) GetStrry() map[string]string {
+ if m != nil {
+ return m.Strry
+ }
+ return nil
+}
+
+func (m *Mappy) GetObjjy() map[int32]*Simple3 {
+ if m != nil {
+ return m.Objjy
+ }
+ return nil
+}
+
+func (m *Mappy) GetBuggy() map[int64]string {
+ if m != nil {
+ return m.Buggy
+ }
+ return nil
+}
+
+func (m *Mappy) GetBooly() map[bool]bool {
+ if m != nil {
+ return m.Booly
+ }
+ return nil
+}
+
+func (m *Mappy) GetEnumy() map[string]Numeral {
+ if m != nil {
+ return m.Enumy
+ }
+ return nil
+}
+
+func (m *Mappy) GetS32Booly() map[int32]bool {
+ if m != nil {
+ return m.S32Booly
+ }
+ return nil
+}
+
+func (m *Mappy) GetS64Booly() map[int64]bool {
+ if m != nil {
+ return m.S64Booly
+ }
+ return nil
+}
+
+func (m *Mappy) GetU32Booly() map[uint32]bool {
+ if m != nil {
+ return m.U32Booly
+ }
+ return nil
+}
+
+func (m *Mappy) GetU64Booly() map[uint64]bool {
+ if m != nil {
+ return m.U64Booly
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*Simple3)(nil), "jsonpb.Simple3")
+ proto.RegisterType((*SimpleSlice3)(nil), "jsonpb.SimpleSlice3")
+ proto.RegisterType((*SimpleMap3)(nil), "jsonpb.SimpleMap3")
+ proto.RegisterType((*SimpleNull3)(nil), "jsonpb.SimpleNull3")
+ proto.RegisterType((*Mappy)(nil), "jsonpb.Mappy")
+ proto.RegisterEnum("jsonpb.Numeral", Numeral_name, Numeral_value)
+}
+
+func init() { proto.RegisterFile("more_test_objects.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 526 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x94, 0xdd, 0x6b, 0xdb, 0x3c,
+ 0x14, 0x87, 0x5f, 0x27, 0xf5, 0xd7, 0x49, 0xfb, 0x2e, 0x88, 0xb1, 0x99, 0xf4, 0x62, 0xc5, 0xb0,
+ 0xad, 0x0c, 0xe6, 0x8b, 0x78, 0x74, 0x5d, 0x77, 0x95, 0x8e, 0x5e, 0x94, 0x11, 0x07, 0x1c, 0xc2,
+ 0x2e, 0x4b, 0xdc, 0x99, 0x90, 0xcc, 0x5f, 0xd8, 0xd6, 0xc0, 0xd7, 0xfb, 0xbb, 0x07, 0xe3, 0x48,
+ 0x72, 0x2d, 0x07, 0x85, 0x6c, 0x77, 0x52, 0x7e, 0xcf, 0xe3, 0x73, 0x24, 0x1d, 0x02, 0x2f, 0xd3,
+ 0xbc, 0x8c, 0x1f, 0xea, 0xb8, 0xaa, 0x1f, 0xf2, 0x68, 0x17, 0x3f, 0xd6, 0x95, 0x57, 0x94, 0x79,
+ 0x9d, 0x13, 0x63, 0x57, 0xe5, 0x59, 0x11, 0xb9, 0xe7, 0x60, 0x2e, 0xb7, 0x69, 0x91, 0xc4, 0x3e,
+ 0x19, 0xc3, 0xf0, 0x3b, 0x8d, 0x1c, 0xed, 0x42, 0xbb, 0xd4, 0x42, 0x5c, 0xba, 0x6f, 0xe0, 0x94,
+ 0x87, 0xcb, 0x64, 0xfb, 0x18, 0xfb, 0xe4, 0x05, 0x18, 0x15, 0xae, 0x2a, 0x47, 0xbb, 0x18, 0x5e,
+ 0xda, 0xa1, 0xd8, 0xb9, 0xbf, 0x34, 0x00, 0x0e, 0xce, 0xd7, 0x85, 0x4f, 0x3e, 0x81, 0x59, 0xd5,
+ 0xe5, 0x36, 0xdb, 0x34, 0x8c, 0x1b, 0x4d, 0x5f, 0x79, 0xbc, 0x9a, 0xd7, 0x41, 0xde, 0x92, 0x13,
+ 0x77, 0x59, 0x5d, 0x36, 0x61, 0xcb, 0x4f, 0x6e, 0xe0, 0x54, 0x0e, 0xb0, 0xa7, 0x1f, 0x71, 0xc3,
+ 0x7a, 0xb2, 0x43, 0x5c, 0x92, 0xe7, 0xa0, 0xff, 0x5c, 0x27, 0x34, 0x76, 0x06, 0xec, 0x37, 0xbe,
+ 0xb9, 0x19, 0x5c, 0x6b, 0xee, 0x15, 0x8c, 0xf8, 0xf7, 0x03, 0x9a, 0x24, 0x3e, 0x79, 0x0b, 0x46,
+ 0xc5, 0xb6, 0xcc, 0x1e, 0x4d, 0x9f, 0xf5, 0x9b, 0xf0, 0x43, 0x11, 0xbb, 0xbf, 0x2d, 0xd0, 0xe7,
+ 0xeb, 0xa2, 0x68, 0x88, 0x07, 0x7a, 0x46, 0xd3, 0xb4, 0x6d, 0xdb, 0x69, 0x0d, 0x96, 0x7a, 0x01,
+ 0x46, 0xbc, 0x5f, 0x8e, 0x21, 0x5f, 0xd5, 0x65, 0xd9, 0x38, 0x03, 0x15, 0xbf, 0xc4, 0x48, 0xf0,
+ 0x0c, 0x43, 0x3e, 0x8f, 0x76, 0xbb, 0xc6, 0x19, 0xaa, 0xf8, 0x05, 0x46, 0x82, 0x67, 0x18, 0xf2,
+ 0x11, 0xdd, 0x6c, 0x1a, 0xe7, 0x44, 0xc5, 0xdf, 0x62, 0x24, 0x78, 0x86, 0x31, 0x3e, 0xcf, 0x93,
+ 0xc6, 0xd1, 0x95, 0x3c, 0x46, 0x2d, 0x8f, 0x6b, 0xe4, 0xe3, 0x8c, 0xa6, 0x8d, 0x63, 0xa8, 0xf8,
+ 0x3b, 0x8c, 0x04, 0xcf, 0x30, 0xf2, 0x11, 0xac, 0xca, 0x9f, 0xf2, 0x12, 0x26, 0x53, 0xce, 0xf7,
+ 0x8e, 0x2c, 0x52, 0x6e, 0x3d, 0xc1, 0x4c, 0xbc, 0xfa, 0xc0, 0x45, 0x4b, 0x29, 0x8a, 0xb4, 0x15,
+ 0xc5, 0x16, 0x45, 0xda, 0x56, 0xb4, 0x55, 0xe2, 0xaa, 0x5f, 0x91, 0x4a, 0x15, 0x69, 0x5b, 0x11,
+ 0x94, 0x62, 0xbf, 0x62, 0x0b, 0x4f, 0xae, 0x01, 0xba, 0x87, 0x96, 0xe7, 0x6f, 0xa8, 0x98, 0x3f,
+ 0x5d, 0x9a, 0x3f, 0x34, 0xbb, 0x27, 0xff, 0x97, 0xc9, 0x9d, 0xdc, 0x03, 0x74, 0x8f, 0x2f, 0x9b,
+ 0x3a, 0x37, 0x5f, 0xcb, 0xa6, 0x62, 0x92, 0xfb, 0x4d, 0x74, 0x73, 0x71, 0xac, 0x7d, 0x7b, 0xdf,
+ 0x7c, 0xba, 0x10, 0xd9, 0xb4, 0x14, 0xa6, 0xb5, 0xd7, 0x7e, 0x37, 0x2b, 0x8a, 0x83, 0xf7, 0xda,
+ 0xff, 0xbf, 0x6b, 0x3f, 0xa0, 0x69, 0x5c, 0xae, 0x13, 0xf9, 0x53, 0x9f, 0xe1, 0xac, 0x37, 0x43,
+ 0x8a, 0xcb, 0x38, 0xdc, 0x07, 0xca, 0xf2, 0xab, 0x1e, 0x3b, 0xfe, 0xbe, 0xbc, 0x3a, 0x54, 0xf9,
+ 0xec, 0x6f, 0xe4, 0x43, 0x95, 0x4f, 0x8e, 0xc8, 0xef, 0xde, 0x83, 0x29, 0x6e, 0x82, 0x8c, 0xc0,
+ 0x5c, 0x05, 0x5f, 0x83, 0xc5, 0xb7, 0x60, 0xfc, 0x1f, 0x01, 0x30, 0x66, 0xe1, 0xec, 0xf6, 0xfe,
+ 0xcb, 0x58, 0x23, 0x36, 0xe8, 0xe1, 0x62, 0x3e, 0x0b, 0xc6, 0x83, 0xc8, 0x60, 0x7f, 0xe0, 0xfe,
+ 0x9f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x34, 0xaf, 0xdb, 0x05, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto
new file mode 100644
index 0000000..d254fa5
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/more_test_objects.proto
@@ -0,0 +1,69 @@
+// 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.
+
+syntax = "proto3";
+
+package jsonpb;
+
+message Simple3 {
+ double dub = 1;
+}
+
+message SimpleSlice3 {
+ repeated string slices = 1;
+}
+
+message SimpleMap3 {
+ map stringy = 1;
+}
+
+message SimpleNull3 {
+ Simple3 simple = 1;
+}
+
+enum Numeral {
+ UNKNOWN = 0;
+ ARABIC = 1;
+ ROMAN = 2;
+}
+
+message Mappy {
+ map nummy = 1;
+ map strry = 2;
+ map objjy = 3;
+ map buggy = 4;
+ map booly = 5;
+ map enumy = 6;
+ map s32booly = 7;
+ map s64booly = 8;
+ map u32booly = 9;
+ map u64booly = 10;
+}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go
new file mode 100644
index 0000000..d413d74
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.pb.go
@@ -0,0 +1,852 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: test_objects.proto
+
+package jsonpb
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import google_protobuf "github.com/golang/protobuf/ptypes/any"
+import google_protobuf1 "github.com/golang/protobuf/ptypes/duration"
+import google_protobuf2 "github.com/golang/protobuf/ptypes/struct"
+import google_protobuf3 "github.com/golang/protobuf/ptypes/timestamp"
+import google_protobuf4 "github.com/golang/protobuf/ptypes/wrappers"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+type Widget_Color int32
+
+const (
+ Widget_RED Widget_Color = 0
+ Widget_GREEN Widget_Color = 1
+ Widget_BLUE Widget_Color = 2
+)
+
+var Widget_Color_name = map[int32]string{
+ 0: "RED",
+ 1: "GREEN",
+ 2: "BLUE",
+}
+var Widget_Color_value = map[string]int32{
+ "RED": 0,
+ "GREEN": 1,
+ "BLUE": 2,
+}
+
+func (x Widget_Color) Enum() *Widget_Color {
+ p := new(Widget_Color)
+ *p = x
+ return p
+}
+func (x Widget_Color) String() string {
+ return proto.EnumName(Widget_Color_name, int32(x))
+}
+func (x *Widget_Color) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(Widget_Color_value, data, "Widget_Color")
+ if err != nil {
+ return err
+ }
+ *x = Widget_Color(value)
+ return nil
+}
+func (Widget_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor1, []int{3, 0} }
+
+// Test message for holding primitive types.
+type Simple struct {
+ OBool *bool `protobuf:"varint,1,opt,name=o_bool,json=oBool" json:"o_bool,omitempty"`
+ OInt32 *int32 `protobuf:"varint,2,opt,name=o_int32,json=oInt32" json:"o_int32,omitempty"`
+ OInt64 *int64 `protobuf:"varint,3,opt,name=o_int64,json=oInt64" json:"o_int64,omitempty"`
+ OUint32 *uint32 `protobuf:"varint,4,opt,name=o_uint32,json=oUint32" json:"o_uint32,omitempty"`
+ OUint64 *uint64 `protobuf:"varint,5,opt,name=o_uint64,json=oUint64" json:"o_uint64,omitempty"`
+ OSint32 *int32 `protobuf:"zigzag32,6,opt,name=o_sint32,json=oSint32" json:"o_sint32,omitempty"`
+ OSint64 *int64 `protobuf:"zigzag64,7,opt,name=o_sint64,json=oSint64" json:"o_sint64,omitempty"`
+ OFloat *float32 `protobuf:"fixed32,8,opt,name=o_float,json=oFloat" json:"o_float,omitempty"`
+ ODouble *float64 `protobuf:"fixed64,9,opt,name=o_double,json=oDouble" json:"o_double,omitempty"`
+ OString *string `protobuf:"bytes,10,opt,name=o_string,json=oString" json:"o_string,omitempty"`
+ OBytes []byte `protobuf:"bytes,11,opt,name=o_bytes,json=oBytes" json:"o_bytes,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Simple) Reset() { *m = Simple{} }
+func (m *Simple) String() string { return proto.CompactTextString(m) }
+func (*Simple) ProtoMessage() {}
+func (*Simple) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{0} }
+
+func (m *Simple) GetOBool() bool {
+ if m != nil && m.OBool != nil {
+ return *m.OBool
+ }
+ return false
+}
+
+func (m *Simple) GetOInt32() int32 {
+ if m != nil && m.OInt32 != nil {
+ return *m.OInt32
+ }
+ return 0
+}
+
+func (m *Simple) GetOInt64() int64 {
+ if m != nil && m.OInt64 != nil {
+ return *m.OInt64
+ }
+ return 0
+}
+
+func (m *Simple) GetOUint32() uint32 {
+ if m != nil && m.OUint32 != nil {
+ return *m.OUint32
+ }
+ return 0
+}
+
+func (m *Simple) GetOUint64() uint64 {
+ if m != nil && m.OUint64 != nil {
+ return *m.OUint64
+ }
+ return 0
+}
+
+func (m *Simple) GetOSint32() int32 {
+ if m != nil && m.OSint32 != nil {
+ return *m.OSint32
+ }
+ return 0
+}
+
+func (m *Simple) GetOSint64() int64 {
+ if m != nil && m.OSint64 != nil {
+ return *m.OSint64
+ }
+ return 0
+}
+
+func (m *Simple) GetOFloat() float32 {
+ if m != nil && m.OFloat != nil {
+ return *m.OFloat
+ }
+ return 0
+}
+
+func (m *Simple) GetODouble() float64 {
+ if m != nil && m.ODouble != nil {
+ return *m.ODouble
+ }
+ return 0
+}
+
+func (m *Simple) GetOString() string {
+ if m != nil && m.OString != nil {
+ return *m.OString
+ }
+ return ""
+}
+
+func (m *Simple) GetOBytes() []byte {
+ if m != nil {
+ return m.OBytes
+ }
+ return nil
+}
+
+// Test message for holding special non-finites primitives.
+type NonFinites struct {
+ FNan *float32 `protobuf:"fixed32,1,opt,name=f_nan,json=fNan" json:"f_nan,omitempty"`
+ FPinf *float32 `protobuf:"fixed32,2,opt,name=f_pinf,json=fPinf" json:"f_pinf,omitempty"`
+ FNinf *float32 `protobuf:"fixed32,3,opt,name=f_ninf,json=fNinf" json:"f_ninf,omitempty"`
+ DNan *float64 `protobuf:"fixed64,4,opt,name=d_nan,json=dNan" json:"d_nan,omitempty"`
+ DPinf *float64 `protobuf:"fixed64,5,opt,name=d_pinf,json=dPinf" json:"d_pinf,omitempty"`
+ DNinf *float64 `protobuf:"fixed64,6,opt,name=d_ninf,json=dNinf" json:"d_ninf,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *NonFinites) Reset() { *m = NonFinites{} }
+func (m *NonFinites) String() string { return proto.CompactTextString(m) }
+func (*NonFinites) ProtoMessage() {}
+func (*NonFinites) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{1} }
+
+func (m *NonFinites) GetFNan() float32 {
+ if m != nil && m.FNan != nil {
+ return *m.FNan
+ }
+ return 0
+}
+
+func (m *NonFinites) GetFPinf() float32 {
+ if m != nil && m.FPinf != nil {
+ return *m.FPinf
+ }
+ return 0
+}
+
+func (m *NonFinites) GetFNinf() float32 {
+ if m != nil && m.FNinf != nil {
+ return *m.FNinf
+ }
+ return 0
+}
+
+func (m *NonFinites) GetDNan() float64 {
+ if m != nil && m.DNan != nil {
+ return *m.DNan
+ }
+ return 0
+}
+
+func (m *NonFinites) GetDPinf() float64 {
+ if m != nil && m.DPinf != nil {
+ return *m.DPinf
+ }
+ return 0
+}
+
+func (m *NonFinites) GetDNinf() float64 {
+ if m != nil && m.DNinf != nil {
+ return *m.DNinf
+ }
+ return 0
+}
+
+// Test message for holding repeated primitives.
+type Repeats struct {
+ RBool []bool `protobuf:"varint,1,rep,name=r_bool,json=rBool" json:"r_bool,omitempty"`
+ RInt32 []int32 `protobuf:"varint,2,rep,name=r_int32,json=rInt32" json:"r_int32,omitempty"`
+ RInt64 []int64 `protobuf:"varint,3,rep,name=r_int64,json=rInt64" json:"r_int64,omitempty"`
+ RUint32 []uint32 `protobuf:"varint,4,rep,name=r_uint32,json=rUint32" json:"r_uint32,omitempty"`
+ RUint64 []uint64 `protobuf:"varint,5,rep,name=r_uint64,json=rUint64" json:"r_uint64,omitempty"`
+ RSint32 []int32 `protobuf:"zigzag32,6,rep,name=r_sint32,json=rSint32" json:"r_sint32,omitempty"`
+ RSint64 []int64 `protobuf:"zigzag64,7,rep,name=r_sint64,json=rSint64" json:"r_sint64,omitempty"`
+ RFloat []float32 `protobuf:"fixed32,8,rep,name=r_float,json=rFloat" json:"r_float,omitempty"`
+ RDouble []float64 `protobuf:"fixed64,9,rep,name=r_double,json=rDouble" json:"r_double,omitempty"`
+ RString []string `protobuf:"bytes,10,rep,name=r_string,json=rString" json:"r_string,omitempty"`
+ RBytes [][]byte `protobuf:"bytes,11,rep,name=r_bytes,json=rBytes" json:"r_bytes,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Repeats) Reset() { *m = Repeats{} }
+func (m *Repeats) String() string { return proto.CompactTextString(m) }
+func (*Repeats) ProtoMessage() {}
+func (*Repeats) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{2} }
+
+func (m *Repeats) GetRBool() []bool {
+ if m != nil {
+ return m.RBool
+ }
+ return nil
+}
+
+func (m *Repeats) GetRInt32() []int32 {
+ if m != nil {
+ return m.RInt32
+ }
+ return nil
+}
+
+func (m *Repeats) GetRInt64() []int64 {
+ if m != nil {
+ return m.RInt64
+ }
+ return nil
+}
+
+func (m *Repeats) GetRUint32() []uint32 {
+ if m != nil {
+ return m.RUint32
+ }
+ return nil
+}
+
+func (m *Repeats) GetRUint64() []uint64 {
+ if m != nil {
+ return m.RUint64
+ }
+ return nil
+}
+
+func (m *Repeats) GetRSint32() []int32 {
+ if m != nil {
+ return m.RSint32
+ }
+ return nil
+}
+
+func (m *Repeats) GetRSint64() []int64 {
+ if m != nil {
+ return m.RSint64
+ }
+ return nil
+}
+
+func (m *Repeats) GetRFloat() []float32 {
+ if m != nil {
+ return m.RFloat
+ }
+ return nil
+}
+
+func (m *Repeats) GetRDouble() []float64 {
+ if m != nil {
+ return m.RDouble
+ }
+ return nil
+}
+
+func (m *Repeats) GetRString() []string {
+ if m != nil {
+ return m.RString
+ }
+ return nil
+}
+
+func (m *Repeats) GetRBytes() [][]byte {
+ if m != nil {
+ return m.RBytes
+ }
+ return nil
+}
+
+// Test message for holding enums and nested messages.
+type Widget struct {
+ Color *Widget_Color `protobuf:"varint,1,opt,name=color,enum=jsonpb.Widget_Color" json:"color,omitempty"`
+ RColor []Widget_Color `protobuf:"varint,2,rep,name=r_color,json=rColor,enum=jsonpb.Widget_Color" json:"r_color,omitempty"`
+ Simple *Simple `protobuf:"bytes,10,opt,name=simple" json:"simple,omitempty"`
+ RSimple []*Simple `protobuf:"bytes,11,rep,name=r_simple,json=rSimple" json:"r_simple,omitempty"`
+ Repeats *Repeats `protobuf:"bytes,20,opt,name=repeats" json:"repeats,omitempty"`
+ RRepeats []*Repeats `protobuf:"bytes,21,rep,name=r_repeats,json=rRepeats" json:"r_repeats,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Widget) Reset() { *m = Widget{} }
+func (m *Widget) String() string { return proto.CompactTextString(m) }
+func (*Widget) ProtoMessage() {}
+func (*Widget) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{3} }
+
+func (m *Widget) GetColor() Widget_Color {
+ if m != nil && m.Color != nil {
+ return *m.Color
+ }
+ return Widget_RED
+}
+
+func (m *Widget) GetRColor() []Widget_Color {
+ if m != nil {
+ return m.RColor
+ }
+ return nil
+}
+
+func (m *Widget) GetSimple() *Simple {
+ if m != nil {
+ return m.Simple
+ }
+ return nil
+}
+
+func (m *Widget) GetRSimple() []*Simple {
+ if m != nil {
+ return m.RSimple
+ }
+ return nil
+}
+
+func (m *Widget) GetRepeats() *Repeats {
+ if m != nil {
+ return m.Repeats
+ }
+ return nil
+}
+
+func (m *Widget) GetRRepeats() []*Repeats {
+ if m != nil {
+ return m.RRepeats
+ }
+ return nil
+}
+
+type Maps struct {
+ MInt64Str map[int64]string `protobuf:"bytes,1,rep,name=m_int64_str,json=mInt64Str" json:"m_int64_str,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ MBoolSimple map[bool]*Simple `protobuf:"bytes,2,rep,name=m_bool_simple,json=mBoolSimple" json:"m_bool_simple,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Maps) Reset() { *m = Maps{} }
+func (m *Maps) String() string { return proto.CompactTextString(m) }
+func (*Maps) ProtoMessage() {}
+func (*Maps) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{4} }
+
+func (m *Maps) GetMInt64Str() map[int64]string {
+ if m != nil {
+ return m.MInt64Str
+ }
+ return nil
+}
+
+func (m *Maps) GetMBoolSimple() map[bool]*Simple {
+ if m != nil {
+ return m.MBoolSimple
+ }
+ return nil
+}
+
+type MsgWithOneof struct {
+ // Types that are valid to be assigned to Union:
+ // *MsgWithOneof_Title
+ // *MsgWithOneof_Salary
+ // *MsgWithOneof_Country
+ // *MsgWithOneof_HomeAddress
+ Union isMsgWithOneof_Union `protobuf_oneof:"union"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MsgWithOneof) Reset() { *m = MsgWithOneof{} }
+func (m *MsgWithOneof) String() string { return proto.CompactTextString(m) }
+func (*MsgWithOneof) ProtoMessage() {}
+func (*MsgWithOneof) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{5} }
+
+type isMsgWithOneof_Union interface {
+ isMsgWithOneof_Union()
+}
+
+type MsgWithOneof_Title struct {
+ Title string `protobuf:"bytes,1,opt,name=title,oneof"`
+}
+type MsgWithOneof_Salary struct {
+ Salary int64 `protobuf:"varint,2,opt,name=salary,oneof"`
+}
+type MsgWithOneof_Country struct {
+ Country string `protobuf:"bytes,3,opt,name=Country,oneof"`
+}
+type MsgWithOneof_HomeAddress struct {
+ HomeAddress string `protobuf:"bytes,4,opt,name=home_address,json=homeAddress,oneof"`
+}
+
+func (*MsgWithOneof_Title) isMsgWithOneof_Union() {}
+func (*MsgWithOneof_Salary) isMsgWithOneof_Union() {}
+func (*MsgWithOneof_Country) isMsgWithOneof_Union() {}
+func (*MsgWithOneof_HomeAddress) isMsgWithOneof_Union() {}
+
+func (m *MsgWithOneof) GetUnion() isMsgWithOneof_Union {
+ if m != nil {
+ return m.Union
+ }
+ return nil
+}
+
+func (m *MsgWithOneof) GetTitle() string {
+ if x, ok := m.GetUnion().(*MsgWithOneof_Title); ok {
+ return x.Title
+ }
+ return ""
+}
+
+func (m *MsgWithOneof) GetSalary() int64 {
+ if x, ok := m.GetUnion().(*MsgWithOneof_Salary); ok {
+ return x.Salary
+ }
+ return 0
+}
+
+func (m *MsgWithOneof) GetCountry() string {
+ if x, ok := m.GetUnion().(*MsgWithOneof_Country); ok {
+ return x.Country
+ }
+ return ""
+}
+
+func (m *MsgWithOneof) GetHomeAddress() string {
+ if x, ok := m.GetUnion().(*MsgWithOneof_HomeAddress); ok {
+ return x.HomeAddress
+ }
+ return ""
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*MsgWithOneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _MsgWithOneof_OneofMarshaler, _MsgWithOneof_OneofUnmarshaler, _MsgWithOneof_OneofSizer, []interface{}{
+ (*MsgWithOneof_Title)(nil),
+ (*MsgWithOneof_Salary)(nil),
+ (*MsgWithOneof_Country)(nil),
+ (*MsgWithOneof_HomeAddress)(nil),
+ }
+}
+
+func _MsgWithOneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*MsgWithOneof)
+ // union
+ switch x := m.Union.(type) {
+ case *MsgWithOneof_Title:
+ b.EncodeVarint(1<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.Title)
+ case *MsgWithOneof_Salary:
+ b.EncodeVarint(2<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.Salary))
+ case *MsgWithOneof_Country:
+ b.EncodeVarint(3<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.Country)
+ case *MsgWithOneof_HomeAddress:
+ b.EncodeVarint(4<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.HomeAddress)
+ case nil:
+ default:
+ return fmt.Errorf("MsgWithOneof.Union has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _MsgWithOneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*MsgWithOneof)
+ switch tag {
+ case 1: // union.title
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Union = &MsgWithOneof_Title{x}
+ return true, err
+ case 2: // union.salary
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &MsgWithOneof_Salary{int64(x)}
+ return true, err
+ case 3: // union.Country
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Union = &MsgWithOneof_Country{x}
+ return true, err
+ case 4: // union.home_address
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Union = &MsgWithOneof_HomeAddress{x}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _MsgWithOneof_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*MsgWithOneof)
+ // union
+ switch x := m.Union.(type) {
+ case *MsgWithOneof_Title:
+ n += proto.SizeVarint(1<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Title)))
+ n += len(x.Title)
+ case *MsgWithOneof_Salary:
+ n += proto.SizeVarint(2<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.Salary))
+ case *MsgWithOneof_Country:
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Country)))
+ n += len(x.Country)
+ case *MsgWithOneof_HomeAddress:
+ n += proto.SizeVarint(4<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.HomeAddress)))
+ n += len(x.HomeAddress)
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+type Real struct {
+ Value *float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Real) Reset() { *m = Real{} }
+func (m *Real) String() string { return proto.CompactTextString(m) }
+func (*Real) ProtoMessage() {}
+func (*Real) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{6} }
+
+var extRange_Real = []proto.ExtensionRange{
+ {100, 536870911},
+}
+
+func (*Real) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_Real
+}
+
+func (m *Real) GetValue() float64 {
+ if m != nil && m.Value != nil {
+ return *m.Value
+ }
+ return 0
+}
+
+type Complex struct {
+ Imaginary *float64 `protobuf:"fixed64,1,opt,name=imaginary" json:"imaginary,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Complex) Reset() { *m = Complex{} }
+func (m *Complex) String() string { return proto.CompactTextString(m) }
+func (*Complex) ProtoMessage() {}
+func (*Complex) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{7} }
+
+var extRange_Complex = []proto.ExtensionRange{
+ {100, 536870911},
+}
+
+func (*Complex) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_Complex
+}
+
+func (m *Complex) GetImaginary() float64 {
+ if m != nil && m.Imaginary != nil {
+ return *m.Imaginary
+ }
+ return 0
+}
+
+var E_Complex_RealExtension = &proto.ExtensionDesc{
+ ExtendedType: (*Real)(nil),
+ ExtensionType: (*Complex)(nil),
+ Field: 123,
+ Name: "jsonpb.Complex.real_extension",
+ Tag: "bytes,123,opt,name=real_extension,json=realExtension",
+ Filename: "test_objects.proto",
+}
+
+type KnownTypes struct {
+ An *google_protobuf.Any `protobuf:"bytes,14,opt,name=an" json:"an,omitempty"`
+ Dur *google_protobuf1.Duration `protobuf:"bytes,1,opt,name=dur" json:"dur,omitempty"`
+ St *google_protobuf2.Struct `protobuf:"bytes,12,opt,name=st" json:"st,omitempty"`
+ Ts *google_protobuf3.Timestamp `protobuf:"bytes,2,opt,name=ts" json:"ts,omitempty"`
+ Lv *google_protobuf2.ListValue `protobuf:"bytes,15,opt,name=lv" json:"lv,omitempty"`
+ Val *google_protobuf2.Value `protobuf:"bytes,16,opt,name=val" json:"val,omitempty"`
+ Dbl *google_protobuf4.DoubleValue `protobuf:"bytes,3,opt,name=dbl" json:"dbl,omitempty"`
+ Flt *google_protobuf4.FloatValue `protobuf:"bytes,4,opt,name=flt" json:"flt,omitempty"`
+ I64 *google_protobuf4.Int64Value `protobuf:"bytes,5,opt,name=i64" json:"i64,omitempty"`
+ U64 *google_protobuf4.UInt64Value `protobuf:"bytes,6,opt,name=u64" json:"u64,omitempty"`
+ I32 *google_protobuf4.Int32Value `protobuf:"bytes,7,opt,name=i32" json:"i32,omitempty"`
+ U32 *google_protobuf4.UInt32Value `protobuf:"bytes,8,opt,name=u32" json:"u32,omitempty"`
+ Bool *google_protobuf4.BoolValue `protobuf:"bytes,9,opt,name=bool" json:"bool,omitempty"`
+ Str *google_protobuf4.StringValue `protobuf:"bytes,10,opt,name=str" json:"str,omitempty"`
+ Bytes *google_protobuf4.BytesValue `protobuf:"bytes,11,opt,name=bytes" json:"bytes,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *KnownTypes) Reset() { *m = KnownTypes{} }
+func (m *KnownTypes) String() string { return proto.CompactTextString(m) }
+func (*KnownTypes) ProtoMessage() {}
+func (*KnownTypes) Descriptor() ([]byte, []int) { return fileDescriptor1, []int{8} }
+
+func (m *KnownTypes) GetAn() *google_protobuf.Any {
+ if m != nil {
+ return m.An
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetDur() *google_protobuf1.Duration {
+ if m != nil {
+ return m.Dur
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetSt() *google_protobuf2.Struct {
+ if m != nil {
+ return m.St
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetTs() *google_protobuf3.Timestamp {
+ if m != nil {
+ return m.Ts
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetLv() *google_protobuf2.ListValue {
+ if m != nil {
+ return m.Lv
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetVal() *google_protobuf2.Value {
+ if m != nil {
+ return m.Val
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetDbl() *google_protobuf4.DoubleValue {
+ if m != nil {
+ return m.Dbl
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetFlt() *google_protobuf4.FloatValue {
+ if m != nil {
+ return m.Flt
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetI64() *google_protobuf4.Int64Value {
+ if m != nil {
+ return m.I64
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetU64() *google_protobuf4.UInt64Value {
+ if m != nil {
+ return m.U64
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetI32() *google_protobuf4.Int32Value {
+ if m != nil {
+ return m.I32
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetU32() *google_protobuf4.UInt32Value {
+ if m != nil {
+ return m.U32
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetBool() *google_protobuf4.BoolValue {
+ if m != nil {
+ return m.Bool
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetStr() *google_protobuf4.StringValue {
+ if m != nil {
+ return m.Str
+ }
+ return nil
+}
+
+func (m *KnownTypes) GetBytes() *google_protobuf4.BytesValue {
+ if m != nil {
+ return m.Bytes
+ }
+ return nil
+}
+
+var E_Name = &proto.ExtensionDesc{
+ ExtendedType: (*Real)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 124,
+ Name: "jsonpb.name",
+ Tag: "bytes,124,opt,name=name",
+ Filename: "test_objects.proto",
+}
+
+func init() {
+ proto.RegisterType((*Simple)(nil), "jsonpb.Simple")
+ proto.RegisterType((*NonFinites)(nil), "jsonpb.NonFinites")
+ proto.RegisterType((*Repeats)(nil), "jsonpb.Repeats")
+ proto.RegisterType((*Widget)(nil), "jsonpb.Widget")
+ proto.RegisterType((*Maps)(nil), "jsonpb.Maps")
+ proto.RegisterType((*MsgWithOneof)(nil), "jsonpb.MsgWithOneof")
+ proto.RegisterType((*Real)(nil), "jsonpb.Real")
+ proto.RegisterType((*Complex)(nil), "jsonpb.Complex")
+ proto.RegisterType((*KnownTypes)(nil), "jsonpb.KnownTypes")
+ proto.RegisterEnum("jsonpb.Widget_Color", Widget_Color_name, Widget_Color_value)
+ proto.RegisterExtension(E_Complex_RealExtension)
+ proto.RegisterExtension(E_Name)
+}
+
+func init() { proto.RegisterFile("test_objects.proto", fileDescriptor1) }
+
+var fileDescriptor1 = []byte{
+ // 1160 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x95, 0x41, 0x73, 0xdb, 0x44,
+ 0x14, 0xc7, 0x23, 0xc9, 0x92, 0xed, 0x75, 0x92, 0x9a, 0x6d, 0xda, 0x2a, 0x26, 0x80, 0xc6, 0x94,
+ 0x22, 0x0a, 0x75, 0x07, 0xc7, 0xe3, 0x61, 0x0a, 0x97, 0xa4, 0x71, 0x29, 0x43, 0x13, 0x98, 0x4d,
+ 0x43, 0x8f, 0x1e, 0x39, 0x5a, 0xbb, 0x2a, 0xf2, 0xae, 0x67, 0x77, 0x95, 0xd4, 0x03, 0x87, 0x9c,
+ 0x39, 0x32, 0x7c, 0x05, 0xf8, 0x08, 0x1c, 0xf8, 0x74, 0xcc, 0xdb, 0x95, 0xac, 0xc4, 0x8e, 0x4f,
+ 0xf1, 0x7b, 0xef, 0xff, 0xfe, 0x59, 0xed, 0x6f, 0x77, 0x1f, 0xc2, 0x8a, 0x4a, 0x35, 0xe4, 0xa3,
+ 0x77, 0xf4, 0x5c, 0xc9, 0xce, 0x4c, 0x70, 0xc5, 0xb1, 0xf7, 0x4e, 0x72, 0x36, 0x1b, 0xb5, 0x76,
+ 0x27, 0x9c, 0x4f, 0x52, 0xfa, 0x54, 0x67, 0x47, 0xd9, 0xf8, 0x69, 0xc4, 0xe6, 0x46, 0xd2, 0xfa,
+ 0x78, 0xb9, 0x14, 0x67, 0x22, 0x52, 0x09, 0x67, 0x79, 0x7d, 0x6f, 0xb9, 0x2e, 0x95, 0xc8, 0xce,
+ 0x55, 0x5e, 0xfd, 0x64, 0xb9, 0xaa, 0x92, 0x29, 0x95, 0x2a, 0x9a, 0xce, 0xd6, 0xd9, 0x5f, 0x8a,
+ 0x68, 0x36, 0xa3, 0x22, 0x5f, 0x61, 0xfb, 0x6f, 0x1b, 0x79, 0xa7, 0xc9, 0x74, 0x96, 0x52, 0x7c,
+ 0x0f, 0x79, 0x7c, 0x38, 0xe2, 0x3c, 0xf5, 0xad, 0xc0, 0x0a, 0x6b, 0xc4, 0xe5, 0x87, 0x9c, 0xa7,
+ 0xf8, 0x01, 0xaa, 0xf2, 0x61, 0xc2, 0xd4, 0x7e, 0xd7, 0xb7, 0x03, 0x2b, 0x74, 0x89, 0xc7, 0x7f,
+ 0x80, 0x68, 0x51, 0xe8, 0xf7, 0x7c, 0x27, 0xb0, 0x42, 0xc7, 0x14, 0xfa, 0x3d, 0xbc, 0x8b, 0x6a,
+ 0x7c, 0x98, 0x99, 0x96, 0x4a, 0x60, 0x85, 0x5b, 0xa4, 0xca, 0xcf, 0x74, 0x58, 0x96, 0xfa, 0x3d,
+ 0xdf, 0x0d, 0xac, 0xb0, 0x92, 0x97, 0x8a, 0x2e, 0x69, 0xba, 0xbc, 0xc0, 0x0a, 0x3f, 0x20, 0x55,
+ 0x7e, 0x7a, 0xad, 0x4b, 0x9a, 0xae, 0x6a, 0x60, 0x85, 0x38, 0x2f, 0xf5, 0x7b, 0x66, 0x11, 0xe3,
+ 0x94, 0x47, 0xca, 0xaf, 0x05, 0x56, 0x68, 0x13, 0x8f, 0xbf, 0x80, 0xc8, 0xf4, 0xc4, 0x3c, 0x1b,
+ 0xa5, 0xd4, 0xaf, 0x07, 0x56, 0x68, 0x91, 0x2a, 0x3f, 0xd2, 0x61, 0x6e, 0xa7, 0x44, 0xc2, 0x26,
+ 0x3e, 0x0a, 0xac, 0xb0, 0x0e, 0x76, 0x3a, 0x34, 0x76, 0xa3, 0xb9, 0xa2, 0xd2, 0x6f, 0x04, 0x56,
+ 0xb8, 0x49, 0x3c, 0x7e, 0x08, 0x51, 0xfb, 0x4f, 0x0b, 0xa1, 0x13, 0xce, 0x5e, 0x24, 0x2c, 0x51,
+ 0x54, 0xe2, 0xbb, 0xc8, 0x1d, 0x0f, 0x59, 0xc4, 0xf4, 0x56, 0xd9, 0xa4, 0x32, 0x3e, 0x89, 0x18,
+ 0x6c, 0xe0, 0x78, 0x38, 0x4b, 0xd8, 0x58, 0x6f, 0x94, 0x4d, 0xdc, 0xf1, 0xcf, 0x09, 0x1b, 0x9b,
+ 0x34, 0x83, 0xb4, 0x93, 0xa7, 0x4f, 0x20, 0x7d, 0x17, 0xb9, 0xb1, 0xb6, 0xa8, 0xe8, 0xd5, 0x55,
+ 0xe2, 0xdc, 0x22, 0x36, 0x16, 0xae, 0xce, 0xba, 0x71, 0x61, 0x11, 0x1b, 0x0b, 0x2f, 0x4f, 0x83,
+ 0x45, 0xfb, 0x1f, 0x1b, 0x55, 0x09, 0x9d, 0xd1, 0x48, 0x49, 0x90, 0x88, 0x82, 0x9e, 0x03, 0xf4,
+ 0x44, 0x41, 0x4f, 0x2c, 0xe8, 0x39, 0x40, 0x4f, 0x2c, 0xe8, 0x89, 0x05, 0x3d, 0x07, 0xe8, 0x89,
+ 0x05, 0x3d, 0x51, 0xd2, 0x73, 0x80, 0x9e, 0x28, 0xe9, 0x89, 0x92, 0x9e, 0x03, 0xf4, 0x44, 0x49,
+ 0x4f, 0x94, 0xf4, 0x1c, 0xa0, 0x27, 0x4e, 0xaf, 0x75, 0x2d, 0xe8, 0x39, 0x40, 0x4f, 0x94, 0xf4,
+ 0xc4, 0x82, 0x9e, 0x03, 0xf4, 0xc4, 0x82, 0x9e, 0x28, 0xe9, 0x39, 0x40, 0x4f, 0x94, 0xf4, 0x44,
+ 0x49, 0xcf, 0x01, 0x7a, 0xa2, 0xa4, 0x27, 0x16, 0xf4, 0x1c, 0xa0, 0x27, 0x0c, 0xbd, 0x7f, 0x6d,
+ 0xe4, 0xbd, 0x49, 0xe2, 0x09, 0x55, 0xf8, 0x31, 0x72, 0xcf, 0x79, 0xca, 0x85, 0x26, 0xb7, 0xdd,
+ 0xdd, 0xe9, 0x98, 0x2b, 0xda, 0x31, 0xe5, 0xce, 0x73, 0xa8, 0x11, 0x23, 0xc1, 0x4f, 0xc0, 0xcf,
+ 0xa8, 0x61, 0xf3, 0xd6, 0xa9, 0x3d, 0xa1, 0xff, 0xe2, 0x47, 0xc8, 0x93, 0xfa, 0x2a, 0xe9, 0x53,
+ 0xd5, 0xe8, 0x6e, 0x17, 0x6a, 0x73, 0xc1, 0x48, 0x5e, 0xc5, 0x5f, 0x98, 0x0d, 0xd1, 0x4a, 0x58,
+ 0xe7, 0xaa, 0x12, 0x36, 0x28, 0x97, 0x56, 0x85, 0x01, 0xec, 0xef, 0x68, 0xcf, 0x3b, 0x85, 0x32,
+ 0xe7, 0x4e, 0x8a, 0x3a, 0xfe, 0x0a, 0xd5, 0xc5, 0xb0, 0x10, 0xdf, 0xd3, 0xb6, 0x2b, 0xe2, 0x9a,
+ 0xc8, 0x7f, 0xb5, 0x3f, 0x43, 0xae, 0x59, 0x74, 0x15, 0x39, 0x64, 0x70, 0xd4, 0xdc, 0xc0, 0x75,
+ 0xe4, 0x7e, 0x4f, 0x06, 0x83, 0x93, 0xa6, 0x85, 0x6b, 0xa8, 0x72, 0xf8, 0xea, 0x6c, 0xd0, 0xb4,
+ 0xdb, 0x7f, 0xd9, 0xa8, 0x72, 0x1c, 0xcd, 0x24, 0xfe, 0x16, 0x35, 0xa6, 0xe6, 0xb8, 0xc0, 0xde,
+ 0xeb, 0x33, 0xd6, 0xe8, 0x7e, 0x58, 0xf8, 0x83, 0xa4, 0x73, 0xac, 0xcf, 0xcf, 0xa9, 0x12, 0x03,
+ 0xa6, 0xc4, 0x9c, 0xd4, 0xa7, 0x45, 0x8c, 0x0f, 0xd0, 0xd6, 0x54, 0x9f, 0xcd, 0xe2, 0xab, 0x6d,
+ 0xdd, 0xfe, 0xd1, 0xcd, 0x76, 0x38, 0xaf, 0xe6, 0xb3, 0x8d, 0x41, 0x63, 0x5a, 0x66, 0x5a, 0xdf,
+ 0xa1, 0xed, 0x9b, 0xfe, 0xb8, 0x89, 0x9c, 0x5f, 0xe9, 0x5c, 0x63, 0x74, 0x08, 0xfc, 0xc4, 0x3b,
+ 0xc8, 0xbd, 0x88, 0xd2, 0x8c, 0xea, 0xeb, 0x57, 0x27, 0x26, 0x78, 0x66, 0x7f, 0x63, 0xb5, 0x4e,
+ 0x50, 0x73, 0xd9, 0xfe, 0x7a, 0x7f, 0xcd, 0xf4, 0x3f, 0xbc, 0xde, 0xbf, 0x0a, 0xa5, 0xf4, 0x6b,
+ 0xff, 0x61, 0xa1, 0xcd, 0x63, 0x39, 0x79, 0x93, 0xa8, 0xb7, 0x3f, 0x31, 0xca, 0xc7, 0xf8, 0x3e,
+ 0x72, 0x55, 0xa2, 0x52, 0xaa, 0xed, 0xea, 0x2f, 0x37, 0x88, 0x09, 0xb1, 0x8f, 0x3c, 0x19, 0xa5,
+ 0x91, 0x98, 0x6b, 0x4f, 0xe7, 0xe5, 0x06, 0xc9, 0x63, 0xdc, 0x42, 0xd5, 0xe7, 0x3c, 0x83, 0x95,
+ 0xe8, 0x67, 0x01, 0x7a, 0x8a, 0x04, 0xfe, 0x14, 0x6d, 0xbe, 0xe5, 0x53, 0x3a, 0x8c, 0xe2, 0x58,
+ 0x50, 0x29, 0xf5, 0x0b, 0x01, 0x82, 0x06, 0x64, 0x0f, 0x4c, 0xf2, 0xb0, 0x8a, 0xdc, 0x8c, 0x25,
+ 0x9c, 0xb5, 0x1f, 0xa1, 0x0a, 0xa1, 0x51, 0x5a, 0x7e, 0xbe, 0x65, 0xde, 0x08, 0x1d, 0x3c, 0xae,
+ 0xd5, 0xe2, 0xe6, 0xd5, 0xd5, 0xd5, 0x95, 0xdd, 0xbe, 0x84, 0xff, 0x08, 0x5f, 0xf2, 0x1e, 0xef,
+ 0xa1, 0x7a, 0x32, 0x8d, 0x26, 0x09, 0x83, 0x95, 0x19, 0x79, 0x99, 0x28, 0x5b, 0xba, 0x47, 0x68,
+ 0x5b, 0xd0, 0x28, 0x1d, 0xd2, 0xf7, 0x8a, 0x32, 0x99, 0x70, 0x86, 0x37, 0xcb, 0x23, 0x15, 0xa5,
+ 0xfe, 0x6f, 0x37, 0xcf, 0x64, 0x6e, 0x4f, 0xb6, 0xa0, 0x69, 0x50, 0xf4, 0xb4, 0xff, 0x73, 0x11,
+ 0xfa, 0x91, 0xf1, 0x4b, 0xf6, 0x7a, 0x3e, 0xa3, 0x12, 0x3f, 0x44, 0x76, 0xc4, 0xfc, 0x6d, 0xdd,
+ 0xba, 0xd3, 0x31, 0xf3, 0xa9, 0x53, 0xcc, 0xa7, 0xce, 0x01, 0x9b, 0x13, 0x3b, 0x62, 0xf8, 0x4b,
+ 0xe4, 0xc4, 0x99, 0xb9, 0xa5, 0x8d, 0xee, 0xee, 0x8a, 0xec, 0x28, 0x9f, 0x92, 0x04, 0x54, 0xf8,
+ 0x73, 0x64, 0x4b, 0xe5, 0x6f, 0x6a, 0xed, 0x83, 0x15, 0xed, 0xa9, 0x9e, 0x98, 0xc4, 0x96, 0x70,
+ 0xfb, 0x6d, 0x25, 0x73, 0xbe, 0xad, 0x15, 0xe1, 0xeb, 0x62, 0x78, 0x12, 0x5b, 0x49, 0xd0, 0xa6,
+ 0x17, 0xfe, 0x9d, 0x35, 0xda, 0x57, 0x89, 0x54, 0xbf, 0xc0, 0x0e, 0x13, 0x3b, 0xbd, 0xc0, 0x21,
+ 0x72, 0x2e, 0xa2, 0xd4, 0x6f, 0x6a, 0xf1, 0xfd, 0x15, 0xb1, 0x11, 0x82, 0x04, 0x77, 0x90, 0x13,
+ 0x8f, 0x52, 0xcd, 0xbc, 0xd1, 0xdd, 0x5b, 0xfd, 0x2e, 0xfd, 0xc8, 0xe5, 0xfa, 0x78, 0x94, 0xe2,
+ 0x27, 0xc8, 0x19, 0xa7, 0x4a, 0x1f, 0x01, 0xb8, 0x70, 0xcb, 0x7a, 0xfd, 0x5c, 0xe6, 0xf2, 0x71,
+ 0xaa, 0x40, 0x9e, 0xe4, 0xb3, 0xf5, 0x36, 0xb9, 0xbe, 0x42, 0xb9, 0x3c, 0xe9, 0xf7, 0x60, 0x35,
+ 0x59, 0xbf, 0xa7, 0xa7, 0xca, 0x6d, 0xab, 0x39, 0xbb, 0xae, 0xcf, 0xfa, 0x3d, 0x6d, 0xbf, 0xdf,
+ 0xd5, 0x43, 0x78, 0x8d, 0xfd, 0x7e, 0xb7, 0xb0, 0xdf, 0xef, 0x6a, 0xfb, 0xfd, 0xae, 0x9e, 0xcc,
+ 0xeb, 0xec, 0x17, 0xfa, 0x4c, 0xeb, 0x2b, 0x7a, 0x84, 0xd5, 0xd7, 0x6c, 0x3a, 0xdc, 0x61, 0x23,
+ 0xd7, 0x3a, 0xf0, 0x87, 0xd7, 0x08, 0xad, 0xf1, 0x37, 0x63, 0x21, 0xf7, 0x97, 0x4a, 0xe0, 0xaf,
+ 0x91, 0x5b, 0x0e, 0xf7, 0xdb, 0x3e, 0x40, 0x8f, 0x0b, 0xd3, 0x60, 0x94, 0xcf, 0x02, 0x54, 0x61,
+ 0xd1, 0x94, 0x2e, 0x1d, 0xfc, 0xdf, 0xf5, 0x0b, 0xa3, 0x2b, 0xff, 0x07, 0x00, 0x00, 0xff, 0xff,
+ 0xd5, 0x39, 0x32, 0x09, 0xf9, 0x09, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto
new file mode 100644
index 0000000..0d2fc1f
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/jsonpb/jsonpb_test_proto/test_objects.proto
@@ -0,0 +1,147 @@
+// 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.
+
+syntax = "proto2";
+
+import "google/protobuf/any.proto";
+import "google/protobuf/duration.proto";
+import "google/protobuf/struct.proto";
+import "google/protobuf/timestamp.proto";
+import "google/protobuf/wrappers.proto";
+
+package jsonpb;
+
+// Test message for holding primitive types.
+message Simple {
+ optional bool o_bool = 1;
+ optional int32 o_int32 = 2;
+ optional int64 o_int64 = 3;
+ optional uint32 o_uint32 = 4;
+ optional uint64 o_uint64 = 5;
+ optional sint32 o_sint32 = 6;
+ optional sint64 o_sint64 = 7;
+ optional float o_float = 8;
+ optional double o_double = 9;
+ optional string o_string = 10;
+ optional bytes o_bytes = 11;
+}
+
+// Test message for holding special non-finites primitives.
+message NonFinites {
+ optional float f_nan = 1;
+ optional float f_pinf = 2;
+ optional float f_ninf = 3;
+ optional double d_nan = 4;
+ optional double d_pinf = 5;
+ optional double d_ninf = 6;
+}
+
+// Test message for holding repeated primitives.
+message Repeats {
+ repeated bool r_bool = 1;
+ repeated int32 r_int32 = 2;
+ repeated int64 r_int64 = 3;
+ repeated uint32 r_uint32 = 4;
+ repeated uint64 r_uint64 = 5;
+ repeated sint32 r_sint32 = 6;
+ repeated sint64 r_sint64 = 7;
+ repeated float r_float = 8;
+ repeated double r_double = 9;
+ repeated string r_string = 10;
+ repeated bytes r_bytes = 11;
+}
+
+// Test message for holding enums and nested messages.
+message Widget {
+ enum Color {
+ RED = 0;
+ GREEN = 1;
+ BLUE = 2;
+ };
+ optional Color color = 1;
+ repeated Color r_color = 2;
+
+ optional Simple simple = 10;
+ repeated Simple r_simple = 11;
+
+ optional Repeats repeats = 20;
+ repeated Repeats r_repeats = 21;
+}
+
+message Maps {
+ map m_int64_str = 1;
+ map m_bool_simple = 2;
+}
+
+message MsgWithOneof {
+ oneof union {
+ string title = 1;
+ int64 salary = 2;
+ string Country = 3;
+ string home_address = 4;
+ }
+}
+
+message Real {
+ optional double value = 1;
+ extensions 100 to max;
+}
+
+extend Real {
+ optional string name = 124;
+}
+
+message Complex {
+ extend Real {
+ optional Complex real_extension = 123;
+ }
+ optional double imaginary = 1;
+ extensions 100 to max;
+}
+
+message KnownTypes {
+ optional google.protobuf.Any an = 14;
+ optional google.protobuf.Duration dur = 1;
+ optional google.protobuf.Struct st = 12;
+ optional google.protobuf.Timestamp ts = 2;
+ optional google.protobuf.ListValue lv = 15;
+ optional google.protobuf.Value val = 16;
+
+ optional google.protobuf.DoubleValue dbl = 3;
+ optional google.protobuf.FloatValue flt = 4;
+ optional google.protobuf.Int64Value i64 = 5;
+ optional google.protobuf.UInt64Value u64 = 6;
+ optional google.protobuf.Int32Value i32 = 7;
+ optional google.protobuf.UInt32Value u32 = 8;
+ optional google.protobuf.BoolValue bool = 9;
+ optional google.protobuf.StringValue str = 10;
+ optional google.protobuf.BytesValue bytes = 11;
+}
diff --git a/vendor/github.com/golang/protobuf/proto/Makefile b/vendor/github.com/golang/protobuf/proto/Makefile
index f1f0656..e2e0651 100644
--- a/vendor/github.com/golang/protobuf/proto/Makefile
+++ b/vendor/github.com/golang/protobuf/proto/Makefile
@@ -39,5 +39,5 @@ test: install generate-test-pbs
generate-test-pbs:
make install
make -C testdata
- protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata:. proto3_proto/proto3.proto
+ protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata,Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. proto3_proto/proto3.proto
make
diff --git a/vendor/github.com/golang/protobuf/proto/all_test.go b/vendor/github.com/golang/protobuf/proto/all_test.go
index 5a9b6a4..41451a4 100644
--- a/vendor/github.com/golang/protobuf/proto/all_test.go
+++ b/vendor/github.com/golang/protobuf/proto/all_test.go
@@ -401,17 +401,18 @@ type fakeMarshaler struct {
err error
}
-func (f fakeMarshaler) Marshal() ([]byte, error) {
- return f.b, f.err
+func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err }
+func (f *fakeMarshaler) String() string { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) }
+func (f *fakeMarshaler) ProtoMessage() {}
+func (f *fakeMarshaler) Reset() {}
+
+type msgWithFakeMarshaler struct {
+ M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"`
}
-func (f fakeMarshaler) String() string {
- return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err)
-}
-
-func (f fakeMarshaler) ProtoMessage() {}
-
-func (f fakeMarshaler) Reset() {}
+func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) }
+func (m *msgWithFakeMarshaler) ProtoMessage() {}
+func (m *msgWithFakeMarshaler) Reset() {}
// Simple tests for proto messages that implement the Marshaler interface.
func TestMarshalerEncoding(t *testing.T) {
@@ -419,36 +420,65 @@ func TestMarshalerEncoding(t *testing.T) {
name string
m Message
want []byte
- wantErr error
+ errType reflect.Type
}{
{
name: "Marshaler that fails",
- m: fakeMarshaler{
+ m: &fakeMarshaler{
err: errors.New("some marshal err"),
b: []byte{5, 6, 7},
},
- // Since there's an error, nothing should be written to buffer.
- want: nil,
- wantErr: errors.New("some marshal err"),
+ // Since the Marshal method returned bytes, they should be written to the
+ // buffer. (For efficiency, we assume that Marshal implementations are
+ // always correct w.r.t. RequiredNotSetError and output.)
+ want: []byte{5, 6, 7},
+ errType: reflect.TypeOf(errors.New("some marshal err")),
+ },
+ {
+ name: "Marshaler that fails with RequiredNotSetError",
+ m: &msgWithFakeMarshaler{
+ M: &fakeMarshaler{
+ err: &RequiredNotSetError{},
+ b: []byte{5, 6, 7},
+ },
+ },
+ // Since there's an error that can be continued after,
+ // the buffer should be written.
+ want: []byte{
+ 10, 3, // for &msgWithFakeMarshaler
+ 5, 6, 7, // for &fakeMarshaler
+ },
+ errType: reflect.TypeOf(&RequiredNotSetError{}),
},
{
name: "Marshaler that succeeds",
- m: fakeMarshaler{
+ m: &fakeMarshaler{
b: []byte{0, 1, 2, 3, 4, 127, 255},
},
- want: []byte{0, 1, 2, 3, 4, 127, 255},
- wantErr: nil,
+ want: []byte{0, 1, 2, 3, 4, 127, 255},
},
}
for _, test := range tests {
b := NewBuffer(nil)
err := b.Marshal(test.m)
- if !reflect.DeepEqual(test.wantErr, err) {
- t.Errorf("%s: got err %v wanted %v", test.name, err, test.wantErr)
+ if reflect.TypeOf(err) != test.errType {
+ t.Errorf("%s: got err %T(%v) wanted %T", test.name, err, err, test.errType)
}
if !reflect.DeepEqual(test.want, b.Bytes()) {
t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want)
}
+ if size := Size(test.m); size != len(b.Bytes()) {
+ t.Errorf("%s: Size(_) = %v, but marshaled to %v bytes", test.name, size, len(b.Bytes()))
+ }
+
+ m, mErr := Marshal(test.m)
+ if !bytes.Equal(b.Bytes(), m) {
+ t.Errorf("%s: Marshal returned %v, but (*Buffer).Marshal wrote %v", test.name, m, b.Bytes())
+ }
+ if !reflect.DeepEqual(err, mErr) {
+ t.Errorf("%s: Marshal err = %q, but (*Buffer).Marshal returned %q",
+ test.name, fmt.Sprint(mErr), fmt.Sprint(err))
+ }
}
}
@@ -1281,7 +1311,7 @@ func TestEnum(t *testing.T) {
// We don't care what the value actually is, just as long as it doesn't crash.
func TestPrintingNilEnumFields(t *testing.T) {
pb := new(GoEnum)
- fmt.Sprintf("%+v", pb)
+ _ = fmt.Sprintf("%+v", pb)
}
// Verify that absent required fields cause Marshal/Unmarshal to return errors.
@@ -1290,7 +1320,7 @@ func TestRequiredFieldEnforcement(t *testing.T) {
_, err := Marshal(pb)
if err == nil {
t.Error("marshal: expected error, got nil")
- } else if strings.Index(err.Error(), "Label") < 0 {
+ } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Label") {
t.Errorf("marshal: bad error type: %v", err)
}
@@ -1301,16 +1331,42 @@ func TestRequiredFieldEnforcement(t *testing.T) {
err = Unmarshal(buf, pb)
if err == nil {
t.Error("unmarshal: expected error, got nil")
- } else if strings.Index(err.Error(), "{Unknown}") < 0 {
+ } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "{Unknown}") {
+ t.Errorf("unmarshal: bad error type: %v", err)
+ }
+}
+
+// Verify that absent required fields in groups cause Marshal/Unmarshal to return errors.
+func TestRequiredFieldEnforcementGroups(t *testing.T) {
+ pb := &GoTestRequiredGroupField{Group: &GoTestRequiredGroupField_Group{}}
+ if _, err := Marshal(pb); err == nil {
+ t.Error("marshal: expected error, got nil")
+ } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") {
+ t.Errorf("marshal: bad error type: %v", err)
+ }
+
+ buf := []byte{11, 12}
+ if err := Unmarshal(buf, pb); err == nil {
+ t.Error("unmarshal: expected error, got nil")
+ } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.{Unknown}") {
t.Errorf("unmarshal: bad error type: %v", err)
}
}
func TestTypedNilMarshal(t *testing.T) {
// A typed nil should return ErrNil and not crash.
- _, err := Marshal((*GoEnum)(nil))
- if err != ErrNil {
- t.Errorf("Marshal: got err %v, want ErrNil", err)
+ {
+ var m *GoEnum
+ if _, err := Marshal(m); err != ErrNil {
+ t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err)
+ }
+ }
+
+ {
+ m := &Communique{Union: &Communique_Msg{nil}}
+ if _, err := Marshal(m); err == nil || err == ErrNil {
+ t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err)
+ }
}
}
@@ -1926,14 +1982,153 @@ func TestMapFieldRoundTrips(t *testing.T) {
}
func TestMapFieldWithNil(t *testing.T) {
- m := &MessageWithMap{
+ m1 := &MessageWithMap{
MsgMapping: map[int64]*FloatingPoint{
1: nil,
},
}
+ b, err := Marshal(m1)
+ if err != nil {
+ t.Fatalf("Marshal: %v", err)
+ }
+ m2 := new(MessageWithMap)
+ if err := Unmarshal(b, m2); err != nil {
+ t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b)
+ }
+ if v, ok := m2.MsgMapping[1]; !ok {
+ t.Error("msg_mapping[1] not present")
+ } else if v != nil {
+ t.Errorf("msg_mapping[1] not nil: %v", v)
+ }
+}
+
+func TestMapFieldWithNilBytes(t *testing.T) {
+ m1 := &MessageWithMap{
+ ByteMapping: map[bool][]byte{
+ false: []byte{},
+ true: nil,
+ },
+ }
+ n := Size(m1)
+ b, err := Marshal(m1)
+ if err != nil {
+ t.Fatalf("Marshal: %v", err)
+ }
+ if n != len(b) {
+ t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b))
+ }
+ m2 := new(MessageWithMap)
+ if err := Unmarshal(b, m2); err != nil {
+ t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b)
+ }
+ if v, ok := m2.ByteMapping[false]; !ok {
+ t.Error("byte_mapping[false] not present")
+ } else if len(v) != 0 {
+ t.Errorf("byte_mapping[false] not empty: %#v", v)
+ }
+ if v, ok := m2.ByteMapping[true]; !ok {
+ t.Error("byte_mapping[true] not present")
+ } else if len(v) != 0 {
+ t.Errorf("byte_mapping[true] not empty: %#v", v)
+ }
+}
+
+func TestDecodeMapFieldMissingKey(t *testing.T) {
+ b := []byte{
+ 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes
+ // no key
+ 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m"
+ }
+ got := &MessageWithMap{}
+ err := Unmarshal(b, got)
+ if err != nil {
+ t.Fatalf("failed to marshal map with missing key: %v", err)
+ }
+ want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}}
+ if !Equal(got, want) {
+ t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want)
+ }
+}
+
+func TestDecodeMapFieldMissingValue(t *testing.T) {
+ b := []byte{
+ 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes
+ 0x08, 0x01, // varint key, value 1
+ // no value
+ }
+ got := &MessageWithMap{}
+ err := Unmarshal(b, got)
+ if err != nil {
+ t.Fatalf("failed to marshal map with missing value: %v", err)
+ }
+ want := &MessageWithMap{NameMapping: map[int32]string{1: ""}}
+ if !Equal(got, want) {
+ t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want)
+ }
+}
+
+func TestOneof(t *testing.T) {
+ m := &Communique{}
b, err := Marshal(m)
- if err == nil {
- t.Fatalf("Marshal of bad map should have failed, got these bytes: %v", b)
+ if err != nil {
+ t.Fatalf("Marshal of empty message with oneof: %v", err)
+ }
+ if len(b) != 0 {
+ t.Errorf("Marshal of empty message yielded too many bytes: %v", b)
+ }
+
+ m = &Communique{
+ Union: &Communique_Name{"Barry"},
+ }
+
+ // Round-trip.
+ b, err = Marshal(m)
+ if err != nil {
+ t.Fatalf("Marshal of message with oneof: %v", err)
+ }
+ if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5)
+ t.Errorf("Incorrect marshal of message with oneof: %v", b)
+ }
+ m.Reset()
+ if err := Unmarshal(b, m); err != nil {
+ t.Fatalf("Unmarshal of message with oneof: %v", err)
+ }
+ if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" {
+ t.Errorf("After round trip, Union = %+v", m.Union)
+ }
+ if name := m.GetName(); name != "Barry" {
+ t.Errorf("After round trip, GetName = %q, want %q", name, "Barry")
+ }
+
+ // Let's try with a message in the oneof.
+ m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}}
+ b, err = Marshal(m)
+ if err != nil {
+ t.Fatalf("Marshal of message with oneof set to message: %v", err)
+ }
+ if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16)
+ t.Errorf("Incorrect marshal of message with oneof set to message: %v", b)
+ }
+ m.Reset()
+ if err := Unmarshal(b, m); err != nil {
+ t.Fatalf("Unmarshal of message with oneof set to message: %v", err)
+ }
+ ss, ok := m.Union.(*Communique_Msg)
+ if !ok || ss.Msg.GetStringField() != "deep deep string" {
+ t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union)
+ }
+}
+
+func TestInefficientPackedBool(t *testing.T) {
+ // https://github.com/golang/protobuf/issues/76
+ inp := []byte{
+ 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes
+ // Usually a bool should take a single byte,
+ // but it is permitted to be any varint.
+ 0xb9, 0x30,
+ }
+ if err := Unmarshal(inp, new(MoreRepeated)); err != nil {
+ t.Error(err)
}
}
diff --git a/vendor/github.com/golang/protobuf/proto/any_test.go b/vendor/github.com/golang/protobuf/proto/any_test.go
new file mode 100644
index 0000000..1a3c22e
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/any_test.go
@@ -0,0 +1,300 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 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 proto_test
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/golang/protobuf/proto"
+
+ pb "github.com/golang/protobuf/proto/proto3_proto"
+ testpb "github.com/golang/protobuf/proto/testdata"
+ anypb "github.com/golang/protobuf/ptypes/any"
+)
+
+var (
+ expandedMarshaler = proto.TextMarshaler{ExpandAny: true}
+ expandedCompactMarshaler = proto.TextMarshaler{Compact: true, ExpandAny: true}
+)
+
+// anyEqual reports whether two messages which may be google.protobuf.Any or may
+// contain google.protobuf.Any fields are equal. We can't use proto.Equal for
+// comparison, because semantically equivalent messages may be marshaled to
+// binary in different tag order. Instead, trust that TextMarshaler with
+// ExpandAny option works and compare the text marshaling results.
+func anyEqual(got, want proto.Message) bool {
+ // if messages are proto.Equal, no need to marshal.
+ if proto.Equal(got, want) {
+ return true
+ }
+ g := expandedMarshaler.Text(got)
+ w := expandedMarshaler.Text(want)
+ return g == w
+}
+
+type golden struct {
+ m proto.Message
+ t, c string
+}
+
+var goldenMessages = makeGolden()
+
+func makeGolden() []golden {
+ nested := &pb.Nested{Bunny: "Monty"}
+ nb, err := proto.Marshal(nested)
+ if err != nil {
+ panic(err)
+ }
+ m1 := &pb.Message{
+ Name: "David",
+ ResultCount: 47,
+ Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb},
+ }
+ m2 := &pb.Message{
+ Name: "David",
+ ResultCount: 47,
+ Anything: &anypb.Any{TypeUrl: "http://[::1]/type.googleapis.com/" + proto.MessageName(nested), Value: nb},
+ }
+ m3 := &pb.Message{
+ Name: "David",
+ ResultCount: 47,
+ Anything: &anypb.Any{TypeUrl: `type.googleapis.com/"/` + proto.MessageName(nested), Value: nb},
+ }
+ m4 := &pb.Message{
+ Name: "David",
+ ResultCount: 47,
+ Anything: &anypb.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb},
+ }
+ m5 := &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}
+
+ any1 := &testpb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")}
+ proto.SetExtension(any1, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("foo")})
+ proto.SetExtension(any1, testpb.E_Ext_Text, proto.String("bar"))
+ any1b, err := proto.Marshal(any1)
+ if err != nil {
+ panic(err)
+ }
+ any2 := &testpb.MyMessage{Count: proto.Int32(42), Bikeshed: testpb.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}}
+ proto.SetExtension(any2, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("baz")})
+ any2b, err := proto.Marshal(any2)
+ if err != nil {
+ panic(err)
+ }
+ m6 := &pb.Message{
+ Name: "David",
+ ResultCount: 47,
+ Anything: &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b},
+ ManyThings: []*anypb.Any{
+ &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b},
+ &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b},
+ },
+ }
+
+ const (
+ m1Golden = `
+name: "David"
+result_count: 47
+anything: <
+ [type.googleapis.com/proto3_proto.Nested]: <
+ bunny: "Monty"
+ >
+>
+`
+ m2Golden = `
+name: "David"
+result_count: 47
+anything: <
+ ["http://[::1]/type.googleapis.com/proto3_proto.Nested"]: <
+ bunny: "Monty"
+ >
+>
+`
+ m3Golden = `
+name: "David"
+result_count: 47
+anything: <
+ ["type.googleapis.com/\"/proto3_proto.Nested"]: <
+ bunny: "Monty"
+ >
+>
+`
+ m4Golden = `
+name: "David"
+result_count: 47
+anything: <
+ [type.googleapis.com/a/path/proto3_proto.Nested]: <
+ bunny: "Monty"
+ >
+>
+`
+ m5Golden = `
+[type.googleapis.com/proto3_proto.Nested]: <
+ bunny: "Monty"
+>
+`
+ m6Golden = `
+name: "David"
+result_count: 47
+anything: <
+ [type.googleapis.com/testdata.MyMessage]: <
+ count: 47
+ name: "David"
+ [testdata.Ext.more]: <
+ data: "foo"
+ >
+ [testdata.Ext.text]: "bar"
+ >
+>
+many_things: <
+ [type.googleapis.com/testdata.MyMessage]: <
+ count: 42
+ bikeshed: GREEN
+ rep_bytes: "roboto"
+ [testdata.Ext.more]: <
+ data: "baz"
+ >
+ >
+>
+many_things: <
+ [type.googleapis.com/testdata.MyMessage]: <
+ count: 47
+ name: "David"
+ [testdata.Ext.more]: <
+ data: "foo"
+ >
+ [testdata.Ext.text]: "bar"
+ >
+>
+`
+ )
+ return []golden{
+ {m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "},
+ {m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "},
+ {m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "},
+ {m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "},
+ {m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "},
+ {m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "},
+ }
+}
+
+func TestMarshalGolden(t *testing.T) {
+ for _, tt := range goldenMessages {
+ if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want {
+ t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want)
+ }
+ if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want {
+ t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want)
+ }
+ }
+}
+
+func TestUnmarshalGolden(t *testing.T) {
+ for _, tt := range goldenMessages {
+ want := tt.m
+ got := proto.Clone(tt.m)
+ got.Reset()
+ if err := proto.UnmarshalText(tt.t, got); err != nil {
+ t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err)
+ }
+ if !anyEqual(got, want) {
+ t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want)
+ }
+ got.Reset()
+ if err := proto.UnmarshalText(tt.c, got); err != nil {
+ t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err)
+ }
+ if !anyEqual(got, want) {
+ t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want)
+ }
+ }
+}
+
+func TestMarshalUnknownAny(t *testing.T) {
+ m := &pb.Message{
+ Anything: &anypb.Any{
+ TypeUrl: "foo",
+ Value: []byte("bar"),
+ },
+ }
+ want := `anything: <
+ type_url: "foo"
+ value: "bar"
+>
+`
+ got := expandedMarshaler.Text(m)
+ if got != want {
+ t.Errorf("got\n`%s`\nwant\n`%s`", got, want)
+ }
+}
+
+func TestAmbiguousAny(t *testing.T) {
+ pb := &anypb.Any{}
+ err := proto.UnmarshalText(`
+ type_url: "ttt/proto3_proto.Nested"
+ value: "\n\x05Monty"
+ `, pb)
+ t.Logf("result: %v (error: %v)", expandedMarshaler.Text(pb), err)
+ if err != nil {
+ t.Errorf("failed to parse ambiguous Any message: %v", err)
+ }
+}
+
+func TestUnmarshalOverwriteAny(t *testing.T) {
+ pb := &anypb.Any{}
+ err := proto.UnmarshalText(`
+ [type.googleapis.com/a/path/proto3_proto.Nested]: <
+ bunny: "Monty"
+ >
+ [type.googleapis.com/a/path/proto3_proto.Nested]: <
+ bunny: "Rabbit of Caerbannog"
+ >
+ `, pb)
+ want := `line 7: Any message unpacked multiple times, or "type_url" already set`
+ if err.Error() != want {
+ t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want)
+ }
+}
+
+func TestUnmarshalAnyMixAndMatch(t *testing.T) {
+ pb := &anypb.Any{}
+ err := proto.UnmarshalText(`
+ value: "\n\x05Monty"
+ [type.googleapis.com/a/path/proto3_proto.Nested]: <
+ bunny: "Rabbit of Caerbannog"
+ >
+ `, pb)
+ want := `line 5: Any message unpacked multiple times, or "value" already set`
+ if err.Error() != want {
+ t.Errorf("incorrect error.\nHave: %v\nWant: %v", err.Error(), want)
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/proto/clone.go b/vendor/github.com/golang/protobuf/proto/clone.go
index 6c6a7d9..e392575 100644
--- a/vendor/github.com/golang/protobuf/proto/clone.go
+++ b/vendor/github.com/golang/protobuf/proto/clone.go
@@ -30,7 +30,7 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Protocol buffer deep copy and merge.
-// TODO: MessageSet and RawMessage.
+// TODO: RawMessage.
package proto
@@ -75,17 +75,24 @@ func Merge(dst, src Message) {
}
func mergeStruct(out, in reflect.Value) {
+ sprop := GetProperties(in.Type())
for i := 0; i < in.NumField(); i++ {
f := in.Type().Field(i)
if strings.HasPrefix(f.Name, "XXX_") {
continue
}
- mergeAny(out.Field(i), in.Field(i))
+ mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
}
- if emIn, ok := in.Addr().Interface().(extendableProto); ok {
- emOut := out.Addr().Interface().(extendableProto)
- mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap())
+ if emIn, ok := extendable(in.Addr().Interface()); ok {
+ emOut, _ := extendable(out.Addr().Interface())
+ mIn, muIn := emIn.extensionsRead()
+ if mIn != nil {
+ mOut := emOut.extensionsWrite()
+ muIn.Lock()
+ mergeExtension(mOut, mIn)
+ muIn.Unlock()
+ }
}
uf := in.FieldByName("XXX_unrecognized")
@@ -98,7 +105,10 @@ func mergeStruct(out, in reflect.Value) {
}
}
-func mergeAny(out, in reflect.Value) {
+// mergeAny performs a merge between two values of the same type.
+// viaPtr indicates whether the values were indirected through a pointer (implying proto2).
+// prop is set if this is a struct field (it may be nil).
+func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
if in.Type() == protoMessageType {
if !in.IsNil() {
if out.IsNil() {
@@ -112,7 +122,21 @@ func mergeAny(out, in reflect.Value) {
switch in.Kind() {
case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
reflect.String, reflect.Uint32, reflect.Uint64:
+ if !viaPtr && isProto3Zero(in) {
+ return
+ }
out.Set(in)
+ case reflect.Interface:
+ // Probably a oneof field; copy non-nil values.
+ if in.IsNil() {
+ return
+ }
+ // Allocate destination if it is not set, or set to a different type.
+ // Otherwise we will merge as normal.
+ if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
+ out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
+ }
+ mergeAny(out.Elem(), in.Elem(), false, nil)
case reflect.Map:
if in.Len() == 0 {
return
@@ -127,7 +151,7 @@ func mergeAny(out, in reflect.Value) {
switch elemKind {
case reflect.Ptr:
val = reflect.New(in.Type().Elem().Elem())
- mergeAny(val, in.MapIndex(key))
+ mergeAny(val, in.MapIndex(key), false, nil)
case reflect.Slice:
val = in.MapIndex(key)
val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
@@ -143,13 +167,21 @@ func mergeAny(out, in reflect.Value) {
if out.IsNil() {
out.Set(reflect.New(in.Elem().Type()))
}
- mergeAny(out.Elem(), in.Elem())
+ mergeAny(out.Elem(), in.Elem(), true, nil)
case reflect.Slice:
if in.IsNil() {
return
}
if in.Type().Elem().Kind() == reflect.Uint8 {
// []byte is a scalar bytes field, not a repeated field.
+
+ // Edge case: if this is in a proto3 message, a zero length
+ // bytes field is considered the zero value, and should not
+ // be merged.
+ if prop != nil && prop.proto3 && in.Len() == 0 {
+ return
+ }
+
// Make a deep copy.
// Append to []byte{} instead of []byte(nil) so that we never end up
// with a nil result.
@@ -167,7 +199,7 @@ func mergeAny(out, in reflect.Value) {
default:
for i := 0; i < n; i++ {
x := reflect.Indirect(reflect.New(in.Type().Elem()))
- mergeAny(x, in.Index(i))
+ mergeAny(x, in.Index(i), false, nil)
out.Set(reflect.Append(out, x))
}
}
@@ -184,7 +216,7 @@ func mergeExtension(out, in map[int32]Extension) {
eOut := Extension{desc: eIn.desc}
if eIn.value != nil {
v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
- mergeAny(v, reflect.ValueOf(eIn.value))
+ mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
eOut.value = v.Interface()
}
if eIn.enc != nil {
diff --git a/vendor/github.com/golang/protobuf/proto/clone_test.go b/vendor/github.com/golang/protobuf/proto/clone_test.go
index 9db0fb6..f607ff4 100644
--- a/vendor/github.com/golang/protobuf/proto/clone_test.go
+++ b/vendor/github.com/golang/protobuf/proto/clone_test.go
@@ -36,6 +36,7 @@ import (
"github.com/golang/protobuf/proto"
+ proto3pb "github.com/golang/protobuf/proto/proto3_proto"
pb "github.com/golang/protobuf/proto/testdata"
)
@@ -194,6 +195,9 @@ var mergeTests = []struct {
NameMapping: map[int32]string{6: "Nigel"},
MsgMapping: map[int64]*pb.FloatingPoint{
0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)},
+ 0x4002: &pb.FloatingPoint{
+ F: proto.Float64(2.0),
+ },
},
ByteMapping: map[bool][]byte{true: []byte("wowsa")},
},
@@ -202,6 +206,12 @@ var mergeTests = []struct {
6: "Bruce", // should be overwritten
7: "Andrew",
},
+ MsgMapping: map[int64]*pb.FloatingPoint{
+ 0x4002: &pb.FloatingPoint{
+ F: proto.Float64(3.0),
+ Exact: proto.Bool(true),
+ }, // the entire message should be overwritten
+ },
},
want: &pb.MessageWithMap{
NameMapping: map[int32]string{
@@ -210,10 +220,73 @@ var mergeTests = []struct {
},
MsgMapping: map[int64]*pb.FloatingPoint{
0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)},
+ 0x4002: &pb.FloatingPoint{
+ F: proto.Float64(2.0),
+ },
},
ByteMapping: map[bool][]byte{true: []byte("wowsa")},
},
},
+ // proto3 shouldn't merge zero values,
+ // in the same way that proto2 shouldn't merge nils.
+ {
+ src: &proto3pb.Message{
+ Name: "Aaron",
+ Data: []byte(""), // zero value, but not nil
+ },
+ dst: &proto3pb.Message{
+ HeightInCm: 176,
+ Data: []byte("texas!"),
+ },
+ want: &proto3pb.Message{
+ Name: "Aaron",
+ HeightInCm: 176,
+ Data: []byte("texas!"),
+ },
+ },
+ // Oneof fields should merge by assignment.
+ {
+ src: &pb.Communique{
+ Union: &pb.Communique_Number{41},
+ },
+ dst: &pb.Communique{
+ Union: &pb.Communique_Name{"Bobby Tables"},
+ },
+ want: &pb.Communique{
+ Union: &pb.Communique_Number{41},
+ },
+ },
+ // Oneof nil is the same as not set.
+ {
+ src: &pb.Communique{},
+ dst: &pb.Communique{
+ Union: &pb.Communique_Name{"Bobby Tables"},
+ },
+ want: &pb.Communique{
+ Union: &pb.Communique_Name{"Bobby Tables"},
+ },
+ },
+ {
+ src: &proto3pb.Message{
+ Terrain: map[string]*proto3pb.Nested{
+ "kay_a": &proto3pb.Nested{Cute: true}, // replace
+ "kay_b": &proto3pb.Nested{Bunny: "rabbit"}, // insert
+ },
+ },
+ dst: &proto3pb.Message{
+ Terrain: map[string]*proto3pb.Nested{
+ "kay_a": &proto3pb.Nested{Bunny: "lost"}, // replaced
+ "kay_c": &proto3pb.Nested{Bunny: "bunny"}, // keep
+ },
+ },
+ want: &proto3pb.Message{
+ Terrain: map[string]*proto3pb.Nested{
+ "kay_a": &proto3pb.Nested{Cute: true},
+ "kay_b": &proto3pb.Nested{Bunny: "rabbit"},
+ "kay_c": &proto3pb.Nested{Bunny: "bunny"},
+ },
+ },
+ },
}
func TestMerge(t *testing.T) {
diff --git a/vendor/github.com/golang/protobuf/proto/decode.go b/vendor/github.com/golang/protobuf/proto/decode.go
index 312e604..aa20729 100644
--- a/vendor/github.com/golang/protobuf/proto/decode.go
+++ b/vendor/github.com/golang/protobuf/proto/decode.go
@@ -46,6 +46,10 @@ import (
// errOverflow is returned when an integer is too large to be represented.
var errOverflow = errors.New("proto: integer overflow")
+// ErrInternalBadWireType is returned by generated code when an incorrect
+// wire type is encountered. It does not get returned to user code.
+var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof")
+
// The fundamental decoders that interpret bytes on the wire.
// Those that take integer types all return uint64 and are
// therefore of type valueDecoder.
@@ -57,7 +61,6 @@ var errOverflow = errors.New("proto: integer overflow")
// int32, int64, uint32, uint64, bool, and enum
// protocol buffer types.
func DecodeVarint(buf []byte) (x uint64, n int) {
- // x, n already 0
for shift := uint(0); shift < 64; shift += 7 {
if n >= len(buf) {
return 0, 0
@@ -74,13 +77,7 @@ func DecodeVarint(buf []byte) (x uint64, n int) {
return 0, 0
}
-// DecodeVarint reads a varint-encoded integer from the Buffer.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-func (p *Buffer) DecodeVarint() (x uint64, err error) {
- // x, err already 0
-
+func (p *Buffer) decodeVarintSlow() (x uint64, err error) {
i := p.index
l := len(p.buf)
@@ -103,6 +100,107 @@ func (p *Buffer) DecodeVarint() (x uint64, err error) {
return
}
+// DecodeVarint reads a varint-encoded integer from the Buffer.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+func (p *Buffer) DecodeVarint() (x uint64, err error) {
+ i := p.index
+ buf := p.buf
+
+ if i >= len(buf) {
+ return 0, io.ErrUnexpectedEOF
+ } else if buf[i] < 0x80 {
+ p.index++
+ return uint64(buf[i]), nil
+ } else if len(buf)-i < 10 {
+ return p.decodeVarintSlow()
+ }
+
+ var b uint64
+ // we already checked the first byte
+ x = uint64(buf[i]) - 0x80
+ i++
+
+ b = uint64(buf[i])
+ i++
+ x += b << 7
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 7
+
+ b = uint64(buf[i])
+ i++
+ x += b << 14
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 14
+
+ b = uint64(buf[i])
+ i++
+ x += b << 21
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 21
+
+ b = uint64(buf[i])
+ i++
+ x += b << 28
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 28
+
+ b = uint64(buf[i])
+ i++
+ x += b << 35
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 35
+
+ b = uint64(buf[i])
+ i++
+ x += b << 42
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 42
+
+ b = uint64(buf[i])
+ i++
+ x += b << 49
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 49
+
+ b = uint64(buf[i])
+ i++
+ x += b << 56
+ if b&0x80 == 0 {
+ goto done
+ }
+ x -= 0x80 << 56
+
+ b = uint64(buf[i])
+ i++
+ x += b << 63
+ if b&0x80 == 0 {
+ goto done
+ }
+ // x -= 0x80 << 63 // Always zero.
+
+ return 0, errOverflow
+
+done:
+ p.index = i
+ return x, nil
+}
+
// DecodeFixed64 reads a 64-bit integer from the Buffer.
// This is the format for the
// fixed64, sfixed64, and double protocol buffer types.
@@ -314,10 +412,30 @@ func UnmarshalMerge(buf []byte, pb Message) error {
return NewBuffer(buf).Unmarshal(pb)
}
+// DecodeMessage reads a count-delimited message from the Buffer.
+func (p *Buffer) DecodeMessage(pb Message) error {
+ enc, err := p.DecodeRawBytes(false)
+ if err != nil {
+ return err
+ }
+ return NewBuffer(enc).Unmarshal(pb)
+}
+
+// DecodeGroup reads a tag-delimited group from the Buffer.
+func (p *Buffer) DecodeGroup(pb Message) error {
+ typ, base, err := getbase(pb)
+ if err != nil {
+ return err
+ }
+ return p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), true, base)
+}
+
// Unmarshal parses the protocol buffer representation in the
// Buffer and places the decoded result in pb. If the struct
// underlying pb does not match the data in the buffer, the results can be
// unpredictable.
+//
+// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal.
func (p *Buffer) Unmarshal(pb Message) error {
// If the object can unmarshal itself, let it.
if u, ok := pb.(Unmarshaler); ok {
@@ -356,6 +474,11 @@ func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group
wire := int(u & 0x7)
if wire == WireEndGroup {
if is_group {
+ if required > 0 {
+ // Not enough information to determine the exact field.
+ // (See below.)
+ return &RequiredNotSetError{"{Unknown}"}
+ }
return nil // input is satisfied
}
return fmt.Errorf("proto: %s: wiretype end group for non-group", st)
@@ -368,15 +491,30 @@ func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group
if !ok {
// Maybe it's an extension?
if prop.extendable {
- if e := structPointer_Interface(base, st).(extendableProto); isExtensionField(e, int32(tag)) {
+ if e, _ := extendable(structPointer_Interface(base, st)); isExtensionField(e, int32(tag)) {
if err = o.skip(st, tag, wire); err == nil {
- ext := e.ExtensionMap()[int32(tag)] // may be missing
+ extmap := e.extensionsWrite()
+ ext := extmap[int32(tag)] // may be missing
ext.enc = append(ext.enc, o.buf[oi:o.index]...)
- e.ExtensionMap()[int32(tag)] = ext
+ extmap[int32(tag)] = ext
}
continue
}
}
+ // Maybe it's a oneof?
+ if prop.oneofUnmarshaler != nil {
+ m := structPointer_Interface(base, st).(Message)
+ // First return value indicates whether tag is a oneof field.
+ ok, err = prop.oneofUnmarshaler(m, tag, wire, o)
+ if err == ErrInternalBadWireType {
+ // Map the error to something more descriptive.
+ // Do the formatting here to save generated code space.
+ err = fmt.Errorf("bad wiretype for oneof field in %T", m)
+ }
+ if ok {
+ continue
+ }
+ }
err = o.skipAndSave(st, tag, wire, base, prop.unrecField)
continue
}
@@ -561,9 +699,13 @@ func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error
return err
}
nb := int(nn) // number of bytes of encoded bools
+ fin := o.index + nb
+ if fin < o.index {
+ return errOverflow
+ }
y := *v
- for i := 0; i < nb; i++ {
+ for o.index < fin {
u, err := p.valDec(o)
if err != nil {
return err
@@ -675,7 +817,7 @@ func (o *Buffer) dec_new_map(p *Properties, base structPointer) error {
oi := o.index // index at the end of this map entry
o.index -= len(raw) // move buffer back to start of map entry
- mptr := structPointer_Map(base, p.field, p.mtype) // *map[K]V
+ mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V
if mptr.Elem().IsNil() {
mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem()))
}
@@ -728,10 +870,11 @@ func (o *Buffer) dec_new_map(p *Properties, base structPointer) error {
}
}
keyelem, valelem := keyptr.Elem(), valptr.Elem()
- if !keyelem.IsValid() || !valelem.IsValid() {
- // We did not decode the key or the value in the map entry.
- // Either way, it's an invalid map entry.
- return fmt.Errorf("proto: bad map data: missing key/val")
+ if !keyelem.IsValid() {
+ keyelem = reflect.Zero(p.mtype.Key())
+ }
+ if !valelem.IsValid() {
+ valelem = reflect.Zero(p.mtype.Elem())
}
v.SetMapIndex(keyelem, valelem)
diff --git a/vendor/github.com/golang/protobuf/proto/decode_test.go b/vendor/github.com/golang/protobuf/proto/decode_test.go
new file mode 100644
index 0000000..2c4c31d
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/decode_test.go
@@ -0,0 +1,258 @@
+// 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.
+
+// +build go1.7
+
+package proto_test
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/golang/protobuf/proto"
+ tpb "github.com/golang/protobuf/proto/proto3_proto"
+)
+
+var (
+ bytesBlackhole []byte
+ msgBlackhole = new(tpb.Message)
+)
+
+// BenchmarkVarint32ArraySmall shows the performance on an array of small int32 fields (1 and
+// 2 bytes long).
+func BenchmarkVarint32ArraySmall(b *testing.B) {
+ for i := uint(1); i <= 10; i++ {
+ dist := genInt32Dist([7]int{0, 3, 1}, 1<2GB.
+ ErrTooLarge = errors.New("proto: message encodes to over 2 GB")
)
// The fundamental encoders that put bytes on the wire.
@@ -74,6 +82,10 @@ var (
const maxVarintBytes = 10 // maximum length of a varint
+// maxMarshalSize is the largest allowed size of an encoded protobuf,
+// since C++ and Java use signed int32s for the size.
+const maxMarshalSize = 1<<31 - 1
+
// EncodeVarint returns the varint encoding of x.
// This is the format for the
// int32, int64, uint32, uint64, bool, and enum
@@ -105,6 +117,11 @@ func (p *Buffer) EncodeVarint(x uint64) error {
return nil
}
+// SizeVarint returns the varint encoding size of an integer.
+func SizeVarint(x uint64) int {
+ return sizeVarint(x)
+}
+
func sizeVarint(x uint64) (n int) {
for {
n++
@@ -157,11 +174,11 @@ func sizeFixed32(x uint64) int {
// This is the format used for the sint64 protocol buffer type.
func (p *Buffer) EncodeZigzag64(x uint64) error {
// use signed number to get arithmetic right shift.
- return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+ return p.EncodeVarint((x << 1) ^ uint64((int64(x) >> 63)))
}
func sizeZigzag64(x uint64) int {
- return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
+ return sizeVarint((x << 1) ^ uint64((int64(x) >> 63)))
}
// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
@@ -217,10 +234,6 @@ func Marshal(pb Message) ([]byte, error) {
}
p := NewBuffer(nil)
err := p.Marshal(pb)
- var state errorState
- if err != nil && !state.shouldContinue(err, nil) {
- return nil, err
- }
if p.buf == nil && err == nil {
// Return a non-nil slice on success.
return []byte{}, nil
@@ -228,6 +241,20 @@ func Marshal(pb Message) ([]byte, error) {
return p.buf, err
}
+// EncodeMessage writes the protocol buffer to the Buffer,
+// prefixed by a varint-encoded length.
+func (p *Buffer) EncodeMessage(pb Message) error {
+ t, base, err := getbase(pb)
+ if structPointer_IsNil(base) {
+ return ErrNil
+ }
+ if err == nil {
+ var state errorState
+ err = p.enc_len_struct(GetProperties(t.Elem()), base, &state)
+ }
+ return err
+}
+
// Marshal takes the protocol buffer
// and encodes it into the wire format, writing the result to the
// Buffer.
@@ -235,11 +262,8 @@ func (p *Buffer) Marshal(pb Message) error {
// Can the object marshal itself?
if m, ok := pb.(Marshaler); ok {
data, err := m.Marshal()
- if err != nil {
- return err
- }
p.buf = append(p.buf, data...)
- return nil
+ return err
}
t, base, err := getbase(pb)
@@ -251,9 +275,12 @@ func (p *Buffer) Marshal(pb Message) error {
}
if collectStats {
- stats.Encode++
+ (stats).Encode++ // Parens are to work around a goimports bug.
}
+ if len(p.buf) > maxMarshalSize {
+ return ErrTooLarge
+ }
return err
}
@@ -275,7 +302,7 @@ func Size(pb Message) (n int) {
}
if collectStats {
- stats.Size++
+ (stats).Size++ // Parens are to work around a goimports bug.
}
return
@@ -318,7 +345,7 @@ func size_bool(p *Properties, base structPointer) int {
func size_proto3_bool(p *Properties, base structPointer) int {
v := *structPointer_BoolVal(base, p.field)
- if !v {
+ if !v && !p.oneof {
return 0
}
return len(p.tagcode) + 1 // each bool takes exactly one byte
@@ -361,7 +388,7 @@ func size_int32(p *Properties, base structPointer) (n int) {
func size_proto3_int32(p *Properties, base structPointer) (n int) {
v := structPointer_Word32Val(base, p.field)
x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
- if x == 0 {
+ if x == 0 && !p.oneof {
return 0
}
n += len(p.tagcode)
@@ -407,7 +434,7 @@ func size_uint32(p *Properties, base structPointer) (n int) {
func size_proto3_uint32(p *Properties, base structPointer) (n int) {
v := structPointer_Word32Val(base, p.field)
x := word32Val_Get(v)
- if x == 0 {
+ if x == 0 && !p.oneof {
return 0
}
n += len(p.tagcode)
@@ -452,7 +479,7 @@ func size_int64(p *Properties, base structPointer) (n int) {
func size_proto3_int64(p *Properties, base structPointer) (n int) {
v := structPointer_Word64Val(base, p.field)
x := word64Val_Get(v)
- if x == 0 {
+ if x == 0 && !p.oneof {
return 0
}
n += len(p.tagcode)
@@ -495,7 +522,7 @@ func size_string(p *Properties, base structPointer) (n int) {
func size_proto3_string(p *Properties, base structPointer) (n int) {
v := *structPointer_StringVal(base, p.field)
- if v == "" {
+ if v == "" && !p.oneof {
return 0
}
n += len(p.tagcode)
@@ -529,7 +556,7 @@ func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
}
o.buf = append(o.buf, p.tagcode...)
o.EncodeRawBytes(data)
- return nil
+ return state.err
}
o.buf = append(o.buf, p.tagcode...)
@@ -667,7 +694,7 @@ func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error
func size_slice_byte(p *Properties, base structPointer) (n int) {
s := *structPointer_Bytes(base, p.field)
- if s == nil {
+ if s == nil && !p.oneof {
return 0
}
n += len(p.tagcode)
@@ -677,7 +704,7 @@ func size_slice_byte(p *Properties, base structPointer) (n int) {
func size_proto3_slice_byte(p *Properties, base structPointer) (n int) {
s := *structPointer_Bytes(base, p.field)
- if len(s) == 0 {
+ if len(s) == 0 && !p.oneof {
return 0
}
n += len(p.tagcode)
@@ -980,7 +1007,6 @@ func size_slice_struct_message(p *Properties, base structPointer) (n int) {
if p.isMarshaler {
m := structPointer_Interface(structp, p.stype).(Marshaler)
data, _ := m.Marshal()
- n += len(p.tagcode)
n += sizeRawBytes(data)
continue
}
@@ -1039,10 +1065,32 @@ func size_slice_struct_group(p *Properties, base structPointer) (n int) {
// Encode an extension map.
func (o *Buffer) enc_map(p *Properties, base structPointer) error {
- v := *structPointer_ExtMap(base, p.field)
- if err := encodeExtensionMap(v); err != nil {
+ exts := structPointer_ExtMap(base, p.field)
+ if err := encodeExtensionsMap(*exts); err != nil {
return err
}
+
+ return o.enc_map_body(*exts)
+}
+
+func (o *Buffer) enc_exts(p *Properties, base structPointer) error {
+ exts := structPointer_Extensions(base, p.field)
+
+ v, mu := exts.extensionsRead()
+ if v == nil {
+ return nil
+ }
+
+ mu.Lock()
+ defer mu.Unlock()
+ if err := encodeExtensionsMap(v); err != nil {
+ return err
+ }
+
+ return o.enc_map_body(v)
+}
+
+func (o *Buffer) enc_map_body(v map[int32]Extension) error {
// Fast-path for common cases: zero or one extensions.
if len(v) <= 1 {
for _, e := range v {
@@ -1065,8 +1113,13 @@ func (o *Buffer) enc_map(p *Properties, base structPointer) error {
}
func size_map(p *Properties, base structPointer) int {
- v := *structPointer_ExtMap(base, p.field)
- return sizeExtensionMap(v)
+ v := structPointer_ExtMap(base, p.field)
+ return extensionsMapSize(*v)
+}
+
+func size_exts(p *Properties, base structPointer) int {
+ v := structPointer_Extensions(base, p.field)
+ return extensionsSize(v)
}
// Encode a map field.
@@ -1084,7 +1137,7 @@ func (o *Buffer) enc_new_map(p *Properties, base structPointer) error {
repeated MapFieldEntry map_field = N;
*/
- v := structPointer_Map(base, p.field, p.mtype).Elem() // map[K]V
+ v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
if v.Len() == 0 {
return nil
}
@@ -1095,22 +1148,16 @@ func (o *Buffer) enc_new_map(p *Properties, base structPointer) error {
if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil {
return err
}
- if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil {
+ if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil && err != ErrNil {
return err
}
return nil
}
- keys := v.MapKeys()
- sort.Sort(mapKeys(keys))
- for _, key := range keys {
+ // Don't sort map keys. It is not required by the spec, and C++ doesn't do it.
+ for _, key := range v.MapKeys() {
val := v.MapIndex(key)
- // The only illegal map entry values are nil message pointers.
- if val.Kind() == reflect.Ptr && val.IsNil() {
- return errors.New("proto: map has nil element")
- }
-
keycopy.Set(key)
valcopy.Set(val)
@@ -1123,7 +1170,7 @@ func (o *Buffer) enc_new_map(p *Properties, base structPointer) error {
}
func size_new_map(p *Properties, base structPointer) int {
- v := structPointer_Map(base, p.field, p.mtype).Elem() // map[K]V
+ v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
@@ -1198,12 +1245,28 @@ func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error {
return err
}
}
+ if len(o.buf) > maxMarshalSize {
+ return ErrTooLarge
+ }
+ }
+ }
+
+ // Do oneof fields.
+ if prop.oneofMarshaler != nil {
+ m := structPointer_Interface(base, prop.stype).(Message)
+ if err := prop.oneofMarshaler(m, o); err == ErrNil {
+ return errOneofHasNil
+ } else if err != nil {
+ return err
}
}
// Add unrecognized fields at the end.
if prop.unrecField.IsValid() {
v := *structPointer_Bytes(base, prop.unrecField)
+ if len(o.buf)+len(v) > maxMarshalSize {
+ return ErrTooLarge
+ }
if len(v) > 0 {
o.buf = append(o.buf, v...)
}
@@ -1226,6 +1289,12 @@ func size_struct(prop *StructProperties, base structPointer) (n int) {
n += len(v)
}
+ // Factor in any oneof fields.
+ if prop.oneofSizer != nil {
+ m := structPointer_Interface(base, prop.stype).(Message)
+ n += prop.oneofSizer(m)
+ }
+
return
}
diff --git a/vendor/github.com/golang/protobuf/proto/encode_test.go b/vendor/github.com/golang/protobuf/proto/encode_test.go
new file mode 100644
index 0000000..a720947
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/encode_test.go
@@ -0,0 +1,85 @@
+// 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.
+
+// +build go1.7
+
+package proto_test
+
+import (
+ "strconv"
+ "testing"
+
+ "github.com/golang/protobuf/proto"
+ tpb "github.com/golang/protobuf/proto/proto3_proto"
+ "github.com/golang/protobuf/ptypes"
+)
+
+var (
+ blackhole []byte
+)
+
+// BenchmarkAny creates increasingly large arbitrary Any messages. The type is always the
+// same.
+func BenchmarkAny(b *testing.B) {
+ data := make([]byte, 1<<20)
+ quantum := 1 << 10
+ for i := uint(0); i <= 10; i++ {
+ b.Run(strconv.Itoa(quantum<= len(o.buf) {
+ if o.index >= len(o.buf) {
break
}
}
@@ -333,10 +473,9 @@ func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
// GetExtensions returns a slice of the extensions present in pb that are also listed in es.
// The returned slice has the same length as es; missing extensions will appear as nil elements.
func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
- epb, ok := pb.(extendableProto)
+ epb, ok := extendable(pb)
if !ok {
- err = errors.New("proto: not an extendable proto")
- return
+ return nil, errors.New("proto: not an extendable proto")
}
extensions = make([]interface{}, len(es))
for i, e := range es {
@@ -351,9 +490,44 @@ func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, e
return
}
+// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order.
+// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing
+// just the Field field, which defines the extension's field number.
+func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) {
+ epb, ok := extendable(pb)
+ if !ok {
+ return nil, fmt.Errorf("proto: %T is not an extendable proto.Message", pb)
+ }
+ registeredExtensions := RegisteredExtensions(pb)
+
+ emap, mu := epb.extensionsRead()
+ if emap == nil {
+ return nil, nil
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ extensions := make([]*ExtensionDesc, 0, len(emap))
+ for extid, e := range emap {
+ desc := e.desc
+ if desc == nil {
+ desc = registeredExtensions[extid]
+ if desc == nil {
+ desc = &ExtensionDesc{Field: extid}
+ }
+ }
+
+ extensions = append(extensions, desc)
+ }
+ return extensions, nil
+}
+
// SetExtension sets the specified extension of pb to the specified value.
-func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{}) error {
- if err := checkExtensionTypes(pb, extension); err != nil {
+func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
+ epb, ok := extendable(pb)
+ if !ok {
+ return errors.New("proto: not an extendable proto")
+ }
+ if err := checkExtensionTypes(epb, extension); err != nil {
return err
}
typ := reflect.TypeOf(extension.ExtensionType)
@@ -369,10 +543,23 @@ func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{
return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
}
- pb.ExtensionMap()[extension.Field] = Extension{desc: extension, value: value}
+ extmap := epb.extensionsWrite()
+ extmap[extension.Field] = Extension{desc: extension, value: value}
return nil
}
+// ClearAllExtensions clears all extensions from pb.
+func ClearAllExtensions(pb Message) {
+ epb, ok := extendable(pb)
+ if !ok {
+ return
+ }
+ m := epb.extensionsWrite()
+ for k := range m {
+ delete(m, k)
+ }
+}
+
// A global registry of extensions.
// The generated code will register the generated descriptors by calling RegisterExtension.
diff --git a/vendor/github.com/golang/protobuf/proto/extensions_test.go b/vendor/github.com/golang/protobuf/proto/extensions_test.go
index 7255276..b6d9114 100644
--- a/vendor/github.com/golang/protobuf/proto/extensions_test.go
+++ b/vendor/github.com/golang/protobuf/proto/extensions_test.go
@@ -32,19 +32,22 @@
package proto_test
import (
+ "bytes"
"fmt"
"reflect"
+ "sort"
"testing"
"github.com/golang/protobuf/proto"
pb "github.com/golang/protobuf/proto/testdata"
+ "golang.org/x/sync/errgroup"
)
func TestGetExtensionsWithMissingExtensions(t *testing.T) {
msg := &pb.MyMessage{}
ext1 := &pb.Ext{}
if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil {
- t.Fatalf("Could not set ext1: %s", ext1)
+ t.Fatalf("Could not set ext1: %s", err)
}
exts, err := proto.GetExtensions(msg, []*proto.ExtensionDesc{
pb.E_Ext_More,
@@ -61,6 +64,58 @@ func TestGetExtensionsWithMissingExtensions(t *testing.T) {
}
}
+func TestExtensionDescsWithMissingExtensions(t *testing.T) {
+ msg := &pb.MyMessage{Count: proto.Int32(0)}
+ extdesc1 := pb.E_Ext_More
+ if descs, err := proto.ExtensionDescs(msg); len(descs) != 0 || err != nil {
+ t.Errorf("proto.ExtensionDescs: got %d descs, error %v; want 0, nil", len(descs), err)
+ }
+
+ ext1 := &pb.Ext{}
+ if err := proto.SetExtension(msg, extdesc1, ext1); err != nil {
+ t.Fatalf("Could not set ext1: %s", err)
+ }
+ extdesc2 := &proto.ExtensionDesc{
+ ExtendedType: (*pb.MyMessage)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 123456789,
+ Name: "a.b",
+ Tag: "varint,123456789,opt",
+ }
+ ext2 := proto.Bool(false)
+ if err := proto.SetExtension(msg, extdesc2, ext2); err != nil {
+ t.Fatalf("Could not set ext2: %s", err)
+ }
+
+ b, err := proto.Marshal(msg)
+ if err != nil {
+ t.Fatalf("Could not marshal msg: %v", err)
+ }
+ if err := proto.Unmarshal(b, msg); err != nil {
+ t.Fatalf("Could not unmarshal into msg: %v", err)
+ }
+
+ descs, err := proto.ExtensionDescs(msg)
+ if err != nil {
+ t.Fatalf("proto.ExtensionDescs: got error %v", err)
+ }
+ sortExtDescs(descs)
+ wantDescs := []*proto.ExtensionDesc{extdesc1, &proto.ExtensionDesc{Field: extdesc2.Field}}
+ if !reflect.DeepEqual(descs, wantDescs) {
+ t.Errorf("proto.ExtensionDescs(msg) sorted extension ids: got %+v, want %+v", descs, wantDescs)
+ }
+}
+
+type ExtensionDescSlice []*proto.ExtensionDesc
+
+func (s ExtensionDescSlice) Len() int { return len(s) }
+func (s ExtensionDescSlice) Less(i, j int) bool { return s[i].Field < s[j].Field }
+func (s ExtensionDescSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
+
+func sortExtDescs(s []*proto.ExtensionDesc) {
+ sort.Sort(ExtensionDescSlice(s))
+}
+
func TestGetExtensionStability(t *testing.T) {
check := func(m *pb.MyMessage) bool {
ext1, err := proto.GetExtension(m, pb.E_Ext_More)
@@ -290,3 +345,192 @@ func TestNilExtension(t *testing.T) {
// Note: if the behavior of Marshal is ever changed to ignore nil extensions, update
// this test to verify that E_Ext_Text is properly propagated through marshal->unmarshal.
}
+
+func TestMarshalUnmarshalRepeatedExtension(t *testing.T) {
+ // Add a repeated extension to the result.
+ tests := []struct {
+ name string
+ ext []*pb.ComplexExtension
+ }{
+ {
+ "two fields",
+ []*pb.ComplexExtension{
+ {First: proto.Int32(7)},
+ {Second: proto.Int32(11)},
+ },
+ },
+ {
+ "repeated field",
+ []*pb.ComplexExtension{
+ {Third: []int32{1000}},
+ {Third: []int32{2000}},
+ },
+ },
+ {
+ "two fields and repeated field",
+ []*pb.ComplexExtension{
+ {Third: []int32{1000}},
+ {First: proto.Int32(9)},
+ {Second: proto.Int32(21)},
+ {Third: []int32{2000}},
+ },
+ },
+ }
+ for _, test := range tests {
+ // Marshal message with a repeated extension.
+ msg1 := new(pb.OtherMessage)
+ err := proto.SetExtension(msg1, pb.E_RComplex, test.ext)
+ if err != nil {
+ t.Fatalf("[%s] Error setting extension: %v", test.name, err)
+ }
+ b, err := proto.Marshal(msg1)
+ if err != nil {
+ t.Fatalf("[%s] Error marshaling message: %v", test.name, err)
+ }
+
+ // Unmarshal and read the merged proto.
+ msg2 := new(pb.OtherMessage)
+ err = proto.Unmarshal(b, msg2)
+ if err != nil {
+ t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err)
+ }
+ e, err := proto.GetExtension(msg2, pb.E_RComplex)
+ if err != nil {
+ t.Fatalf("[%s] Error getting extension: %v", test.name, err)
+ }
+ ext := e.([]*pb.ComplexExtension)
+ if ext == nil {
+ t.Fatalf("[%s] Invalid extension", test.name)
+ }
+ if !reflect.DeepEqual(ext, test.ext) {
+ t.Errorf("[%s] Wrong value for ComplexExtension: got: %v want: %v\n", test.name, ext, test.ext)
+ }
+ }
+}
+
+func TestUnmarshalRepeatingNonRepeatedExtension(t *testing.T) {
+ // We may see multiple instances of the same extension in the wire
+ // format. For example, the proto compiler may encode custom options in
+ // this way. Here, we verify that we merge the extensions together.
+ tests := []struct {
+ name string
+ ext []*pb.ComplexExtension
+ }{
+ {
+ "two fields",
+ []*pb.ComplexExtension{
+ {First: proto.Int32(7)},
+ {Second: proto.Int32(11)},
+ },
+ },
+ {
+ "repeated field",
+ []*pb.ComplexExtension{
+ {Third: []int32{1000}},
+ {Third: []int32{2000}},
+ },
+ },
+ {
+ "two fields and repeated field",
+ []*pb.ComplexExtension{
+ {Third: []int32{1000}},
+ {First: proto.Int32(9)},
+ {Second: proto.Int32(21)},
+ {Third: []int32{2000}},
+ },
+ },
+ }
+ for _, test := range tests {
+ var buf bytes.Buffer
+ var want pb.ComplexExtension
+
+ // Generate a serialized representation of a repeated extension
+ // by catenating bytes together.
+ for i, e := range test.ext {
+ // Merge to create the wanted proto.
+ proto.Merge(&want, e)
+
+ // serialize the message
+ msg := new(pb.OtherMessage)
+ err := proto.SetExtension(msg, pb.E_Complex, e)
+ if err != nil {
+ t.Fatalf("[%s] Error setting extension %d: %v", test.name, i, err)
+ }
+ b, err := proto.Marshal(msg)
+ if err != nil {
+ t.Fatalf("[%s] Error marshaling message %d: %v", test.name, i, err)
+ }
+ buf.Write(b)
+ }
+
+ // Unmarshal and read the merged proto.
+ msg2 := new(pb.OtherMessage)
+ err := proto.Unmarshal(buf.Bytes(), msg2)
+ if err != nil {
+ t.Fatalf("[%s] Error unmarshaling message: %v", test.name, err)
+ }
+ e, err := proto.GetExtension(msg2, pb.E_Complex)
+ if err != nil {
+ t.Fatalf("[%s] Error getting extension: %v", test.name, err)
+ }
+ ext := e.(*pb.ComplexExtension)
+ if ext == nil {
+ t.Fatalf("[%s] Invalid extension", test.name)
+ }
+ if !reflect.DeepEqual(*ext, want) {
+ t.Errorf("[%s] Wrong value for ComplexExtension: got: %s want: %s\n", test.name, ext, want)
+ }
+ }
+}
+
+func TestClearAllExtensions(t *testing.T) {
+ // unregistered extension
+ desc := &proto.ExtensionDesc{
+ ExtendedType: (*pb.MyMessage)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 101010100,
+ Name: "emptyextension",
+ Tag: "varint,0,opt",
+ }
+ m := &pb.MyMessage{}
+ if proto.HasExtension(m, desc) {
+ t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m))
+ }
+ if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil {
+ t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err)
+ }
+ if !proto.HasExtension(m, desc) {
+ t.Errorf("proto.HasExtension(%s): got false, want true", proto.MarshalTextString(m))
+ }
+ proto.ClearAllExtensions(m)
+ if proto.HasExtension(m, desc) {
+ t.Errorf("proto.HasExtension(%s): got true, want false", proto.MarshalTextString(m))
+ }
+}
+
+func TestMarshalRace(t *testing.T) {
+ // unregistered extension
+ desc := &proto.ExtensionDesc{
+ ExtendedType: (*pb.MyMessage)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 101010100,
+ Name: "emptyextension",
+ Tag: "varint,0,opt",
+ }
+
+ m := &pb.MyMessage{Count: proto.Int32(4)}
+ if err := proto.SetExtension(m, desc, proto.Bool(true)); err != nil {
+ t.Errorf("proto.SetExtension(m, desc, true): got error %q, want nil", err)
+ }
+
+ var g errgroup.Group
+ for n := 3; n > 0; n-- {
+ g.Go(func() error {
+ _, err := proto.Marshal(m)
+ return err
+ })
+ }
+ if err := g.Wait(); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/golang/protobuf/proto/lib.go
index 89ca42a..1c22550 100644
--- a/vendor/github.com/golang/protobuf/proto/lib.go
+++ b/vendor/github.com/golang/protobuf/proto/lib.go
@@ -66,8 +66,15 @@ for a protocol buffer variable v:
that contain it (if any) followed by the CamelCased name of the
extension field itself. HasExtension, ClearExtension, GetExtension
and SetExtension are functions for manipulating extensions.
+ - Oneof field sets are given a single field in their message,
+ with distinguished wrapper types for each possible field value.
- Marshal and Unmarshal are functions to encode and decode the wire format.
+When the .proto file specifies `syntax="proto3"`, there are some differences:
+
+ - Non-repeated fields of non-message type are values instead of pointers.
+ - Enum types do not get an Enum method.
+
The simplest way to describe this is to see an example.
Given file test.proto, containing
@@ -82,6 +89,10 @@ Given file test.proto, containing
optional group OptionalGroup = 4 {
required string RequiredField = 5;
}
+ oneof union {
+ int32 number = 6;
+ string name = 7;
+ }
}
The resulting file, test.pb.go, is:
@@ -120,15 +131,40 @@ The resulting file, test.pb.go, is:
}
type Test struct {
- Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
- Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
- Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
- Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
- XXX_unrecognized []byte `json:"-"`
+ Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
+ Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
+ Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
+ Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
+ // Types that are valid to be assigned to Union:
+ // *Test_Number
+ // *Test_Name
+ Union isTest_Union `protobuf_oneof:"union"`
+ XXX_unrecognized []byte `json:"-"`
}
func (m *Test) Reset() { *m = Test{} }
func (m *Test) String() string { return proto.CompactTextString(m) }
- func (*Test) ProtoMessage() {}
+ func (*Test) ProtoMessage() {}
+
+ type isTest_Union interface {
+ isTest_Union()
+ }
+
+ type Test_Number struct {
+ Number int32 `protobuf:"varint,6,opt,name=number"`
+ }
+ type Test_Name struct {
+ Name string `protobuf:"bytes,7,opt,name=name"`
+ }
+
+ func (*Test_Number) isTest_Union() {}
+ func (*Test_Name) isTest_Union() {}
+
+ func (m *Test) GetUnion() isTest_Union {
+ if m != nil {
+ return m.Union
+ }
+ return nil
+ }
const Default_Test_Type int32 = 77
func (m *Test) GetLabel() string {
@@ -165,13 +201,27 @@ The resulting file, test.pb.go, is:
return ""
}
+ func (m *Test) GetNumber() int32 {
+ if x, ok := m.GetUnion().(*Test_Number); ok {
+ return x.Number
+ }
+ return 0
+ }
+
+ func (m *Test) GetName() string {
+ if x, ok := m.GetUnion().(*Test_Name); ok {
+ return x.Name
+ }
+ return ""
+ }
+
func init() {
proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
}
To create and play with a Test object:
-package main
+ package main
import (
"log"
@@ -184,9 +234,11 @@ package main
test := &pb.Test{
Label: proto.String("hello"),
Type: proto.Int32(17),
+ Reps: []int64{1, 2, 3},
Optionalgroup: &pb.Test_OptionalGroup{
RequiredField: proto.String("good bye"),
},
+ Union: &pb.Test_Name{"fred"},
}
data, err := proto.Marshal(test)
if err != nil {
@@ -201,6 +253,11 @@ package main
if test.GetLabel() != newTest.GetLabel() {
log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
}
+ // Use a type switch to determine which oneof was set.
+ switch u := test.Union.(type) {
+ case *pb.Test_Number: // u.Number contains the number.
+ case *pb.Test_Name: // u.Name contains the string.
+ }
// etc.
}
*/
@@ -211,6 +268,7 @@ import (
"fmt"
"log"
"reflect"
+ "sort"
"strconv"
"sync"
)
@@ -249,7 +307,7 @@ func GetStats() Stats { return stats }
// temporary Buffer and are fine for most applications.
type Buffer struct {
buf []byte // encode/decode byte stream
- index int // write point
+ index int // read point
// pools of basic types to amortize allocation.
bools []bool
@@ -459,7 +517,6 @@ out:
break out
}
fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
- break
case WireVarint:
u, err = p.DecodeVarint()
@@ -470,19 +527,11 @@ out:
fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
case WireStartGroup:
- if err != nil {
- fmt.Printf("%3d: t=%3d start err %v\n", index, tag, err)
- break out
- }
fmt.Printf("%3d: t=%3d start\n", index, tag)
depth++
case WireEndGroup:
depth--
- if err != nil {
- fmt.Printf("%3d: t=%3d end err %v\n", index, tag, err)
- break out
- }
fmt.Printf("%3d: t=%3d end\n", index, tag)
}
}
@@ -787,10 +836,62 @@ func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMes
// If this turns out to be inefficient we can always consider other options,
// such as doing a Schwartzian transform.
-type mapKeys []reflect.Value
+func mapKeys(vs []reflect.Value) sort.Interface {
+ s := mapKeySorter{
+ vs: vs,
+ // default Less function: textual comparison
+ less: func(a, b reflect.Value) bool {
+ return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface())
+ },
+ }
-func (s mapKeys) Len() int { return len(s) }
-func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
-func (s mapKeys) Less(i, j int) bool {
- return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface())
+ // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps;
+ // numeric keys are sorted numerically.
+ if len(vs) == 0 {
+ return s
+ }
+ switch vs[0].Kind() {
+ case reflect.Int32, reflect.Int64:
+ s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
+ case reflect.Uint32, reflect.Uint64:
+ s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
+ }
+
+ return s
}
+
+type mapKeySorter struct {
+ vs []reflect.Value
+ less func(a, b reflect.Value) bool
+}
+
+func (s mapKeySorter) Len() int { return len(s.vs) }
+func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
+func (s mapKeySorter) Less(i, j int) bool {
+ return s.less(s.vs[i], s.vs[j])
+}
+
+// isProto3Zero reports whether v is a zero proto3 value.
+func isProto3Zero(v reflect.Value) bool {
+ switch v.Kind() {
+ case reflect.Bool:
+ return !v.Bool()
+ case reflect.Int32, reflect.Int64:
+ return v.Int() == 0
+ case reflect.Uint32, reflect.Uint64:
+ return v.Uint() == 0
+ case reflect.Float32, reflect.Float64:
+ return v.Float() == 0
+ case reflect.String:
+ return v.String() == ""
+ }
+ return false
+}
+
+// ProtoPackageIsVersion2 is referenced from generated protocol buffer files
+// to assert that that code is compatible with this version of the proto package.
+const ProtoPackageIsVersion2 = true
+
+// ProtoPackageIsVersion1 is referenced from generated protocol buffer files
+// to assert that that code is compatible with this version of the proto package.
+const ProtoPackageIsVersion1 = true
diff --git a/vendor/github.com/golang/protobuf/proto/map_test.go b/vendor/github.com/golang/protobuf/proto/map_test.go
new file mode 100644
index 0000000..313e879
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/map_test.go
@@ -0,0 +1,46 @@
+package proto_test
+
+import (
+ "fmt"
+ "testing"
+
+ "github.com/golang/protobuf/proto"
+ ppb "github.com/golang/protobuf/proto/proto3_proto"
+)
+
+func marshalled() []byte {
+ m := &ppb.IntMaps{}
+ for i := 0; i < 1000; i++ {
+ m.Maps = append(m.Maps, &ppb.IntMap{
+ Rtt: map[int32]int32{1: 2},
+ })
+ }
+ b, err := proto.Marshal(m)
+ if err != nil {
+ panic(fmt.Sprintf("Can't marshal %+v: %v", m, err))
+ }
+ return b
+}
+
+func BenchmarkConcurrentMapUnmarshal(b *testing.B) {
+ in := marshalled()
+ b.RunParallel(func(pb *testing.PB) {
+ for pb.Next() {
+ var out ppb.IntMaps
+ if err := proto.Unmarshal(in, &out); err != nil {
+ b.Errorf("Can't unmarshal ppb.IntMaps: %v", err)
+ }
+ }
+ })
+}
+
+func BenchmarkSequentialMapUnmarshal(b *testing.B) {
+ in := marshalled()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ var out ppb.IntMaps
+ if err := proto.Unmarshal(in, &out); err != nil {
+ b.Errorf("Can't unmarshal ppb.IntMaps: %v", err)
+ }
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/proto/message_set.go b/vendor/github.com/golang/protobuf/proto/message_set.go
index 9d912bc..fd982de 100644
--- a/vendor/github.com/golang/protobuf/proto/message_set.go
+++ b/vendor/github.com/golang/protobuf/proto/message_set.go
@@ -44,11 +44,11 @@ import (
"sort"
)
-// ErrNoMessageTypeId occurs when a protocol buffer does not have a message type ID.
+// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID.
// A message type ID is required for storing a protocol buffer in a message set.
-var ErrNoMessageTypeId = errors.New("proto does not have a message type ID")
+var errNoMessageTypeID = errors.New("proto does not have a message type ID")
-// The first two types (_MessageSet_Item and MessageSet)
+// The first two types (_MessageSet_Item and messageSet)
// model what the protocol compiler produces for the following protocol message:
// message MessageSet {
// repeated group Item = 1 {
@@ -58,27 +58,20 @@ var ErrNoMessageTypeId = errors.New("proto does not have a message type ID")
// }
// That is the MessageSet wire format. We can't use a proto to generate these
// because that would introduce a circular dependency between it and this package.
-//
-// When a proto1 proto has a field that looks like:
-// optional message info = 3;
-// the protocol compiler produces a field in the generated struct that looks like:
-// Info *_proto_.MessageSet `protobuf:"bytes,3,opt,name=info"`
-// The package is automatically inserted so there is no need for that proto file to
-// import this package.
type _MessageSet_Item struct {
TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
Message []byte `protobuf:"bytes,3,req,name=message"`
}
-type MessageSet struct {
+type messageSet struct {
Item []*_MessageSet_Item `protobuf:"group,1,rep"`
XXX_unrecognized []byte
// TODO: caching?
}
-// Make sure MessageSet is a Message.
-var _ Message = (*MessageSet)(nil)
+// Make sure messageSet is a Message.
+var _ Message = (*messageSet)(nil)
// messageTypeIder is an interface satisfied by a protocol buffer type
// that may be stored in a MessageSet.
@@ -86,7 +79,7 @@ type messageTypeIder interface {
MessageTypeId() int32
}
-func (ms *MessageSet) find(pb Message) *_MessageSet_Item {
+func (ms *messageSet) find(pb Message) *_MessageSet_Item {
mti, ok := pb.(messageTypeIder)
if !ok {
return nil
@@ -100,24 +93,24 @@ func (ms *MessageSet) find(pb Message) *_MessageSet_Item {
return nil
}
-func (ms *MessageSet) Has(pb Message) bool {
+func (ms *messageSet) Has(pb Message) bool {
if ms.find(pb) != nil {
return true
}
return false
}
-func (ms *MessageSet) Unmarshal(pb Message) error {
+func (ms *messageSet) Unmarshal(pb Message) error {
if item := ms.find(pb); item != nil {
return Unmarshal(item.Message, pb)
}
if _, ok := pb.(messageTypeIder); !ok {
- return ErrNoMessageTypeId
+ return errNoMessageTypeID
}
return nil // TODO: return error instead?
}
-func (ms *MessageSet) Marshal(pb Message) error {
+func (ms *messageSet) Marshal(pb Message) error {
msg, err := Marshal(pb)
if err != nil {
return err
@@ -130,7 +123,7 @@ func (ms *MessageSet) Marshal(pb Message) error {
mti, ok := pb.(messageTypeIder)
if !ok {
- return ErrNoMessageTypeId
+ return errNoMessageTypeID
}
mtid := mti.MessageTypeId()
@@ -141,9 +134,9 @@ func (ms *MessageSet) Marshal(pb Message) error {
return nil
}
-func (ms *MessageSet) Reset() { *ms = MessageSet{} }
-func (ms *MessageSet) String() string { return CompactTextString(ms) }
-func (*MessageSet) ProtoMessage() {}
+func (ms *messageSet) Reset() { *ms = messageSet{} }
+func (ms *messageSet) String() string { return CompactTextString(ms) }
+func (*messageSet) ProtoMessage() {}
// Support for the message_set_wire_format message option.
@@ -156,9 +149,21 @@ func skipVarint(buf []byte) []byte {
// MarshalMessageSet encodes the extension map represented by m in the message set wire format.
// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option.
-func MarshalMessageSet(m map[int32]Extension) ([]byte, error) {
- if err := encodeExtensionMap(m); err != nil {
- return nil, err
+func MarshalMessageSet(exts interface{}) ([]byte, error) {
+ var m map[int32]Extension
+ switch exts := exts.(type) {
+ case *XXX_InternalExtensions:
+ if err := encodeExtensions(exts); err != nil {
+ return nil, err
+ }
+ m, _ = exts.extensionsRead()
+ case map[int32]Extension:
+ if err := encodeExtensionsMap(exts); err != nil {
+ return nil, err
+ }
+ m = exts
+ default:
+ return nil, errors.New("proto: not an extension map")
}
// Sort extension IDs to provide a deterministic encoding.
@@ -169,7 +174,7 @@ func MarshalMessageSet(m map[int32]Extension) ([]byte, error) {
}
sort.Ints(ids)
- ms := &MessageSet{Item: make([]*_MessageSet_Item, 0, len(m))}
+ ms := &messageSet{Item: make([]*_MessageSet_Item, 0, len(m))}
for _, id := range ids {
e := m[int32(id)]
// Remove the wire type and field number varint, as well as the length varint.
@@ -185,8 +190,18 @@ func MarshalMessageSet(m map[int32]Extension) ([]byte, error) {
// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
-func UnmarshalMessageSet(buf []byte, m map[int32]Extension) error {
- ms := new(MessageSet)
+func UnmarshalMessageSet(buf []byte, exts interface{}) error {
+ var m map[int32]Extension
+ switch exts := exts.(type) {
+ case *XXX_InternalExtensions:
+ m = exts.extensionsWrite()
+ case map[int32]Extension:
+ m = exts
+ default:
+ return errors.New("proto: not an extension map")
+ }
+
+ ms := new(messageSet)
if err := Unmarshal(buf, ms); err != nil {
return err
}
@@ -216,7 +231,16 @@ func UnmarshalMessageSet(buf []byte, m map[int32]Extension) error {
// MarshalMessageSetJSON encodes the extension map represented by m in JSON format.
// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
-func MarshalMessageSetJSON(m map[int32]Extension) ([]byte, error) {
+func MarshalMessageSetJSON(exts interface{}) ([]byte, error) {
+ var m map[int32]Extension
+ switch exts := exts.(type) {
+ case *XXX_InternalExtensions:
+ m, _ = exts.extensionsRead()
+ case map[int32]Extension:
+ m = exts
+ default:
+ return nil, errors.New("proto: not an extension map")
+ }
var b bytes.Buffer
b.WriteByte('{')
@@ -259,7 +283,7 @@ func MarshalMessageSetJSON(m map[int32]Extension) ([]byte, error) {
// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format.
// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
-func UnmarshalMessageSetJSON(buf []byte, m map[int32]Extension) error {
+func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error {
// Common-case fast path.
if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) {
return nil
diff --git a/vendor/github.com/golang/protobuf/proto/message_set_test.go b/vendor/github.com/golang/protobuf/proto/message_set_test.go
index 7c29bcc..353a3ea 100644
--- a/vendor/github.com/golang/protobuf/proto/message_set_test.go
+++ b/vendor/github.com/golang/protobuf/proto/message_set_test.go
@@ -38,7 +38,7 @@ import (
func TestUnmarshalMessageSetWithDuplicate(t *testing.T) {
// Check that a repeated message set entry will be concatenated.
- in := &MessageSet{
+ in := &messageSet{
Item: []*_MessageSet_Item{
{TypeId: Int32(12345), Message: []byte("hoo")},
{TypeId: Int32(12345), Message: []byte("hah")},
@@ -50,13 +50,13 @@ func TestUnmarshalMessageSetWithDuplicate(t *testing.T) {
}
t.Logf("Marshaled bytes: %q", b)
- m := make(map[int32]Extension)
- if err := UnmarshalMessageSet(b, m); err != nil {
+ var extensions XXX_InternalExtensions
+ if err := UnmarshalMessageSet(b, &extensions); err != nil {
t.Fatalf("UnmarshalMessageSet: %v", err)
}
- ext, ok := m[12345]
+ ext, ok := extensions.p.extensionMap[12345]
if !ok {
- t.Fatalf("Didn't retrieve extension 12345; map is %v", m)
+ t.Fatalf("Didn't retrieve extension 12345; map is %v", extensions.p.extensionMap)
}
// Skip wire type/field number and length varints.
got := skipVarint(skipVarint(ext.enc))
diff --git a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
index c68b125..fb512e2 100644
--- a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
+++ b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
@@ -29,7 +29,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-// +build appengine
+// +build appengine js
// This file contains an implementation of proto field accesses using package reflect.
// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can
@@ -139,13 +139,18 @@ func structPointer_StringSlice(p structPointer, f field) *[]string {
return structPointer_ifield(p, f).(*[]string)
}
+// Extensions returns the address of an extension map field in the struct.
+func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions {
+ return structPointer_ifield(p, f).(*XXX_InternalExtensions)
+}
+
// ExtMap returns the address of an extension map field in the struct.
func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
return structPointer_ifield(p, f).(*map[int32]Extension)
}
-// Map returns the reflect.Value for the address of a map field in the struct.
-func structPointer_Map(p structPointer, f field, typ reflect.Type) reflect.Value {
+// NewAt returns the reflect.Value for a pointer to a field in the struct.
+func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value {
return structPointer_field(p, f).Addr()
}
diff --git a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
index 48bc0fa..6b5567d 100644
--- a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
+++ b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
@@ -29,7 +29,7 @@
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-// +build !appengine
+// +build !appengine,!js
// This file contains the implementation of the proto field accesses using package unsafe.
@@ -126,12 +126,16 @@ func structPointer_StringSlice(p structPointer, f field) *[]string {
}
// ExtMap returns the address of an extension map field in the struct.
+func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions {
+ return (*XXX_InternalExtensions)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f)))
}
-// Map returns the reflect.Value for the address of a map field in the struct.
-func structPointer_Map(p structPointer, f field, typ reflect.Type) reflect.Value {
+// NewAt returns the reflect.Value for a pointer to a field in the struct.
+func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value {
return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f)))
}
diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go
index d74844a..ec2289c 100644
--- a/vendor/github.com/golang/protobuf/proto/properties.go
+++ b/vendor/github.com/golang/protobuf/proto/properties.go
@@ -37,6 +37,7 @@ package proto
import (
"fmt"
+ "log"
"os"
"reflect"
"sort"
@@ -84,6 +85,15 @@ type decoder func(p *Buffer, prop *Properties, base structPointer) error
// A valueDecoder decodes a single integer in a particular encoding.
type valueDecoder func(o *Buffer) (x uint64, err error)
+// A oneofMarshaler does the marshaling for all oneof fields in a message.
+type oneofMarshaler func(Message, *Buffer) error
+
+// A oneofUnmarshaler does the unmarshaling for a oneof field in a message.
+type oneofUnmarshaler func(Message, int, int, *Buffer) (bool, error)
+
+// A oneofSizer does the sizing for all oneof fields in a message.
+type oneofSizer func(Message) int
+
// tagMap is an optimization over map[int]int for typical protocol buffer
// use-cases. Encoded protocol buffers are often in tag order with small tag
// numbers.
@@ -132,6 +142,22 @@ type StructProperties struct {
order []int // list of struct field numbers in tag order
unrecField field // field id of the XXX_unrecognized []byte field
extendable bool // is this an extendable proto
+
+ oneofMarshaler oneofMarshaler
+ oneofUnmarshaler oneofUnmarshaler
+ oneofSizer oneofSizer
+ stype reflect.Type
+
+ // OneofTypes contains information about the oneof fields in this message.
+ // It is keyed by the original name of a field.
+ OneofTypes map[string]*OneofProperties
+}
+
+// OneofProperties represents information about a specific field in a oneof.
+type OneofProperties struct {
+ Type reflect.Type // pointer to generated struct type for this oneof field
+ Field int // struct field number of the containing oneof in the message
+ Prop *Properties
}
// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
@@ -147,6 +173,7 @@ func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order
type Properties struct {
Name string // name of the field, for error messages
OrigName string // original name before protocol compiler (always set)
+ JSONName string // name to use for JSON; determined by protoc
Wire string
WireType int
Tag int
@@ -156,6 +183,7 @@ type Properties struct {
Packed bool // relevant for repeated primitives only
Enum string // set for enum types only
proto3 bool // whether this is known to be a proto3 field; set for []byte only
+ oneof bool // whether this is a oneof field
Default string // default value
HasDefault bool // whether an explicit default was provided
@@ -202,12 +230,16 @@ func (p *Properties) String() string {
if p.Packed {
s += ",packed"
}
- if p.OrigName != p.Name {
- s += ",name=" + p.OrigName
+ s += ",name=" + p.OrigName
+ if p.JSONName != p.OrigName {
+ s += ",json=" + p.JSONName
}
if p.proto3 {
s += ",proto3"
}
+ if p.oneof {
+ s += ",oneof"
+ }
if len(p.Enum) > 0 {
s += ",enum=" + p.Enum
}
@@ -280,10 +312,14 @@ func (p *Properties) Parse(s string) {
p.Packed = true
case strings.HasPrefix(f, "name="):
p.OrigName = f[5:]
+ case strings.HasPrefix(f, "json="):
+ p.JSONName = f[5:]
case strings.HasPrefix(f, "enum="):
p.Enum = f[5:]
case f == "proto3":
p.proto3 = true
+ case f == "oneof":
+ p.oneof = true
case strings.HasPrefix(f, "def="):
p.HasDefault = true
p.Default = f[4:] // rest of string
@@ -437,17 +473,13 @@ func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lock
p.dec = (*Buffer).dec_slice_int64
p.packedDec = (*Buffer).dec_slice_packed_int64
case reflect.Uint8:
- p.enc = (*Buffer).enc_slice_byte
p.dec = (*Buffer).dec_slice_byte
- p.size = size_slice_byte
- // This is a []byte, which is either a bytes field,
- // or the value of a map field. In the latter case,
- // we always encode an empty []byte, so we should not
- // use the proto3 enc/size funcs.
- // f == nil iff this is the key/value of a map field.
- if p.proto3 && f != nil {
+ if p.proto3 {
p.enc = (*Buffer).enc_proto3_slice_byte
p.size = size_proto3_slice_byte
+ } else {
+ p.enc = (*Buffer).enc_slice_byte
+ p.size = size_slice_byte
}
case reflect.Float32, reflect.Float64:
switch t2.Bits() {
@@ -646,7 +678,8 @@ func getPropertiesLocked(t reflect.Type) *StructProperties {
propertiesMap[t] = prop
// build properties
- prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType)
+ prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) ||
+ reflect.PtrTo(t).Implements(extendableProtoV1Type)
prop.unrecField = invalidField
prop.Prop = make([]*Properties, t.NumField())
prop.order = make([]int, t.NumField())
@@ -657,14 +690,22 @@ func getPropertiesLocked(t reflect.Type) *StructProperties {
name := f.Name
p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
- if f.Name == "XXX_extensions" { // special case
+ if f.Name == "XXX_InternalExtensions" { // special case
+ p.enc = (*Buffer).enc_exts
+ p.dec = nil // not needed
+ p.size = size_exts
+ } else if f.Name == "XXX_extensions" { // special case
p.enc = (*Buffer).enc_map
p.dec = nil // not needed
p.size = size_map
- }
- if f.Name == "XXX_unrecognized" { // special case
+ } else if f.Name == "XXX_unrecognized" { // special case
prop.unrecField = toField(&f)
}
+ oneof := f.Tag.Get("protobuf_oneof") // special case
+ if oneof != "" {
+ // Oneof fields don't use the traditional protobuf tag.
+ p.OrigName = oneof
+ }
prop.Prop[i] = p
prop.order[i] = i
if debug {
@@ -674,7 +715,7 @@ func getPropertiesLocked(t reflect.Type) *StructProperties {
}
print("\n")
}
- if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") {
+ if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && oneof == "" {
fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]")
}
}
@@ -682,6 +723,41 @@ func getPropertiesLocked(t reflect.Type) *StructProperties {
// Re-order prop.order.
sort.Sort(prop)
+ type oneofMessage interface {
+ XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
+ }
+ if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok {
+ var oots []interface{}
+ prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs()
+ prop.stype = t
+
+ // Interpret oneof metadata.
+ prop.OneofTypes = make(map[string]*OneofProperties)
+ for _, oot := range oots {
+ oop := &OneofProperties{
+ Type: reflect.ValueOf(oot).Type(), // *T
+ Prop: new(Properties),
+ }
+ sft := oop.Type.Elem().Field(0)
+ oop.Prop.Name = sft.Name
+ oop.Prop.Parse(sft.Tag.Get("protobuf"))
+ // There will be exactly one interface field that
+ // this new value is assignable to.
+ for i := 0; i < t.NumField(); i++ {
+ f := t.Field(i)
+ if f.Type.Kind() != reflect.Interface {
+ continue
+ }
+ if !oop.Type.AssignableTo(f.Type) {
+ continue
+ }
+ oop.Field = i
+ break
+ }
+ prop.OneofTypes[oop.Prop.OrigName] = oop
+ }
+ }
+
// build required counts
// build tags
reqCount := 0
@@ -740,3 +816,57 @@ func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[
}
enumValueMaps[typeName] = valueMap
}
+
+// EnumValueMap returns the mapping from names to integers of the
+// enum type enumType, or a nil if not found.
+func EnumValueMap(enumType string) map[string]int32 {
+ return enumValueMaps[enumType]
+}
+
+// A registry of all linked message types.
+// The string is a fully-qualified proto name ("pkg.Message").
+var (
+ protoTypes = make(map[string]reflect.Type)
+ revProtoTypes = make(map[reflect.Type]string)
+)
+
+// RegisterType is called from generated code and maps from the fully qualified
+// proto name to the type (pointer to struct) of the protocol buffer.
+func RegisterType(x Message, name string) {
+ if _, ok := protoTypes[name]; ok {
+ // TODO: Some day, make this a panic.
+ log.Printf("proto: duplicate proto type registered: %s", name)
+ return
+ }
+ t := reflect.TypeOf(x)
+ protoTypes[name] = t
+ revProtoTypes[t] = name
+}
+
+// MessageName returns the fully-qualified proto name for the given message type.
+func MessageName(x Message) string {
+ type xname interface {
+ XXX_MessageName() string
+ }
+ if m, ok := x.(xname); ok {
+ return m.XXX_MessageName()
+ }
+ return revProtoTypes[reflect.TypeOf(x)]
+}
+
+// MessageType returns the message type (pointer to struct) for a named message.
+func MessageType(name string) reflect.Type { return protoTypes[name] }
+
+// A registry of all linked proto files.
+var (
+ protoFiles = make(map[string][]byte) // file name => fileDescriptor
+)
+
+// RegisterFile is called from generated code and maps from the
+// full file name of a .proto file to its compressed FileDescriptorProto.
+func RegisterFile(filename string, fileDescriptor []byte) {
+ protoFiles[filename] = fileDescriptor
+}
+
+// FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
+func FileDescriptor(filename string) []byte { return protoFiles[filename] }
diff --git a/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go b/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go
index 37c7782..cc4d048 100644
--- a/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go
+++ b/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go
@@ -12,14 +12,27 @@ It has these top-level messages:
Message
Nested
MessageWithMap
+ IntMap
+ IntMaps
*/
package proto3_proto
import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import google_protobuf "github.com/golang/protobuf/ptypes/any"
import testdata "github.com/golang/protobuf/proto/testdata"
// 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
type Message_Humour int32
@@ -46,25 +59,96 @@ var Message_Humour_value = map[string]int32{
func (x Message_Humour) String() string {
return proto.EnumName(Message_Humour_name, int32(x))
}
+func (Message_Humour) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} }
type Message struct {
Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
Hilarity Message_Humour `protobuf:"varint,2,opt,name=hilarity,enum=proto3_proto.Message_Humour" json:"hilarity,omitempty"`
- HeightInCm uint32 `protobuf:"varint,3,opt,name=height_in_cm" json:"height_in_cm,omitempty"`
+ HeightInCm uint32 `protobuf:"varint,3,opt,name=height_in_cm,json=heightInCm" json:"height_in_cm,omitempty"`
Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"`
- ResultCount int64 `protobuf:"varint,7,opt,name=result_count" json:"result_count,omitempty"`
- TrueScotsman bool `protobuf:"varint,8,opt,name=true_scotsman" json:"true_scotsman,omitempty"`
+ ResultCount int64 `protobuf:"varint,7,opt,name=result_count,json=resultCount" json:"result_count,omitempty"`
+ TrueScotsman bool `protobuf:"varint,8,opt,name=true_scotsman,json=trueScotsman" json:"true_scotsman,omitempty"`
Score float32 `protobuf:"fixed32,9,opt,name=score" json:"score,omitempty"`
- Key []uint64 `protobuf:"varint,5,rep,name=key" json:"key,omitempty"`
+ Key []uint64 `protobuf:"varint,5,rep,packed,name=key" json:"key,omitempty"`
+ ShortKey []int32 `protobuf:"varint,19,rep,packed,name=short_key,json=shortKey" json:"short_key,omitempty"`
Nested *Nested `protobuf:"bytes,6,opt,name=nested" json:"nested,omitempty"`
+ RFunny []Message_Humour `protobuf:"varint,16,rep,packed,name=r_funny,json=rFunny,enum=proto3_proto.Message_Humour" json:"r_funny,omitempty"`
Terrain map[string]*Nested `protobuf:"bytes,10,rep,name=terrain" json:"terrain,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- Proto2Field *testdata.SubDefaults `protobuf:"bytes,11,opt,name=proto2_field" json:"proto2_field,omitempty"`
- Proto2Value map[string]*testdata.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Proto2Field *testdata.SubDefaults `protobuf:"bytes,11,opt,name=proto2_field,json=proto2Field" json:"proto2_field,omitempty"`
+ Proto2Value map[string]*testdata.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value,json=proto2Value" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Anything *google_protobuf.Any `protobuf:"bytes,14,opt,name=anything" json:"anything,omitempty"`
+ ManyThings []*google_protobuf.Any `protobuf:"bytes,15,rep,name=many_things,json=manyThings" json:"many_things,omitempty"`
+ Submessage *Message `protobuf:"bytes,17,opt,name=submessage" json:"submessage,omitempty"`
+ Children []*Message `protobuf:"bytes,18,rep,name=children" json:"children,omitempty"`
}
-func (m *Message) Reset() { *m = Message{} }
-func (m *Message) String() string { return proto.CompactTextString(m) }
-func (*Message) ProtoMessage() {}
+func (m *Message) Reset() { *m = Message{} }
+func (m *Message) String() string { return proto.CompactTextString(m) }
+func (*Message) ProtoMessage() {}
+func (*Message) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+func (m *Message) GetName() string {
+ if m != nil {
+ return m.Name
+ }
+ return ""
+}
+
+func (m *Message) GetHilarity() Message_Humour {
+ if m != nil {
+ return m.Hilarity
+ }
+ return Message_UNKNOWN
+}
+
+func (m *Message) GetHeightInCm() uint32 {
+ if m != nil {
+ return m.HeightInCm
+ }
+ return 0
+}
+
+func (m *Message) GetData() []byte {
+ if m != nil {
+ return m.Data
+ }
+ return nil
+}
+
+func (m *Message) GetResultCount() int64 {
+ if m != nil {
+ return m.ResultCount
+ }
+ return 0
+}
+
+func (m *Message) GetTrueScotsman() bool {
+ if m != nil {
+ return m.TrueScotsman
+ }
+ return false
+}
+
+func (m *Message) GetScore() float32 {
+ if m != nil {
+ return m.Score
+ }
+ return 0
+}
+
+func (m *Message) GetKey() []uint64 {
+ if m != nil {
+ return m.Key
+ }
+ return nil
+}
+
+func (m *Message) GetShortKey() []int32 {
+ if m != nil {
+ return m.ShortKey
+ }
+ return nil
+}
func (m *Message) GetNested() *Nested {
if m != nil {
@@ -73,6 +157,13 @@ func (m *Message) GetNested() *Nested {
return nil
}
+func (m *Message) GetRFunny() []Message_Humour {
+ if m != nil {
+ return m.RFunny
+ }
+ return nil
+}
+
func (m *Message) GetTerrain() map[string]*Nested {
if m != nil {
return m.Terrain
@@ -94,21 +185,66 @@ func (m *Message) GetProto2Value() map[string]*testdata.SubDefaults {
return nil
}
+func (m *Message) GetAnything() *google_protobuf.Any {
+ if m != nil {
+ return m.Anything
+ }
+ return nil
+}
+
+func (m *Message) GetManyThings() []*google_protobuf.Any {
+ if m != nil {
+ return m.ManyThings
+ }
+ return nil
+}
+
+func (m *Message) GetSubmessage() *Message {
+ if m != nil {
+ return m.Submessage
+ }
+ return nil
+}
+
+func (m *Message) GetChildren() []*Message {
+ if m != nil {
+ return m.Children
+ }
+ return nil
+}
+
type Nested struct {
Bunny string `protobuf:"bytes,1,opt,name=bunny" json:"bunny,omitempty"`
+ Cute bool `protobuf:"varint,2,opt,name=cute" json:"cute,omitempty"`
}
-func (m *Nested) Reset() { *m = Nested{} }
-func (m *Nested) String() string { return proto.CompactTextString(m) }
-func (*Nested) ProtoMessage() {}
+func (m *Nested) Reset() { *m = Nested{} }
+func (m *Nested) String() string { return proto.CompactTextString(m) }
+func (*Nested) ProtoMessage() {}
+func (*Nested) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+func (m *Nested) GetBunny() string {
+ if m != nil {
+ return m.Bunny
+ }
+ return ""
+}
+
+func (m *Nested) GetCute() bool {
+ if m != nil {
+ return m.Cute
+ }
+ return false
+}
type MessageWithMap struct {
- ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"`
+ ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"`
}
-func (m *MessageWithMap) Reset() { *m = MessageWithMap{} }
-func (m *MessageWithMap) String() string { return proto.CompactTextString(m) }
-func (*MessageWithMap) ProtoMessage() {}
+func (m *MessageWithMap) Reset() { *m = MessageWithMap{} }
+func (m *MessageWithMap) String() string { return proto.CompactTextString(m) }
+func (*MessageWithMap) ProtoMessage() {}
+func (*MessageWithMap) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
func (m *MessageWithMap) GetByteMapping() map[bool][]byte {
if m != nil {
@@ -117,6 +253,95 @@ func (m *MessageWithMap) GetByteMapping() map[bool][]byte {
return nil
}
+type IntMap struct {
+ Rtt map[int32]int32 `protobuf:"bytes,1,rep,name=rtt" json:"rtt,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"varint,2,opt,name=value"`
+}
+
+func (m *IntMap) Reset() { *m = IntMap{} }
+func (m *IntMap) String() string { return proto.CompactTextString(m) }
+func (*IntMap) ProtoMessage() {}
+func (*IntMap) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
+
+func (m *IntMap) GetRtt() map[int32]int32 {
+ if m != nil {
+ return m.Rtt
+ }
+ return nil
+}
+
+type IntMaps struct {
+ Maps []*IntMap `protobuf:"bytes,1,rep,name=maps" json:"maps,omitempty"`
+}
+
+func (m *IntMaps) Reset() { *m = IntMaps{} }
+func (m *IntMaps) String() string { return proto.CompactTextString(m) }
+func (*IntMaps) ProtoMessage() {}
+func (*IntMaps) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
+
+func (m *IntMaps) GetMaps() []*IntMap {
+ if m != nil {
+ return m.Maps
+ }
+ return nil
+}
+
func init() {
+ proto.RegisterType((*Message)(nil), "proto3_proto.Message")
+ proto.RegisterType((*Nested)(nil), "proto3_proto.Nested")
+ proto.RegisterType((*MessageWithMap)(nil), "proto3_proto.MessageWithMap")
+ proto.RegisterType((*IntMap)(nil), "proto3_proto.IntMap")
+ proto.RegisterType((*IntMaps)(nil), "proto3_proto.IntMaps")
proto.RegisterEnum("proto3_proto.Message_Humour", Message_Humour_name, Message_Humour_value)
}
+
+func init() { proto.RegisterFile("proto3_proto/proto3.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 733 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x84, 0x53, 0x6d, 0x6f, 0xf3, 0x34,
+ 0x14, 0x25, 0x4d, 0x5f, 0xd2, 0x9b, 0x74, 0x0b, 0x5e, 0x91, 0xbc, 0x02, 0x52, 0x28, 0x12, 0x8a,
+ 0x78, 0x49, 0xa1, 0xd3, 0xd0, 0x84, 0x10, 0x68, 0x1b, 0x9b, 0xa8, 0xd6, 0x95, 0xca, 0xdd, 0x98,
+ 0xf8, 0x14, 0xa5, 0xad, 0xdb, 0x46, 0x34, 0x4e, 0x49, 0x1c, 0xa4, 0xfc, 0x1d, 0xfe, 0x28, 0x8f,
+ 0x6c, 0xa7, 0x5d, 0x36, 0x65, 0xcf, 0xf3, 0x29, 0xf6, 0xf1, 0xb9, 0xf7, 0x9c, 0x1c, 0x5f, 0xc3,
+ 0xe9, 0x2e, 0x89, 0x79, 0x7c, 0xe6, 0xcb, 0xcf, 0x40, 0x6d, 0x3c, 0xf9, 0x41, 0x56, 0xf9, 0xa8,
+ 0x77, 0xba, 0x8e, 0xe3, 0xf5, 0x96, 0x2a, 0xca, 0x3c, 0x5b, 0x0d, 0x02, 0x96, 0x2b, 0x62, 0xef,
+ 0x84, 0xd3, 0x94, 0x2f, 0x03, 0x1e, 0x0c, 0xc4, 0x42, 0x81, 0xfd, 0xff, 0x5b, 0xd0, 0xba, 0xa7,
+ 0x69, 0x1a, 0xac, 0x29, 0x42, 0x50, 0x67, 0x41, 0x44, 0xb1, 0xe6, 0x68, 0x6e, 0x9b, 0xc8, 0x35,
+ 0xba, 0x00, 0x63, 0x13, 0x6e, 0x83, 0x24, 0xe4, 0x39, 0xae, 0x39, 0x9a, 0x7b, 0x34, 0xfc, 0xcc,
+ 0x2b, 0x0b, 0x7a, 0x45, 0xb1, 0xf7, 0x7b, 0x16, 0xc5, 0x59, 0x42, 0x0e, 0x6c, 0xe4, 0x80, 0xb5,
+ 0xa1, 0xe1, 0x7a, 0xc3, 0xfd, 0x90, 0xf9, 0x8b, 0x08, 0xeb, 0x8e, 0xe6, 0x76, 0x08, 0x28, 0x6c,
+ 0xc4, 0xae, 0x23, 0xa1, 0x27, 0xec, 0xe0, 0xba, 0xa3, 0xb9, 0x16, 0x91, 0x6b, 0xf4, 0x05, 0x58,
+ 0x09, 0x4d, 0xb3, 0x2d, 0xf7, 0x17, 0x71, 0xc6, 0x38, 0x6e, 0x39, 0x9a, 0xab, 0x13, 0x53, 0x61,
+ 0xd7, 0x02, 0x42, 0x5f, 0x42, 0x87, 0x27, 0x19, 0xf5, 0xd3, 0x45, 0xcc, 0xd3, 0x28, 0x60, 0xd8,
+ 0x70, 0x34, 0xd7, 0x20, 0x96, 0x00, 0x67, 0x05, 0x86, 0xba, 0xd0, 0x48, 0x17, 0x71, 0x42, 0x71,
+ 0xdb, 0xd1, 0xdc, 0x1a, 0x51, 0x1b, 0x64, 0x83, 0xfe, 0x37, 0xcd, 0x71, 0xc3, 0xd1, 0xdd, 0x3a,
+ 0x11, 0x4b, 0xf4, 0x29, 0xb4, 0xd3, 0x4d, 0x9c, 0x70, 0x5f, 0xe0, 0x27, 0x8e, 0xee, 0x36, 0x88,
+ 0x21, 0x81, 0x3b, 0x9a, 0xa3, 0x6f, 0xa1, 0xc9, 0x68, 0xca, 0xe9, 0x12, 0x37, 0x1d, 0xcd, 0x35,
+ 0x87, 0xdd, 0x97, 0xbf, 0x3e, 0x91, 0x67, 0xa4, 0xe0, 0xa0, 0x73, 0x68, 0x25, 0xfe, 0x2a, 0x63,
+ 0x2c, 0xc7, 0xb6, 0xa3, 0x7f, 0x30, 0xa9, 0x66, 0x72, 0x2b, 0xb8, 0xe8, 0x67, 0x68, 0x71, 0x9a,
+ 0x24, 0x41, 0xc8, 0x30, 0x38, 0xba, 0x6b, 0x0e, 0xfb, 0xd5, 0x65, 0x0f, 0x8a, 0x74, 0xc3, 0x78,
+ 0x92, 0x93, 0x7d, 0x09, 0xba, 0x00, 0x75, 0xff, 0x43, 0x7f, 0x15, 0xd2, 0xed, 0x12, 0x9b, 0xd2,
+ 0xe8, 0x27, 0xde, 0xfe, 0xae, 0xbd, 0x59, 0x36, 0xff, 0x8d, 0xae, 0x82, 0x6c, 0xcb, 0x53, 0x62,
+ 0x2a, 0xea, 0xad, 0x60, 0xa2, 0xd1, 0xa1, 0xf2, 0xdf, 0x60, 0x9b, 0x51, 0xdc, 0x91, 0xe2, 0x5f,
+ 0x55, 0x8b, 0x4f, 0x25, 0xf3, 0x4f, 0x41, 0x54, 0x06, 0x8a, 0x56, 0x12, 0x41, 0xdf, 0x83, 0x11,
+ 0xb0, 0x9c, 0x6f, 0x42, 0xb6, 0xc6, 0x47, 0x45, 0x52, 0x6a, 0x0e, 0xbd, 0xfd, 0x1c, 0x7a, 0x97,
+ 0x2c, 0x27, 0x07, 0x16, 0x3a, 0x07, 0x33, 0x0a, 0x58, 0xee, 0xcb, 0x5d, 0x8a, 0x8f, 0xa5, 0x76,
+ 0x75, 0x11, 0x08, 0xe2, 0x83, 0xe4, 0xa1, 0x73, 0x80, 0x34, 0x9b, 0x47, 0xca, 0x14, 0xfe, 0xb8,
+ 0xf8, 0xd7, 0x2a, 0xc7, 0xa4, 0x44, 0x44, 0x3f, 0x80, 0xb1, 0xd8, 0x84, 0xdb, 0x65, 0x42, 0x19,
+ 0x46, 0x52, 0xea, 0x8d, 0xa2, 0x03, 0xad, 0x37, 0x05, 0xab, 0x1c, 0xf8, 0x7e, 0x72, 0xd4, 0xd3,
+ 0x90, 0x93, 0xf3, 0x35, 0x34, 0x54, 0x70, 0xb5, 0xf7, 0xcc, 0x86, 0xa2, 0xfc, 0x54, 0xbb, 0xd0,
+ 0x7a, 0x8f, 0x60, 0xbf, 0x4e, 0xb1, 0xa2, 0xeb, 0x37, 0x2f, 0xbb, 0xbe, 0x71, 0x91, 0xcf, 0x6d,
+ 0xfb, 0xbf, 0x42, 0x53, 0x0d, 0x14, 0x32, 0xa1, 0xf5, 0x38, 0xb9, 0x9b, 0xfc, 0xf1, 0x34, 0xb1,
+ 0x3f, 0x42, 0x06, 0xd4, 0xa7, 0x8f, 0x93, 0x99, 0xad, 0xa1, 0x0e, 0xb4, 0x67, 0xe3, 0xcb, 0xe9,
+ 0xec, 0x61, 0x74, 0x7d, 0x67, 0xd7, 0xd0, 0x31, 0x98, 0x57, 0xa3, 0xf1, 0xd8, 0xbf, 0xba, 0x1c,
+ 0x8d, 0x6f, 0xfe, 0xb2, 0xf5, 0xfe, 0x10, 0x9a, 0xca, 0xac, 0x78, 0x33, 0x73, 0x39, 0xbe, 0xca,
+ 0x8f, 0xda, 0x88, 0x57, 0xba, 0xc8, 0xb8, 0x32, 0x64, 0x10, 0xb9, 0xee, 0xff, 0xa7, 0xc1, 0x51,
+ 0x91, 0xd9, 0x53, 0xc8, 0x37, 0xf7, 0xc1, 0x0e, 0x4d, 0xc1, 0x9a, 0xe7, 0x9c, 0xfa, 0x51, 0xb0,
+ 0xdb, 0x89, 0x39, 0xd0, 0x64, 0xce, 0xdf, 0x55, 0xe6, 0x5c, 0xd4, 0x78, 0x57, 0x39, 0xa7, 0xf7,
+ 0x8a, 0x5f, 0x4c, 0xd5, 0xfc, 0x19, 0xe9, 0xfd, 0x02, 0xf6, 0x6b, 0x42, 0x39, 0x30, 0x43, 0x05,
+ 0xd6, 0x2d, 0x07, 0x66, 0x95, 0x93, 0xf9, 0x07, 0x9a, 0x23, 0xc6, 0x85, 0xb7, 0x01, 0xe8, 0x09,
+ 0xe7, 0x85, 0xa5, 0xcf, 0x5f, 0x5a, 0x52, 0x14, 0x8f, 0x70, 0xae, 0x2c, 0x08, 0x66, 0xef, 0x47,
+ 0x30, 0xf6, 0x40, 0x59, 0xb2, 0x51, 0x21, 0xd9, 0x28, 0x4b, 0x9e, 0x41, 0x4b, 0xf5, 0x4b, 0x91,
+ 0x0b, 0xf5, 0x28, 0xd8, 0xa5, 0x85, 0x68, 0xb7, 0x4a, 0x94, 0x48, 0xc6, 0xbc, 0xa9, 0x8e, 0xde,
+ 0x05, 0x00, 0x00, 0xff, 0xff, 0x75, 0x38, 0xad, 0x84, 0xe4, 0x05, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.proto b/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.proto
index e2311d9..2048655 100644
--- a/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.proto
+++ b/vendor/github.com/golang/protobuf/proto/proto3_proto/proto3.proto
@@ -31,6 +31,7 @@
syntax = "proto3";
+import "google/protobuf/any.proto";
import "testdata/test.proto";
package proto3_proto;
@@ -52,17 +53,35 @@ message Message {
float score = 9;
repeated uint64 key = 5;
+ repeated int32 short_key = 19;
Nested nested = 6;
+ repeated Humour r_funny = 16;
map terrain = 10;
testdata.SubDefaults proto2_field = 11;
map proto2_value = 13;
+
+ google.protobuf.Any anything = 14;
+ repeated google.protobuf.Any many_things = 15;
+
+ Message submessage = 17;
+ repeated Message children = 18;
}
message Nested {
string bunny = 1;
+ bool cute = 2;
}
message MessageWithMap {
map byte_mapping = 1;
}
+
+
+message IntMap {
+ map rtt = 1;
+}
+
+message IntMaps {
+ repeated IntMap maps = 1;
+}
diff --git a/vendor/github.com/golang/protobuf/proto/proto3_test.go b/vendor/github.com/golang/protobuf/proto/proto3_test.go
index 462f805..735837f 100644
--- a/vendor/github.com/golang/protobuf/proto/proto3_test.go
+++ b/vendor/github.com/golang/protobuf/proto/proto3_test.go
@@ -93,6 +93,16 @@ func TestRoundTripProto3(t *testing.T) {
}
}
+func TestGettersForBasicTypesExist(t *testing.T) {
+ var m pb.Message
+ if got := m.GetNested().GetBunny(); got != "" {
+ t.Errorf("m.GetNested().GetBunny() = %q, want empty string", got)
+ }
+ if got := m.GetNested().GetCute(); got {
+ t.Errorf("m.GetNested().GetCute() = %t, want false", got)
+ }
+}
+
func TestProto3SetDefaults(t *testing.T) {
in := &pb.Message{
Terrain: map[string]*pb.Nested{
diff --git a/vendor/github.com/golang/protobuf/proto/size_test.go b/vendor/github.com/golang/protobuf/proto/size_test.go
index db5614f..af1034d 100644
--- a/vendor/github.com/golang/protobuf/proto/size_test.go
+++ b/vendor/github.com/golang/protobuf/proto/size_test.go
@@ -124,6 +124,28 @@ var SizeTests = []struct {
{"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}},
{"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}},
{"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}},
+
+ {"oneof not set", &pb.Oneof{}},
+ {"oneof bool", &pb.Oneof{Union: &pb.Oneof_F_Bool{true}}},
+ {"oneof zero int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{0}}},
+ {"oneof big int32", &pb.Oneof{Union: &pb.Oneof_F_Int32{1 << 20}}},
+ {"oneof int64", &pb.Oneof{Union: &pb.Oneof_F_Int64{42}}},
+ {"oneof fixed32", &pb.Oneof{Union: &pb.Oneof_F_Fixed32{43}}},
+ {"oneof fixed64", &pb.Oneof{Union: &pb.Oneof_F_Fixed64{44}}},
+ {"oneof uint32", &pb.Oneof{Union: &pb.Oneof_F_Uint32{45}}},
+ {"oneof uint64", &pb.Oneof{Union: &pb.Oneof_F_Uint64{46}}},
+ {"oneof float", &pb.Oneof{Union: &pb.Oneof_F_Float{47.1}}},
+ {"oneof double", &pb.Oneof{Union: &pb.Oneof_F_Double{48.9}}},
+ {"oneof string", &pb.Oneof{Union: &pb.Oneof_F_String{"Rhythmic Fman"}}},
+ {"oneof bytes", &pb.Oneof{Union: &pb.Oneof_F_Bytes{[]byte("let go")}}},
+ {"oneof sint32", &pb.Oneof{Union: &pb.Oneof_F_Sint32{50}}},
+ {"oneof sint64", &pb.Oneof{Union: &pb.Oneof_F_Sint64{51}}},
+ {"oneof enum", &pb.Oneof{Union: &pb.Oneof_F_Enum{pb.MyMessage_BLUE}}},
+ {"message for oneof", &pb.GoTestField{Label: String("k"), Type: String("v")}},
+ {"oneof message", &pb.Oneof{Union: &pb.Oneof_F_Message{&pb.GoTestField{Label: String("k"), Type: String("v")}}}},
+ {"oneof group", &pb.Oneof{Union: &pb.Oneof_FGroup{&pb.Oneof_F_Group{X: Int32(52)}}}},
+ {"oneof largest tag", &pb.Oneof{Union: &pb.Oneof_F_Largest_Tag{1}}},
+ {"multiple oneofs", &pb.Oneof{Union: &pb.Oneof_F_Int32{1}, Tormato: &pb.Oneof_Value{2}}},
}
func TestSize(t *testing.T) {
diff --git a/vendor/github.com/golang/protobuf/proto/testdata/Makefile b/vendor/github.com/golang/protobuf/proto/testdata/Makefile
new file mode 100644
index 0000000..fc28862
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/testdata/Makefile
@@ -0,0 +1,50 @@
+# 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.
+
+
+include ../../Make.protobuf
+
+all: regenerate
+
+regenerate:
+ rm -f test.pb.go
+ make test.pb.go
+
+# The following rules are just aids to development. Not needed for typical testing.
+
+diff: regenerate
+ git diff test.pb.go
+
+restore:
+ cp test.pb.go.golden test.pb.go
+
+preserve:
+ cp test.pb.go test.pb.go.golden
diff --git a/vendor/github.com/golang/protobuf/proto/testdata/golden_test.go b/vendor/github.com/golang/protobuf/proto/testdata/golden_test.go
new file mode 100644
index 0000000..7172d0e
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/testdata/golden_test.go
@@ -0,0 +1,86 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2012 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.
+
+// Verify that the compiler output for test.proto is unchanged.
+
+package testdata
+
+import (
+ "crypto/sha1"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+)
+
+// sum returns in string form (for easy comparison) the SHA-1 hash of the named file.
+func sum(t *testing.T, name string) string {
+ data, err := ioutil.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Logf("sum(%q): length is %d", name, len(data))
+ hash := sha1.New()
+ _, err = hash.Write(data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return fmt.Sprintf("% x", hash.Sum(nil))
+}
+
+func run(t *testing.T, name string, args ...string) {
+ cmd := exec.Command(name, args...)
+ cmd.Stdin = os.Stdin
+ cmd.Stdout = os.Stdout
+ cmd.Stderr = os.Stderr
+ err := cmd.Run()
+ if err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestGolden(t *testing.T) {
+ // Compute the original checksum.
+ goldenSum := sum(t, "test.pb.go")
+ // Run the proto compiler.
+ run(t, "protoc", "--go_out="+os.TempDir(), "test.proto")
+ newFile := filepath.Join(os.TempDir(), "test.pb.go")
+ defer os.Remove(newFile)
+ // Compute the new checksum.
+ newSum := sum(t, newFile)
+ // Verify
+ if newSum != goldenSum {
+ run(t, "diff", "-u", "test.pb.go", newFile)
+ t.Fatal("Code generated by protoc-gen-go has changed; update test.pb.go")
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/proto/testdata/test.pb.go b/vendor/github.com/golang/protobuf/proto/testdata/test.pb.go
new file mode 100644
index 0000000..e980d1a
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/testdata/test.pb.go
@@ -0,0 +1,4147 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: test.proto
+
+/*
+Package testdata is a generated protocol buffer package.
+
+It is generated from these files:
+ test.proto
+
+It has these top-level messages:
+ GoEnum
+ GoTestField
+ GoTest
+ GoTestRequiredGroupField
+ GoSkipTest
+ NonPackedTest
+ PackedTest
+ MaxTag
+ OldMessage
+ NewMessage
+ InnerMessage
+ OtherMessage
+ RequiredInnerMessage
+ MyMessage
+ Ext
+ ComplexExtension
+ DefaultsMessage
+ MyMessageSet
+ Empty
+ MessageList
+ Strings
+ Defaults
+ SubDefaults
+ RepeatedEnum
+ MoreRepeated
+ GroupOld
+ GroupNew
+ FloatingPoint
+ MessageWithMap
+ Oneof
+ Communique
+*/
+package testdata
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+type FOO int32
+
+const (
+ FOO_FOO1 FOO = 1
+)
+
+var FOO_name = map[int32]string{
+ 1: "FOO1",
+}
+var FOO_value = map[string]int32{
+ "FOO1": 1,
+}
+
+func (x FOO) Enum() *FOO {
+ p := new(FOO)
+ *p = x
+ return p
+}
+func (x FOO) String() string {
+ return proto.EnumName(FOO_name, int32(x))
+}
+func (x *FOO) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FOO_value, data, "FOO")
+ if err != nil {
+ return err
+ }
+ *x = FOO(value)
+ return nil
+}
+func (FOO) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+// An enum, for completeness.
+type GoTest_KIND int32
+
+const (
+ GoTest_VOID GoTest_KIND = 0
+ // Basic types
+ GoTest_BOOL GoTest_KIND = 1
+ GoTest_BYTES GoTest_KIND = 2
+ GoTest_FINGERPRINT GoTest_KIND = 3
+ GoTest_FLOAT GoTest_KIND = 4
+ GoTest_INT GoTest_KIND = 5
+ GoTest_STRING GoTest_KIND = 6
+ GoTest_TIME GoTest_KIND = 7
+ // Groupings
+ GoTest_TUPLE GoTest_KIND = 8
+ GoTest_ARRAY GoTest_KIND = 9
+ GoTest_MAP GoTest_KIND = 10
+ // Table types
+ GoTest_TABLE GoTest_KIND = 11
+ // Functions
+ GoTest_FUNCTION GoTest_KIND = 12
+)
+
+var GoTest_KIND_name = map[int32]string{
+ 0: "VOID",
+ 1: "BOOL",
+ 2: "BYTES",
+ 3: "FINGERPRINT",
+ 4: "FLOAT",
+ 5: "INT",
+ 6: "STRING",
+ 7: "TIME",
+ 8: "TUPLE",
+ 9: "ARRAY",
+ 10: "MAP",
+ 11: "TABLE",
+ 12: "FUNCTION",
+}
+var GoTest_KIND_value = map[string]int32{
+ "VOID": 0,
+ "BOOL": 1,
+ "BYTES": 2,
+ "FINGERPRINT": 3,
+ "FLOAT": 4,
+ "INT": 5,
+ "STRING": 6,
+ "TIME": 7,
+ "TUPLE": 8,
+ "ARRAY": 9,
+ "MAP": 10,
+ "TABLE": 11,
+ "FUNCTION": 12,
+}
+
+func (x GoTest_KIND) Enum() *GoTest_KIND {
+ p := new(GoTest_KIND)
+ *p = x
+ return p
+}
+func (x GoTest_KIND) String() string {
+ return proto.EnumName(GoTest_KIND_name, int32(x))
+}
+func (x *GoTest_KIND) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(GoTest_KIND_value, data, "GoTest_KIND")
+ if err != nil {
+ return err
+ }
+ *x = GoTest_KIND(value)
+ return nil
+}
+func (GoTest_KIND) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} }
+
+type MyMessage_Color int32
+
+const (
+ MyMessage_RED MyMessage_Color = 0
+ MyMessage_GREEN MyMessage_Color = 1
+ MyMessage_BLUE MyMessage_Color = 2
+)
+
+var MyMessage_Color_name = map[int32]string{
+ 0: "RED",
+ 1: "GREEN",
+ 2: "BLUE",
+}
+var MyMessage_Color_value = map[string]int32{
+ "RED": 0,
+ "GREEN": 1,
+ "BLUE": 2,
+}
+
+func (x MyMessage_Color) Enum() *MyMessage_Color {
+ p := new(MyMessage_Color)
+ *p = x
+ return p
+}
+func (x MyMessage_Color) String() string {
+ return proto.EnumName(MyMessage_Color_name, int32(x))
+}
+func (x *MyMessage_Color) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(MyMessage_Color_value, data, "MyMessage_Color")
+ if err != nil {
+ return err
+ }
+ *x = MyMessage_Color(value)
+ return nil
+}
+func (MyMessage_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{13, 0} }
+
+type DefaultsMessage_DefaultsEnum int32
+
+const (
+ DefaultsMessage_ZERO DefaultsMessage_DefaultsEnum = 0
+ DefaultsMessage_ONE DefaultsMessage_DefaultsEnum = 1
+ DefaultsMessage_TWO DefaultsMessage_DefaultsEnum = 2
+)
+
+var DefaultsMessage_DefaultsEnum_name = map[int32]string{
+ 0: "ZERO",
+ 1: "ONE",
+ 2: "TWO",
+}
+var DefaultsMessage_DefaultsEnum_value = map[string]int32{
+ "ZERO": 0,
+ "ONE": 1,
+ "TWO": 2,
+}
+
+func (x DefaultsMessage_DefaultsEnum) Enum() *DefaultsMessage_DefaultsEnum {
+ p := new(DefaultsMessage_DefaultsEnum)
+ *p = x
+ return p
+}
+func (x DefaultsMessage_DefaultsEnum) String() string {
+ return proto.EnumName(DefaultsMessage_DefaultsEnum_name, int32(x))
+}
+func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(DefaultsMessage_DefaultsEnum_value, data, "DefaultsMessage_DefaultsEnum")
+ if err != nil {
+ return err
+ }
+ *x = DefaultsMessage_DefaultsEnum(value)
+ return nil
+}
+func (DefaultsMessage_DefaultsEnum) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{16, 0}
+}
+
+type Defaults_Color int32
+
+const (
+ Defaults_RED Defaults_Color = 0
+ Defaults_GREEN Defaults_Color = 1
+ Defaults_BLUE Defaults_Color = 2
+)
+
+var Defaults_Color_name = map[int32]string{
+ 0: "RED",
+ 1: "GREEN",
+ 2: "BLUE",
+}
+var Defaults_Color_value = map[string]int32{
+ "RED": 0,
+ "GREEN": 1,
+ "BLUE": 2,
+}
+
+func (x Defaults_Color) Enum() *Defaults_Color {
+ p := new(Defaults_Color)
+ *p = x
+ return p
+}
+func (x Defaults_Color) String() string {
+ return proto.EnumName(Defaults_Color_name, int32(x))
+}
+func (x *Defaults_Color) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(Defaults_Color_value, data, "Defaults_Color")
+ if err != nil {
+ return err
+ }
+ *x = Defaults_Color(value)
+ return nil
+}
+func (Defaults_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{21, 0} }
+
+type RepeatedEnum_Color int32
+
+const (
+ RepeatedEnum_RED RepeatedEnum_Color = 1
+)
+
+var RepeatedEnum_Color_name = map[int32]string{
+ 1: "RED",
+}
+var RepeatedEnum_Color_value = map[string]int32{
+ "RED": 1,
+}
+
+func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color {
+ p := new(RepeatedEnum_Color)
+ *p = x
+ return p
+}
+func (x RepeatedEnum_Color) String() string {
+ return proto.EnumName(RepeatedEnum_Color_name, int32(x))
+}
+func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(RepeatedEnum_Color_value, data, "RepeatedEnum_Color")
+ if err != nil {
+ return err
+ }
+ *x = RepeatedEnum_Color(value)
+ return nil
+}
+func (RepeatedEnum_Color) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{23, 0} }
+
+type GoEnum struct {
+ Foo *FOO `protobuf:"varint,1,req,name=foo,enum=testdata.FOO" json:"foo,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GoEnum) Reset() { *m = GoEnum{} }
+func (m *GoEnum) String() string { return proto.CompactTextString(m) }
+func (*GoEnum) ProtoMessage() {}
+func (*GoEnum) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+func (m *GoEnum) GetFoo() FOO {
+ if m != nil && m.Foo != nil {
+ return *m.Foo
+ }
+ return FOO_FOO1
+}
+
+type GoTestField struct {
+ Label *string `protobuf:"bytes,1,req,name=Label" json:"Label,omitempty"`
+ Type *string `protobuf:"bytes,2,req,name=Type" json:"Type,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GoTestField) Reset() { *m = GoTestField{} }
+func (m *GoTestField) String() string { return proto.CompactTextString(m) }
+func (*GoTestField) ProtoMessage() {}
+func (*GoTestField) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+func (m *GoTestField) GetLabel() string {
+ if m != nil && m.Label != nil {
+ return *m.Label
+ }
+ return ""
+}
+
+func (m *GoTestField) GetType() string {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return ""
+}
+
+type GoTest struct {
+ // Some typical parameters
+ Kind *GoTest_KIND `protobuf:"varint,1,req,name=Kind,enum=testdata.GoTest_KIND" json:"Kind,omitempty"`
+ Table *string `protobuf:"bytes,2,opt,name=Table" json:"Table,omitempty"`
+ Param *int32 `protobuf:"varint,3,opt,name=Param" json:"Param,omitempty"`
+ // Required, repeated and optional foreign fields.
+ RequiredField *GoTestField `protobuf:"bytes,4,req,name=RequiredField" json:"RequiredField,omitempty"`
+ RepeatedField []*GoTestField `protobuf:"bytes,5,rep,name=RepeatedField" json:"RepeatedField,omitempty"`
+ OptionalField *GoTestField `protobuf:"bytes,6,opt,name=OptionalField" json:"OptionalField,omitempty"`
+ // Required fields of all basic types
+ F_BoolRequired *bool `protobuf:"varint,10,req,name=F_Bool_required,json=FBoolRequired" json:"F_Bool_required,omitempty"`
+ F_Int32Required *int32 `protobuf:"varint,11,req,name=F_Int32_required,json=FInt32Required" json:"F_Int32_required,omitempty"`
+ F_Int64Required *int64 `protobuf:"varint,12,req,name=F_Int64_required,json=FInt64Required" json:"F_Int64_required,omitempty"`
+ F_Fixed32Required *uint32 `protobuf:"fixed32,13,req,name=F_Fixed32_required,json=FFixed32Required" json:"F_Fixed32_required,omitempty"`
+ F_Fixed64Required *uint64 `protobuf:"fixed64,14,req,name=F_Fixed64_required,json=FFixed64Required" json:"F_Fixed64_required,omitempty"`
+ F_Uint32Required *uint32 `protobuf:"varint,15,req,name=F_Uint32_required,json=FUint32Required" json:"F_Uint32_required,omitempty"`
+ F_Uint64Required *uint64 `protobuf:"varint,16,req,name=F_Uint64_required,json=FUint64Required" json:"F_Uint64_required,omitempty"`
+ F_FloatRequired *float32 `protobuf:"fixed32,17,req,name=F_Float_required,json=FFloatRequired" json:"F_Float_required,omitempty"`
+ F_DoubleRequired *float64 `protobuf:"fixed64,18,req,name=F_Double_required,json=FDoubleRequired" json:"F_Double_required,omitempty"`
+ F_StringRequired *string `protobuf:"bytes,19,req,name=F_String_required,json=FStringRequired" json:"F_String_required,omitempty"`
+ F_BytesRequired []byte `protobuf:"bytes,101,req,name=F_Bytes_required,json=FBytesRequired" json:"F_Bytes_required,omitempty"`
+ F_Sint32Required *int32 `protobuf:"zigzag32,102,req,name=F_Sint32_required,json=FSint32Required" json:"F_Sint32_required,omitempty"`
+ F_Sint64Required *int64 `protobuf:"zigzag64,103,req,name=F_Sint64_required,json=FSint64Required" json:"F_Sint64_required,omitempty"`
+ // Repeated fields of all basic types
+ F_BoolRepeated []bool `protobuf:"varint,20,rep,name=F_Bool_repeated,json=FBoolRepeated" json:"F_Bool_repeated,omitempty"`
+ F_Int32Repeated []int32 `protobuf:"varint,21,rep,name=F_Int32_repeated,json=FInt32Repeated" json:"F_Int32_repeated,omitempty"`
+ F_Int64Repeated []int64 `protobuf:"varint,22,rep,name=F_Int64_repeated,json=FInt64Repeated" json:"F_Int64_repeated,omitempty"`
+ F_Fixed32Repeated []uint32 `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated,json=FFixed32Repeated" json:"F_Fixed32_repeated,omitempty"`
+ F_Fixed64Repeated []uint64 `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated,json=FFixed64Repeated" json:"F_Fixed64_repeated,omitempty"`
+ F_Uint32Repeated []uint32 `protobuf:"varint,25,rep,name=F_Uint32_repeated,json=FUint32Repeated" json:"F_Uint32_repeated,omitempty"`
+ F_Uint64Repeated []uint64 `protobuf:"varint,26,rep,name=F_Uint64_repeated,json=FUint64Repeated" json:"F_Uint64_repeated,omitempty"`
+ F_FloatRepeated []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated,json=FFloatRepeated" json:"F_Float_repeated,omitempty"`
+ F_DoubleRepeated []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated,json=FDoubleRepeated" json:"F_Double_repeated,omitempty"`
+ F_StringRepeated []string `protobuf:"bytes,29,rep,name=F_String_repeated,json=FStringRepeated" json:"F_String_repeated,omitempty"`
+ F_BytesRepeated [][]byte `protobuf:"bytes,201,rep,name=F_Bytes_repeated,json=FBytesRepeated" json:"F_Bytes_repeated,omitempty"`
+ F_Sint32Repeated []int32 `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated,json=FSint32Repeated" json:"F_Sint32_repeated,omitempty"`
+ F_Sint64Repeated []int64 `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated,json=FSint64Repeated" json:"F_Sint64_repeated,omitempty"`
+ // Optional fields of all basic types
+ F_BoolOptional *bool `protobuf:"varint,30,opt,name=F_Bool_optional,json=FBoolOptional" json:"F_Bool_optional,omitempty"`
+ F_Int32Optional *int32 `protobuf:"varint,31,opt,name=F_Int32_optional,json=FInt32Optional" json:"F_Int32_optional,omitempty"`
+ F_Int64Optional *int64 `protobuf:"varint,32,opt,name=F_Int64_optional,json=FInt64Optional" json:"F_Int64_optional,omitempty"`
+ F_Fixed32Optional *uint32 `protobuf:"fixed32,33,opt,name=F_Fixed32_optional,json=FFixed32Optional" json:"F_Fixed32_optional,omitempty"`
+ F_Fixed64Optional *uint64 `protobuf:"fixed64,34,opt,name=F_Fixed64_optional,json=FFixed64Optional" json:"F_Fixed64_optional,omitempty"`
+ F_Uint32Optional *uint32 `protobuf:"varint,35,opt,name=F_Uint32_optional,json=FUint32Optional" json:"F_Uint32_optional,omitempty"`
+ F_Uint64Optional *uint64 `protobuf:"varint,36,opt,name=F_Uint64_optional,json=FUint64Optional" json:"F_Uint64_optional,omitempty"`
+ F_FloatOptional *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional,json=FFloatOptional" json:"F_Float_optional,omitempty"`
+ F_DoubleOptional *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional,json=FDoubleOptional" json:"F_Double_optional,omitempty"`
+ F_StringOptional *string `protobuf:"bytes,39,opt,name=F_String_optional,json=FStringOptional" json:"F_String_optional,omitempty"`
+ F_BytesOptional []byte `protobuf:"bytes,301,opt,name=F_Bytes_optional,json=FBytesOptional" json:"F_Bytes_optional,omitempty"`
+ F_Sint32Optional *int32 `protobuf:"zigzag32,302,opt,name=F_Sint32_optional,json=FSint32Optional" json:"F_Sint32_optional,omitempty"`
+ F_Sint64Optional *int64 `protobuf:"zigzag64,303,opt,name=F_Sint64_optional,json=FSint64Optional" json:"F_Sint64_optional,omitempty"`
+ // Default-valued fields of all basic types
+ F_BoolDefaulted *bool `protobuf:"varint,40,opt,name=F_Bool_defaulted,json=FBoolDefaulted,def=1" json:"F_Bool_defaulted,omitempty"`
+ F_Int32Defaulted *int32 `protobuf:"varint,41,opt,name=F_Int32_defaulted,json=FInt32Defaulted,def=32" json:"F_Int32_defaulted,omitempty"`
+ F_Int64Defaulted *int64 `protobuf:"varint,42,opt,name=F_Int64_defaulted,json=FInt64Defaulted,def=64" json:"F_Int64_defaulted,omitempty"`
+ F_Fixed32Defaulted *uint32 `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,json=FFixed32Defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"`
+ F_Fixed64Defaulted *uint64 `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,json=FFixed64Defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"`
+ F_Uint32Defaulted *uint32 `protobuf:"varint,45,opt,name=F_Uint32_defaulted,json=FUint32Defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"`
+ F_Uint64Defaulted *uint64 `protobuf:"varint,46,opt,name=F_Uint64_defaulted,json=FUint64Defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"`
+ F_FloatDefaulted *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,json=FFloatDefaulted,def=314159" json:"F_Float_defaulted,omitempty"`
+ F_DoubleDefaulted *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,json=FDoubleDefaulted,def=271828" json:"F_Double_defaulted,omitempty"`
+ F_StringDefaulted *string `protobuf:"bytes,49,opt,name=F_String_defaulted,json=FStringDefaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"`
+ F_BytesDefaulted []byte `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,json=FBytesDefaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"`
+ F_Sint32Defaulted *int32 `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,json=FSint32Defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"`
+ F_Sint64Defaulted *int64 `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,json=FSint64Defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"`
+ // Packed repeated fields (no string or bytes).
+ F_BoolRepeatedPacked []bool `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed,json=FBoolRepeatedPacked" json:"F_Bool_repeated_packed,omitempty"`
+ F_Int32RepeatedPacked []int32 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed,json=FInt32RepeatedPacked" json:"F_Int32_repeated_packed,omitempty"`
+ F_Int64RepeatedPacked []int64 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed,json=FInt64RepeatedPacked" json:"F_Int64_repeated_packed,omitempty"`
+ F_Fixed32RepeatedPacked []uint32 `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed,json=FFixed32RepeatedPacked" json:"F_Fixed32_repeated_packed,omitempty"`
+ F_Fixed64RepeatedPacked []uint64 `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed,json=FFixed64RepeatedPacked" json:"F_Fixed64_repeated_packed,omitempty"`
+ F_Uint32RepeatedPacked []uint32 `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed,json=FUint32RepeatedPacked" json:"F_Uint32_repeated_packed,omitempty"`
+ F_Uint64RepeatedPacked []uint64 `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed,json=FUint64RepeatedPacked" json:"F_Uint64_repeated_packed,omitempty"`
+ F_FloatRepeatedPacked []float32 `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed,json=FFloatRepeatedPacked" json:"F_Float_repeated_packed,omitempty"`
+ F_DoubleRepeatedPacked []float64 `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed,json=FDoubleRepeatedPacked" json:"F_Double_repeated_packed,omitempty"`
+ F_Sint32RepeatedPacked []int32 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed,json=FSint32RepeatedPacked" json:"F_Sint32_repeated_packed,omitempty"`
+ F_Sint64RepeatedPacked []int64 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed,json=FSint64RepeatedPacked" json:"F_Sint64_repeated_packed,omitempty"`
+ Requiredgroup *GoTest_RequiredGroup `protobuf:"group,70,req,name=RequiredGroup,json=requiredgroup" json:"requiredgroup,omitempty"`
+ Repeatedgroup []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup,json=repeatedgroup" json:"repeatedgroup,omitempty"`
+ Optionalgroup *GoTest_OptionalGroup `protobuf:"group,90,opt,name=OptionalGroup,json=optionalgroup" json:"optionalgroup,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GoTest) Reset() { *m = GoTest{} }
+func (m *GoTest) String() string { return proto.CompactTextString(m) }
+func (*GoTest) ProtoMessage() {}
+func (*GoTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
+
+const Default_GoTest_F_BoolDefaulted bool = true
+const Default_GoTest_F_Int32Defaulted int32 = 32
+const Default_GoTest_F_Int64Defaulted int64 = 64
+const Default_GoTest_F_Fixed32Defaulted uint32 = 320
+const Default_GoTest_F_Fixed64Defaulted uint64 = 640
+const Default_GoTest_F_Uint32Defaulted uint32 = 3200
+const Default_GoTest_F_Uint64Defaulted uint64 = 6400
+const Default_GoTest_F_FloatDefaulted float32 = 314159
+const Default_GoTest_F_DoubleDefaulted float64 = 271828
+const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n"
+
+var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose")
+
+const Default_GoTest_F_Sint32Defaulted int32 = -32
+const Default_GoTest_F_Sint64Defaulted int64 = -64
+
+func (m *GoTest) GetKind() GoTest_KIND {
+ if m != nil && m.Kind != nil {
+ return *m.Kind
+ }
+ return GoTest_VOID
+}
+
+func (m *GoTest) GetTable() string {
+ if m != nil && m.Table != nil {
+ return *m.Table
+ }
+ return ""
+}
+
+func (m *GoTest) GetParam() int32 {
+ if m != nil && m.Param != nil {
+ return *m.Param
+ }
+ return 0
+}
+
+func (m *GoTest) GetRequiredField() *GoTestField {
+ if m != nil {
+ return m.RequiredField
+ }
+ return nil
+}
+
+func (m *GoTest) GetRepeatedField() []*GoTestField {
+ if m != nil {
+ return m.RepeatedField
+ }
+ return nil
+}
+
+func (m *GoTest) GetOptionalField() *GoTestField {
+ if m != nil {
+ return m.OptionalField
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_BoolRequired() bool {
+ if m != nil && m.F_BoolRequired != nil {
+ return *m.F_BoolRequired
+ }
+ return false
+}
+
+func (m *GoTest) GetF_Int32Required() int32 {
+ if m != nil && m.F_Int32Required != nil {
+ return *m.F_Int32Required
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_Int64Required() int64 {
+ if m != nil && m.F_Int64Required != nil {
+ return *m.F_Int64Required
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_Fixed32Required() uint32 {
+ if m != nil && m.F_Fixed32Required != nil {
+ return *m.F_Fixed32Required
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_Fixed64Required() uint64 {
+ if m != nil && m.F_Fixed64Required != nil {
+ return *m.F_Fixed64Required
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_Uint32Required() uint32 {
+ if m != nil && m.F_Uint32Required != nil {
+ return *m.F_Uint32Required
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_Uint64Required() uint64 {
+ if m != nil && m.F_Uint64Required != nil {
+ return *m.F_Uint64Required
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_FloatRequired() float32 {
+ if m != nil && m.F_FloatRequired != nil {
+ return *m.F_FloatRequired
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_DoubleRequired() float64 {
+ if m != nil && m.F_DoubleRequired != nil {
+ return *m.F_DoubleRequired
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_StringRequired() string {
+ if m != nil && m.F_StringRequired != nil {
+ return *m.F_StringRequired
+ }
+ return ""
+}
+
+func (m *GoTest) GetF_BytesRequired() []byte {
+ if m != nil {
+ return m.F_BytesRequired
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Sint32Required() int32 {
+ if m != nil && m.F_Sint32Required != nil {
+ return *m.F_Sint32Required
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_Sint64Required() int64 {
+ if m != nil && m.F_Sint64Required != nil {
+ return *m.F_Sint64Required
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_BoolRepeated() []bool {
+ if m != nil {
+ return m.F_BoolRepeated
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Int32Repeated() []int32 {
+ if m != nil {
+ return m.F_Int32Repeated
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Int64Repeated() []int64 {
+ if m != nil {
+ return m.F_Int64Repeated
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Fixed32Repeated() []uint32 {
+ if m != nil {
+ return m.F_Fixed32Repeated
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Fixed64Repeated() []uint64 {
+ if m != nil {
+ return m.F_Fixed64Repeated
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Uint32Repeated() []uint32 {
+ if m != nil {
+ return m.F_Uint32Repeated
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Uint64Repeated() []uint64 {
+ if m != nil {
+ return m.F_Uint64Repeated
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_FloatRepeated() []float32 {
+ if m != nil {
+ return m.F_FloatRepeated
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_DoubleRepeated() []float64 {
+ if m != nil {
+ return m.F_DoubleRepeated
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_StringRepeated() []string {
+ if m != nil {
+ return m.F_StringRepeated
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_BytesRepeated() [][]byte {
+ if m != nil {
+ return m.F_BytesRepeated
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Sint32Repeated() []int32 {
+ if m != nil {
+ return m.F_Sint32Repeated
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Sint64Repeated() []int64 {
+ if m != nil {
+ return m.F_Sint64Repeated
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_BoolOptional() bool {
+ if m != nil && m.F_BoolOptional != nil {
+ return *m.F_BoolOptional
+ }
+ return false
+}
+
+func (m *GoTest) GetF_Int32Optional() int32 {
+ if m != nil && m.F_Int32Optional != nil {
+ return *m.F_Int32Optional
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_Int64Optional() int64 {
+ if m != nil && m.F_Int64Optional != nil {
+ return *m.F_Int64Optional
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_Fixed32Optional() uint32 {
+ if m != nil && m.F_Fixed32Optional != nil {
+ return *m.F_Fixed32Optional
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_Fixed64Optional() uint64 {
+ if m != nil && m.F_Fixed64Optional != nil {
+ return *m.F_Fixed64Optional
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_Uint32Optional() uint32 {
+ if m != nil && m.F_Uint32Optional != nil {
+ return *m.F_Uint32Optional
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_Uint64Optional() uint64 {
+ if m != nil && m.F_Uint64Optional != nil {
+ return *m.F_Uint64Optional
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_FloatOptional() float32 {
+ if m != nil && m.F_FloatOptional != nil {
+ return *m.F_FloatOptional
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_DoubleOptional() float64 {
+ if m != nil && m.F_DoubleOptional != nil {
+ return *m.F_DoubleOptional
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_StringOptional() string {
+ if m != nil && m.F_StringOptional != nil {
+ return *m.F_StringOptional
+ }
+ return ""
+}
+
+func (m *GoTest) GetF_BytesOptional() []byte {
+ if m != nil {
+ return m.F_BytesOptional
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Sint32Optional() int32 {
+ if m != nil && m.F_Sint32Optional != nil {
+ return *m.F_Sint32Optional
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_Sint64Optional() int64 {
+ if m != nil && m.F_Sint64Optional != nil {
+ return *m.F_Sint64Optional
+ }
+ return 0
+}
+
+func (m *GoTest) GetF_BoolDefaulted() bool {
+ if m != nil && m.F_BoolDefaulted != nil {
+ return *m.F_BoolDefaulted
+ }
+ return Default_GoTest_F_BoolDefaulted
+}
+
+func (m *GoTest) GetF_Int32Defaulted() int32 {
+ if m != nil && m.F_Int32Defaulted != nil {
+ return *m.F_Int32Defaulted
+ }
+ return Default_GoTest_F_Int32Defaulted
+}
+
+func (m *GoTest) GetF_Int64Defaulted() int64 {
+ if m != nil && m.F_Int64Defaulted != nil {
+ return *m.F_Int64Defaulted
+ }
+ return Default_GoTest_F_Int64Defaulted
+}
+
+func (m *GoTest) GetF_Fixed32Defaulted() uint32 {
+ if m != nil && m.F_Fixed32Defaulted != nil {
+ return *m.F_Fixed32Defaulted
+ }
+ return Default_GoTest_F_Fixed32Defaulted
+}
+
+func (m *GoTest) GetF_Fixed64Defaulted() uint64 {
+ if m != nil && m.F_Fixed64Defaulted != nil {
+ return *m.F_Fixed64Defaulted
+ }
+ return Default_GoTest_F_Fixed64Defaulted
+}
+
+func (m *GoTest) GetF_Uint32Defaulted() uint32 {
+ if m != nil && m.F_Uint32Defaulted != nil {
+ return *m.F_Uint32Defaulted
+ }
+ return Default_GoTest_F_Uint32Defaulted
+}
+
+func (m *GoTest) GetF_Uint64Defaulted() uint64 {
+ if m != nil && m.F_Uint64Defaulted != nil {
+ return *m.F_Uint64Defaulted
+ }
+ return Default_GoTest_F_Uint64Defaulted
+}
+
+func (m *GoTest) GetF_FloatDefaulted() float32 {
+ if m != nil && m.F_FloatDefaulted != nil {
+ return *m.F_FloatDefaulted
+ }
+ return Default_GoTest_F_FloatDefaulted
+}
+
+func (m *GoTest) GetF_DoubleDefaulted() float64 {
+ if m != nil && m.F_DoubleDefaulted != nil {
+ return *m.F_DoubleDefaulted
+ }
+ return Default_GoTest_F_DoubleDefaulted
+}
+
+func (m *GoTest) GetF_StringDefaulted() string {
+ if m != nil && m.F_StringDefaulted != nil {
+ return *m.F_StringDefaulted
+ }
+ return Default_GoTest_F_StringDefaulted
+}
+
+func (m *GoTest) GetF_BytesDefaulted() []byte {
+ if m != nil && m.F_BytesDefaulted != nil {
+ return m.F_BytesDefaulted
+ }
+ return append([]byte(nil), Default_GoTest_F_BytesDefaulted...)
+}
+
+func (m *GoTest) GetF_Sint32Defaulted() int32 {
+ if m != nil && m.F_Sint32Defaulted != nil {
+ return *m.F_Sint32Defaulted
+ }
+ return Default_GoTest_F_Sint32Defaulted
+}
+
+func (m *GoTest) GetF_Sint64Defaulted() int64 {
+ if m != nil && m.F_Sint64Defaulted != nil {
+ return *m.F_Sint64Defaulted
+ }
+ return Default_GoTest_F_Sint64Defaulted
+}
+
+func (m *GoTest) GetF_BoolRepeatedPacked() []bool {
+ if m != nil {
+ return m.F_BoolRepeatedPacked
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Int32RepeatedPacked() []int32 {
+ if m != nil {
+ return m.F_Int32RepeatedPacked
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Int64RepeatedPacked() []int64 {
+ if m != nil {
+ return m.F_Int64RepeatedPacked
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32 {
+ if m != nil {
+ return m.F_Fixed32RepeatedPacked
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64 {
+ if m != nil {
+ return m.F_Fixed64RepeatedPacked
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32 {
+ if m != nil {
+ return m.F_Uint32RepeatedPacked
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64 {
+ if m != nil {
+ return m.F_Uint64RepeatedPacked
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_FloatRepeatedPacked() []float32 {
+ if m != nil {
+ return m.F_FloatRepeatedPacked
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_DoubleRepeatedPacked() []float64 {
+ if m != nil {
+ return m.F_DoubleRepeatedPacked
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Sint32RepeatedPacked() []int32 {
+ if m != nil {
+ return m.F_Sint32RepeatedPacked
+ }
+ return nil
+}
+
+func (m *GoTest) GetF_Sint64RepeatedPacked() []int64 {
+ if m != nil {
+ return m.F_Sint64RepeatedPacked
+ }
+ return nil
+}
+
+func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup {
+ if m != nil {
+ return m.Requiredgroup
+ }
+ return nil
+}
+
+func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup {
+ if m != nil {
+ return m.Repeatedgroup
+ }
+ return nil
+}
+
+func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup {
+ if m != nil {
+ return m.Optionalgroup
+ }
+ return nil
+}
+
+// Required, repeated, and optional groups.
+type GoTest_RequiredGroup struct {
+ RequiredField *string `protobuf:"bytes,71,req,name=RequiredField" json:"RequiredField,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GoTest_RequiredGroup) Reset() { *m = GoTest_RequiredGroup{} }
+func (m *GoTest_RequiredGroup) String() string { return proto.CompactTextString(m) }
+func (*GoTest_RequiredGroup) ProtoMessage() {}
+func (*GoTest_RequiredGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 0} }
+
+func (m *GoTest_RequiredGroup) GetRequiredField() string {
+ if m != nil && m.RequiredField != nil {
+ return *m.RequiredField
+ }
+ return ""
+}
+
+type GoTest_RepeatedGroup struct {
+ RequiredField *string `protobuf:"bytes,81,req,name=RequiredField" json:"RequiredField,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GoTest_RepeatedGroup) Reset() { *m = GoTest_RepeatedGroup{} }
+func (m *GoTest_RepeatedGroup) String() string { return proto.CompactTextString(m) }
+func (*GoTest_RepeatedGroup) ProtoMessage() {}
+func (*GoTest_RepeatedGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 1} }
+
+func (m *GoTest_RepeatedGroup) GetRequiredField() string {
+ if m != nil && m.RequiredField != nil {
+ return *m.RequiredField
+ }
+ return ""
+}
+
+type GoTest_OptionalGroup struct {
+ RequiredField *string `protobuf:"bytes,91,req,name=RequiredField" json:"RequiredField,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GoTest_OptionalGroup) Reset() { *m = GoTest_OptionalGroup{} }
+func (m *GoTest_OptionalGroup) String() string { return proto.CompactTextString(m) }
+func (*GoTest_OptionalGroup) ProtoMessage() {}
+func (*GoTest_OptionalGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2, 2} }
+
+func (m *GoTest_OptionalGroup) GetRequiredField() string {
+ if m != nil && m.RequiredField != nil {
+ return *m.RequiredField
+ }
+ return ""
+}
+
+// For testing a group containing a required field.
+type GoTestRequiredGroupField struct {
+ Group *GoTestRequiredGroupField_Group `protobuf:"group,1,req,name=Group,json=group" json:"group,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GoTestRequiredGroupField) Reset() { *m = GoTestRequiredGroupField{} }
+func (m *GoTestRequiredGroupField) String() string { return proto.CompactTextString(m) }
+func (*GoTestRequiredGroupField) ProtoMessage() {}
+func (*GoTestRequiredGroupField) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
+
+func (m *GoTestRequiredGroupField) GetGroup() *GoTestRequiredGroupField_Group {
+ if m != nil {
+ return m.Group
+ }
+ return nil
+}
+
+type GoTestRequiredGroupField_Group struct {
+ Field *int32 `protobuf:"varint,2,req,name=Field" json:"Field,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GoTestRequiredGroupField_Group) Reset() { *m = GoTestRequiredGroupField_Group{} }
+func (m *GoTestRequiredGroupField_Group) String() string { return proto.CompactTextString(m) }
+func (*GoTestRequiredGroupField_Group) ProtoMessage() {}
+func (*GoTestRequiredGroupField_Group) Descriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{3, 0}
+}
+
+func (m *GoTestRequiredGroupField_Group) GetField() int32 {
+ if m != nil && m.Field != nil {
+ return *m.Field
+ }
+ return 0
+}
+
+// For testing skipping of unrecognized fields.
+// Numbers are all big, larger than tag numbers in GoTestField,
+// the message used in the corresponding test.
+type GoSkipTest struct {
+ SkipInt32 *int32 `protobuf:"varint,11,req,name=skip_int32,json=skipInt32" json:"skip_int32,omitempty"`
+ SkipFixed32 *uint32 `protobuf:"fixed32,12,req,name=skip_fixed32,json=skipFixed32" json:"skip_fixed32,omitempty"`
+ SkipFixed64 *uint64 `protobuf:"fixed64,13,req,name=skip_fixed64,json=skipFixed64" json:"skip_fixed64,omitempty"`
+ SkipString *string `protobuf:"bytes,14,req,name=skip_string,json=skipString" json:"skip_string,omitempty"`
+ Skipgroup *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup,json=skipgroup" json:"skipgroup,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GoSkipTest) Reset() { *m = GoSkipTest{} }
+func (m *GoSkipTest) String() string { return proto.CompactTextString(m) }
+func (*GoSkipTest) ProtoMessage() {}
+func (*GoSkipTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
+
+func (m *GoSkipTest) GetSkipInt32() int32 {
+ if m != nil && m.SkipInt32 != nil {
+ return *m.SkipInt32
+ }
+ return 0
+}
+
+func (m *GoSkipTest) GetSkipFixed32() uint32 {
+ if m != nil && m.SkipFixed32 != nil {
+ return *m.SkipFixed32
+ }
+ return 0
+}
+
+func (m *GoSkipTest) GetSkipFixed64() uint64 {
+ if m != nil && m.SkipFixed64 != nil {
+ return *m.SkipFixed64
+ }
+ return 0
+}
+
+func (m *GoSkipTest) GetSkipString() string {
+ if m != nil && m.SkipString != nil {
+ return *m.SkipString
+ }
+ return ""
+}
+
+func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup {
+ if m != nil {
+ return m.Skipgroup
+ }
+ return nil
+}
+
+type GoSkipTest_SkipGroup struct {
+ GroupInt32 *int32 `protobuf:"varint,16,req,name=group_int32,json=groupInt32" json:"group_int32,omitempty"`
+ GroupString *string `protobuf:"bytes,17,req,name=group_string,json=groupString" json:"group_string,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GoSkipTest_SkipGroup) Reset() { *m = GoSkipTest_SkipGroup{} }
+func (m *GoSkipTest_SkipGroup) String() string { return proto.CompactTextString(m) }
+func (*GoSkipTest_SkipGroup) ProtoMessage() {}
+func (*GoSkipTest_SkipGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4, 0} }
+
+func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32 {
+ if m != nil && m.GroupInt32 != nil {
+ return *m.GroupInt32
+ }
+ return 0
+}
+
+func (m *GoSkipTest_SkipGroup) GetGroupString() string {
+ if m != nil && m.GroupString != nil {
+ return *m.GroupString
+ }
+ return ""
+}
+
+// For testing packed/non-packed decoder switching.
+// A serialized instance of one should be deserializable as the other.
+type NonPackedTest struct {
+ A []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *NonPackedTest) Reset() { *m = NonPackedTest{} }
+func (m *NonPackedTest) String() string { return proto.CompactTextString(m) }
+func (*NonPackedTest) ProtoMessage() {}
+func (*NonPackedTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
+
+func (m *NonPackedTest) GetA() []int32 {
+ if m != nil {
+ return m.A
+ }
+ return nil
+}
+
+type PackedTest struct {
+ B []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *PackedTest) Reset() { *m = PackedTest{} }
+func (m *PackedTest) String() string { return proto.CompactTextString(m) }
+func (*PackedTest) ProtoMessage() {}
+func (*PackedTest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
+
+func (m *PackedTest) GetB() []int32 {
+ if m != nil {
+ return m.B
+ }
+ return nil
+}
+
+type MaxTag struct {
+ // Maximum possible tag number.
+ LastField *string `protobuf:"bytes,536870911,opt,name=last_field,json=lastField" json:"last_field,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MaxTag) Reset() { *m = MaxTag{} }
+func (m *MaxTag) String() string { return proto.CompactTextString(m) }
+func (*MaxTag) ProtoMessage() {}
+func (*MaxTag) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} }
+
+func (m *MaxTag) GetLastField() string {
+ if m != nil && m.LastField != nil {
+ return *m.LastField
+ }
+ return ""
+}
+
+type OldMessage struct {
+ Nested *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"`
+ Num *int32 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OldMessage) Reset() { *m = OldMessage{} }
+func (m *OldMessage) String() string { return proto.CompactTextString(m) }
+func (*OldMessage) ProtoMessage() {}
+func (*OldMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} }
+
+func (m *OldMessage) GetNested() *OldMessage_Nested {
+ if m != nil {
+ return m.Nested
+ }
+ return nil
+}
+
+func (m *OldMessage) GetNum() int32 {
+ if m != nil && m.Num != nil {
+ return *m.Num
+ }
+ return 0
+}
+
+type OldMessage_Nested struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OldMessage_Nested) Reset() { *m = OldMessage_Nested{} }
+func (m *OldMessage_Nested) String() string { return proto.CompactTextString(m) }
+func (*OldMessage_Nested) ProtoMessage() {}
+func (*OldMessage_Nested) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8, 0} }
+
+func (m *OldMessage_Nested) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+// NewMessage is wire compatible with OldMessage;
+// imagine it as a future version.
+type NewMessage struct {
+ Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"`
+ // This is an int32 in OldMessage.
+ Num *int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *NewMessage) Reset() { *m = NewMessage{} }
+func (m *NewMessage) String() string { return proto.CompactTextString(m) }
+func (*NewMessage) ProtoMessage() {}
+func (*NewMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} }
+
+func (m *NewMessage) GetNested() *NewMessage_Nested {
+ if m != nil {
+ return m.Nested
+ }
+ return nil
+}
+
+func (m *NewMessage) GetNum() int64 {
+ if m != nil && m.Num != nil {
+ return *m.Num
+ }
+ return 0
+}
+
+type NewMessage_Nested struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ FoodGroup *string `protobuf:"bytes,2,opt,name=food_group,json=foodGroup" json:"food_group,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *NewMessage_Nested) Reset() { *m = NewMessage_Nested{} }
+func (m *NewMessage_Nested) String() string { return proto.CompactTextString(m) }
+func (*NewMessage_Nested) ProtoMessage() {}
+func (*NewMessage_Nested) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9, 0} }
+
+func (m *NewMessage_Nested) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *NewMessage_Nested) GetFoodGroup() string {
+ if m != nil && m.FoodGroup != nil {
+ return *m.FoodGroup
+ }
+ return ""
+}
+
+type InnerMessage struct {
+ Host *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"`
+ Port *int32 `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"`
+ Connected *bool `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *InnerMessage) Reset() { *m = InnerMessage{} }
+func (m *InnerMessage) String() string { return proto.CompactTextString(m) }
+func (*InnerMessage) ProtoMessage() {}
+func (*InnerMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} }
+
+const Default_InnerMessage_Port int32 = 4000
+
+func (m *InnerMessage) GetHost() string {
+ if m != nil && m.Host != nil {
+ return *m.Host
+ }
+ return ""
+}
+
+func (m *InnerMessage) GetPort() int32 {
+ if m != nil && m.Port != nil {
+ return *m.Port
+ }
+ return Default_InnerMessage_Port
+}
+
+func (m *InnerMessage) GetConnected() bool {
+ if m != nil && m.Connected != nil {
+ return *m.Connected
+ }
+ return false
+}
+
+type OtherMessage struct {
+ Key *int64 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"`
+ Value []byte `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"`
+ Weight *float32 `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"`
+ Inner *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OtherMessage) Reset() { *m = OtherMessage{} }
+func (m *OtherMessage) String() string { return proto.CompactTextString(m) }
+func (*OtherMessage) ProtoMessage() {}
+func (*OtherMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} }
+
+var extRange_OtherMessage = []proto.ExtensionRange{
+ {100, 536870911},
+}
+
+func (*OtherMessage) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_OtherMessage
+}
+
+func (m *OtherMessage) GetKey() int64 {
+ if m != nil && m.Key != nil {
+ return *m.Key
+ }
+ return 0
+}
+
+func (m *OtherMessage) GetValue() []byte {
+ if m != nil {
+ return m.Value
+ }
+ return nil
+}
+
+func (m *OtherMessage) GetWeight() float32 {
+ if m != nil && m.Weight != nil {
+ return *m.Weight
+ }
+ return 0
+}
+
+func (m *OtherMessage) GetInner() *InnerMessage {
+ if m != nil {
+ return m.Inner
+ }
+ return nil
+}
+
+type RequiredInnerMessage struct {
+ LeoFinallyWonAnOscar *InnerMessage `protobuf:"bytes,1,req,name=leo_finally_won_an_oscar,json=leoFinallyWonAnOscar" json:"leo_finally_won_an_oscar,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *RequiredInnerMessage) Reset() { *m = RequiredInnerMessage{} }
+func (m *RequiredInnerMessage) String() string { return proto.CompactTextString(m) }
+func (*RequiredInnerMessage) ProtoMessage() {}
+func (*RequiredInnerMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} }
+
+func (m *RequiredInnerMessage) GetLeoFinallyWonAnOscar() *InnerMessage {
+ if m != nil {
+ return m.LeoFinallyWonAnOscar
+ }
+ return nil
+}
+
+type MyMessage struct {
+ Count *int32 `protobuf:"varint,1,req,name=count" json:"count,omitempty"`
+ Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"`
+ Quote *string `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"`
+ Pet []string `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"`
+ Inner *InnerMessage `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"`
+ Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"`
+ WeMustGoDeeper *RequiredInnerMessage `protobuf:"bytes,13,opt,name=we_must_go_deeper,json=weMustGoDeeper" json:"we_must_go_deeper,omitempty"`
+ RepInner []*InnerMessage `protobuf:"bytes,12,rep,name=rep_inner,json=repInner" json:"rep_inner,omitempty"`
+ Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=testdata.MyMessage_Color" json:"bikeshed,omitempty"`
+ Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"`
+ // This field becomes [][]byte in the generated code.
+ RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes,json=repBytes" json:"rep_bytes,omitempty"`
+ Bigfloat *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MyMessage) Reset() { *m = MyMessage{} }
+func (m *MyMessage) String() string { return proto.CompactTextString(m) }
+func (*MyMessage) ProtoMessage() {}
+func (*MyMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13} }
+
+var extRange_MyMessage = []proto.ExtensionRange{
+ {100, 536870911},
+}
+
+func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_MyMessage
+}
+
+func (m *MyMessage) GetCount() int32 {
+ if m != nil && m.Count != nil {
+ return *m.Count
+ }
+ return 0
+}
+
+func (m *MyMessage) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *MyMessage) GetQuote() string {
+ if m != nil && m.Quote != nil {
+ return *m.Quote
+ }
+ return ""
+}
+
+func (m *MyMessage) GetPet() []string {
+ if m != nil {
+ return m.Pet
+ }
+ return nil
+}
+
+func (m *MyMessage) GetInner() *InnerMessage {
+ if m != nil {
+ return m.Inner
+ }
+ return nil
+}
+
+func (m *MyMessage) GetOthers() []*OtherMessage {
+ if m != nil {
+ return m.Others
+ }
+ return nil
+}
+
+func (m *MyMessage) GetWeMustGoDeeper() *RequiredInnerMessage {
+ if m != nil {
+ return m.WeMustGoDeeper
+ }
+ return nil
+}
+
+func (m *MyMessage) GetRepInner() []*InnerMessage {
+ if m != nil {
+ return m.RepInner
+ }
+ return nil
+}
+
+func (m *MyMessage) GetBikeshed() MyMessage_Color {
+ if m != nil && m.Bikeshed != nil {
+ return *m.Bikeshed
+ }
+ return MyMessage_RED
+}
+
+func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup {
+ if m != nil {
+ return m.Somegroup
+ }
+ return nil
+}
+
+func (m *MyMessage) GetRepBytes() [][]byte {
+ if m != nil {
+ return m.RepBytes
+ }
+ return nil
+}
+
+func (m *MyMessage) GetBigfloat() float64 {
+ if m != nil && m.Bigfloat != nil {
+ return *m.Bigfloat
+ }
+ return 0
+}
+
+type MyMessage_SomeGroup struct {
+ GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MyMessage_SomeGroup) Reset() { *m = MyMessage_SomeGroup{} }
+func (m *MyMessage_SomeGroup) String() string { return proto.CompactTextString(m) }
+func (*MyMessage_SomeGroup) ProtoMessage() {}
+func (*MyMessage_SomeGroup) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13, 0} }
+
+func (m *MyMessage_SomeGroup) GetGroupField() int32 {
+ if m != nil && m.GroupField != nil {
+ return *m.GroupField
+ }
+ return 0
+}
+
+type Ext struct {
+ Data *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Ext) Reset() { *m = Ext{} }
+func (m *Ext) String() string { return proto.CompactTextString(m) }
+func (*Ext) ProtoMessage() {}
+func (*Ext) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{14} }
+
+func (m *Ext) GetData() string {
+ if m != nil && m.Data != nil {
+ return *m.Data
+ }
+ return ""
+}
+
+var E_Ext_More = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessage)(nil),
+ ExtensionType: (*Ext)(nil),
+ Field: 103,
+ Name: "testdata.Ext.more",
+ Tag: "bytes,103,opt,name=more",
+ Filename: "test.proto",
+}
+
+var E_Ext_Text = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessage)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 104,
+ Name: "testdata.Ext.text",
+ Tag: "bytes,104,opt,name=text",
+ Filename: "test.proto",
+}
+
+var E_Ext_Number = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessage)(nil),
+ ExtensionType: (*int32)(nil),
+ Field: 105,
+ Name: "testdata.Ext.number",
+ Tag: "varint,105,opt,name=number",
+ Filename: "test.proto",
+}
+
+type ComplexExtension struct {
+ First *int32 `protobuf:"varint,1,opt,name=first" json:"first,omitempty"`
+ Second *int32 `protobuf:"varint,2,opt,name=second" json:"second,omitempty"`
+ Third []int32 `protobuf:"varint,3,rep,name=third" json:"third,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *ComplexExtension) Reset() { *m = ComplexExtension{} }
+func (m *ComplexExtension) String() string { return proto.CompactTextString(m) }
+func (*ComplexExtension) ProtoMessage() {}
+func (*ComplexExtension) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} }
+
+func (m *ComplexExtension) GetFirst() int32 {
+ if m != nil && m.First != nil {
+ return *m.First
+ }
+ return 0
+}
+
+func (m *ComplexExtension) GetSecond() int32 {
+ if m != nil && m.Second != nil {
+ return *m.Second
+ }
+ return 0
+}
+
+func (m *ComplexExtension) GetThird() []int32 {
+ if m != nil {
+ return m.Third
+ }
+ return nil
+}
+
+type DefaultsMessage struct {
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *DefaultsMessage) Reset() { *m = DefaultsMessage{} }
+func (m *DefaultsMessage) String() string { return proto.CompactTextString(m) }
+func (*DefaultsMessage) ProtoMessage() {}
+func (*DefaultsMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} }
+
+var extRange_DefaultsMessage = []proto.ExtensionRange{
+ {100, 536870911},
+}
+
+func (*DefaultsMessage) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_DefaultsMessage
+}
+
+type MyMessageSet struct {
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MyMessageSet) Reset() { *m = MyMessageSet{} }
+func (m *MyMessageSet) String() string { return proto.CompactTextString(m) }
+func (*MyMessageSet) ProtoMessage() {}
+func (*MyMessageSet) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} }
+
+func (m *MyMessageSet) Marshal() ([]byte, error) {
+ return proto.MarshalMessageSet(&m.XXX_InternalExtensions)
+}
+func (m *MyMessageSet) Unmarshal(buf []byte) error {
+ return proto.UnmarshalMessageSet(buf, &m.XXX_InternalExtensions)
+}
+func (m *MyMessageSet) MarshalJSON() ([]byte, error) {
+ return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions)
+}
+func (m *MyMessageSet) UnmarshalJSON(buf []byte) error {
+ return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions)
+}
+
+// ensure MyMessageSet satisfies proto.Marshaler and proto.Unmarshaler
+var _ proto.Marshaler = (*MyMessageSet)(nil)
+var _ proto.Unmarshaler = (*MyMessageSet)(nil)
+
+var extRange_MyMessageSet = []proto.ExtensionRange{
+ {100, 2147483646},
+}
+
+func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_MyMessageSet
+}
+
+type Empty struct {
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Empty) Reset() { *m = Empty{} }
+func (m *Empty) String() string { return proto.CompactTextString(m) }
+func (*Empty) ProtoMessage() {}
+func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18} }
+
+type MessageList struct {
+ Message []*MessageList_Message `protobuf:"group,1,rep,name=Message,json=message" json:"message,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MessageList) Reset() { *m = MessageList{} }
+func (m *MessageList) String() string { return proto.CompactTextString(m) }
+func (*MessageList) ProtoMessage() {}
+func (*MessageList) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19} }
+
+func (m *MessageList) GetMessage() []*MessageList_Message {
+ if m != nil {
+ return m.Message
+ }
+ return nil
+}
+
+type MessageList_Message struct {
+ Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"`
+ Count *int32 `protobuf:"varint,3,req,name=count" json:"count,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MessageList_Message) Reset() { *m = MessageList_Message{} }
+func (m *MessageList_Message) String() string { return proto.CompactTextString(m) }
+func (*MessageList_Message) ProtoMessage() {}
+func (*MessageList_Message) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19, 0} }
+
+func (m *MessageList_Message) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *MessageList_Message) GetCount() int32 {
+ if m != nil && m.Count != nil {
+ return *m.Count
+ }
+ return 0
+}
+
+type Strings struct {
+ StringField *string `protobuf:"bytes,1,opt,name=string_field,json=stringField" json:"string_field,omitempty"`
+ BytesField []byte `protobuf:"bytes,2,opt,name=bytes_field,json=bytesField" json:"bytes_field,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Strings) Reset() { *m = Strings{} }
+func (m *Strings) String() string { return proto.CompactTextString(m) }
+func (*Strings) ProtoMessage() {}
+func (*Strings) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20} }
+
+func (m *Strings) GetStringField() string {
+ if m != nil && m.StringField != nil {
+ return *m.StringField
+ }
+ return ""
+}
+
+func (m *Strings) GetBytesField() []byte {
+ if m != nil {
+ return m.BytesField
+ }
+ return nil
+}
+
+type Defaults struct {
+ // Default-valued fields of all basic types.
+ // Same as GoTest, but copied here to make testing easier.
+ F_Bool *bool `protobuf:"varint,1,opt,name=F_Bool,json=FBool,def=1" json:"F_Bool,omitempty"`
+ F_Int32 *int32 `protobuf:"varint,2,opt,name=F_Int32,json=FInt32,def=32" json:"F_Int32,omitempty"`
+ F_Int64 *int64 `protobuf:"varint,3,opt,name=F_Int64,json=FInt64,def=64" json:"F_Int64,omitempty"`
+ F_Fixed32 *uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=FFixed32,def=320" json:"F_Fixed32,omitempty"`
+ F_Fixed64 *uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=FFixed64,def=640" json:"F_Fixed64,omitempty"`
+ F_Uint32 *uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=FUint32,def=3200" json:"F_Uint32,omitempty"`
+ F_Uint64 *uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=FUint64,def=6400" json:"F_Uint64,omitempty"`
+ F_Float *float32 `protobuf:"fixed32,8,opt,name=F_Float,json=FFloat,def=314159" json:"F_Float,omitempty"`
+ F_Double *float64 `protobuf:"fixed64,9,opt,name=F_Double,json=FDouble,def=271828" json:"F_Double,omitempty"`
+ F_String *string `protobuf:"bytes,10,opt,name=F_String,json=FString,def=hello, \"world!\"\n" json:"F_String,omitempty"`
+ F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=FBytes,def=Bignose" json:"F_Bytes,omitempty"`
+ F_Sint32 *int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=FSint32,def=-32" json:"F_Sint32,omitempty"`
+ F_Sint64 *int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=FSint64,def=-64" json:"F_Sint64,omitempty"`
+ F_Enum *Defaults_Color `protobuf:"varint,14,opt,name=F_Enum,json=FEnum,enum=testdata.Defaults_Color,def=1" json:"F_Enum,omitempty"`
+ // More fields with crazy defaults.
+ F_Pinf *float32 `protobuf:"fixed32,15,opt,name=F_Pinf,json=FPinf,def=inf" json:"F_Pinf,omitempty"`
+ F_Ninf *float32 `protobuf:"fixed32,16,opt,name=F_Ninf,json=FNinf,def=-inf" json:"F_Ninf,omitempty"`
+ F_Nan *float32 `protobuf:"fixed32,17,opt,name=F_Nan,json=FNan,def=nan" json:"F_Nan,omitempty"`
+ // Sub-message.
+ Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"`
+ // Redundant but explicit defaults.
+ StrZero *string `protobuf:"bytes,19,opt,name=str_zero,json=strZero,def=" json:"str_zero,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Defaults) Reset() { *m = Defaults{} }
+func (m *Defaults) String() string { return proto.CompactTextString(m) }
+func (*Defaults) ProtoMessage() {}
+func (*Defaults) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{21} }
+
+const Default_Defaults_F_Bool bool = true
+const Default_Defaults_F_Int32 int32 = 32
+const Default_Defaults_F_Int64 int64 = 64
+const Default_Defaults_F_Fixed32 uint32 = 320
+const Default_Defaults_F_Fixed64 uint64 = 640
+const Default_Defaults_F_Uint32 uint32 = 3200
+const Default_Defaults_F_Uint64 uint64 = 6400
+const Default_Defaults_F_Float float32 = 314159
+const Default_Defaults_F_Double float64 = 271828
+const Default_Defaults_F_String string = "hello, \"world!\"\n"
+
+var Default_Defaults_F_Bytes []byte = []byte("Bignose")
+
+const Default_Defaults_F_Sint32 int32 = -32
+const Default_Defaults_F_Sint64 int64 = -64
+const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN
+
+var Default_Defaults_F_Pinf float32 = float32(math.Inf(1))
+var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1))
+var Default_Defaults_F_Nan float32 = float32(math.NaN())
+
+func (m *Defaults) GetF_Bool() bool {
+ if m != nil && m.F_Bool != nil {
+ return *m.F_Bool
+ }
+ return Default_Defaults_F_Bool
+}
+
+func (m *Defaults) GetF_Int32() int32 {
+ if m != nil && m.F_Int32 != nil {
+ return *m.F_Int32
+ }
+ return Default_Defaults_F_Int32
+}
+
+func (m *Defaults) GetF_Int64() int64 {
+ if m != nil && m.F_Int64 != nil {
+ return *m.F_Int64
+ }
+ return Default_Defaults_F_Int64
+}
+
+func (m *Defaults) GetF_Fixed32() uint32 {
+ if m != nil && m.F_Fixed32 != nil {
+ return *m.F_Fixed32
+ }
+ return Default_Defaults_F_Fixed32
+}
+
+func (m *Defaults) GetF_Fixed64() uint64 {
+ if m != nil && m.F_Fixed64 != nil {
+ return *m.F_Fixed64
+ }
+ return Default_Defaults_F_Fixed64
+}
+
+func (m *Defaults) GetF_Uint32() uint32 {
+ if m != nil && m.F_Uint32 != nil {
+ return *m.F_Uint32
+ }
+ return Default_Defaults_F_Uint32
+}
+
+func (m *Defaults) GetF_Uint64() uint64 {
+ if m != nil && m.F_Uint64 != nil {
+ return *m.F_Uint64
+ }
+ return Default_Defaults_F_Uint64
+}
+
+func (m *Defaults) GetF_Float() float32 {
+ if m != nil && m.F_Float != nil {
+ return *m.F_Float
+ }
+ return Default_Defaults_F_Float
+}
+
+func (m *Defaults) GetF_Double() float64 {
+ if m != nil && m.F_Double != nil {
+ return *m.F_Double
+ }
+ return Default_Defaults_F_Double
+}
+
+func (m *Defaults) GetF_String() string {
+ if m != nil && m.F_String != nil {
+ return *m.F_String
+ }
+ return Default_Defaults_F_String
+}
+
+func (m *Defaults) GetF_Bytes() []byte {
+ if m != nil && m.F_Bytes != nil {
+ return m.F_Bytes
+ }
+ return append([]byte(nil), Default_Defaults_F_Bytes...)
+}
+
+func (m *Defaults) GetF_Sint32() int32 {
+ if m != nil && m.F_Sint32 != nil {
+ return *m.F_Sint32
+ }
+ return Default_Defaults_F_Sint32
+}
+
+func (m *Defaults) GetF_Sint64() int64 {
+ if m != nil && m.F_Sint64 != nil {
+ return *m.F_Sint64
+ }
+ return Default_Defaults_F_Sint64
+}
+
+func (m *Defaults) GetF_Enum() Defaults_Color {
+ if m != nil && m.F_Enum != nil {
+ return *m.F_Enum
+ }
+ return Default_Defaults_F_Enum
+}
+
+func (m *Defaults) GetF_Pinf() float32 {
+ if m != nil && m.F_Pinf != nil {
+ return *m.F_Pinf
+ }
+ return Default_Defaults_F_Pinf
+}
+
+func (m *Defaults) GetF_Ninf() float32 {
+ if m != nil && m.F_Ninf != nil {
+ return *m.F_Ninf
+ }
+ return Default_Defaults_F_Ninf
+}
+
+func (m *Defaults) GetF_Nan() float32 {
+ if m != nil && m.F_Nan != nil {
+ return *m.F_Nan
+ }
+ return Default_Defaults_F_Nan
+}
+
+func (m *Defaults) GetSub() *SubDefaults {
+ if m != nil {
+ return m.Sub
+ }
+ return nil
+}
+
+func (m *Defaults) GetStrZero() string {
+ if m != nil && m.StrZero != nil {
+ return *m.StrZero
+ }
+ return ""
+}
+
+type SubDefaults struct {
+ N *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *SubDefaults) Reset() { *m = SubDefaults{} }
+func (m *SubDefaults) String() string { return proto.CompactTextString(m) }
+func (*SubDefaults) ProtoMessage() {}
+func (*SubDefaults) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{22} }
+
+const Default_SubDefaults_N int64 = 7
+
+func (m *SubDefaults) GetN() int64 {
+ if m != nil && m.N != nil {
+ return *m.N
+ }
+ return Default_SubDefaults_N
+}
+
+type RepeatedEnum struct {
+ Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=testdata.RepeatedEnum_Color" json:"color,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *RepeatedEnum) Reset() { *m = RepeatedEnum{} }
+func (m *RepeatedEnum) String() string { return proto.CompactTextString(m) }
+func (*RepeatedEnum) ProtoMessage() {}
+func (*RepeatedEnum) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{23} }
+
+func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color {
+ if m != nil {
+ return m.Color
+ }
+ return nil
+}
+
+type MoreRepeated struct {
+ Bools []bool `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"`
+ BoolsPacked []bool `protobuf:"varint,2,rep,packed,name=bools_packed,json=boolsPacked" json:"bools_packed,omitempty"`
+ Ints []int32 `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"`
+ IntsPacked []int32 `protobuf:"varint,4,rep,packed,name=ints_packed,json=intsPacked" json:"ints_packed,omitempty"`
+ Int64SPacked []int64 `protobuf:"varint,7,rep,packed,name=int64s_packed,json=int64sPacked" json:"int64s_packed,omitempty"`
+ Strings []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"`
+ Fixeds []uint32 `protobuf:"fixed32,6,rep,name=fixeds" json:"fixeds,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MoreRepeated) Reset() { *m = MoreRepeated{} }
+func (m *MoreRepeated) String() string { return proto.CompactTextString(m) }
+func (*MoreRepeated) ProtoMessage() {}
+func (*MoreRepeated) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{24} }
+
+func (m *MoreRepeated) GetBools() []bool {
+ if m != nil {
+ return m.Bools
+ }
+ return nil
+}
+
+func (m *MoreRepeated) GetBoolsPacked() []bool {
+ if m != nil {
+ return m.BoolsPacked
+ }
+ return nil
+}
+
+func (m *MoreRepeated) GetInts() []int32 {
+ if m != nil {
+ return m.Ints
+ }
+ return nil
+}
+
+func (m *MoreRepeated) GetIntsPacked() []int32 {
+ if m != nil {
+ return m.IntsPacked
+ }
+ return nil
+}
+
+func (m *MoreRepeated) GetInt64SPacked() []int64 {
+ if m != nil {
+ return m.Int64SPacked
+ }
+ return nil
+}
+
+func (m *MoreRepeated) GetStrings() []string {
+ if m != nil {
+ return m.Strings
+ }
+ return nil
+}
+
+func (m *MoreRepeated) GetFixeds() []uint32 {
+ if m != nil {
+ return m.Fixeds
+ }
+ return nil
+}
+
+type GroupOld struct {
+ G *GroupOld_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GroupOld) Reset() { *m = GroupOld{} }
+func (m *GroupOld) String() string { return proto.CompactTextString(m) }
+func (*GroupOld) ProtoMessage() {}
+func (*GroupOld) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{25} }
+
+func (m *GroupOld) GetG() *GroupOld_G {
+ if m != nil {
+ return m.G
+ }
+ return nil
+}
+
+type GroupOld_G struct {
+ X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GroupOld_G) Reset() { *m = GroupOld_G{} }
+func (m *GroupOld_G) String() string { return proto.CompactTextString(m) }
+func (*GroupOld_G) ProtoMessage() {}
+func (*GroupOld_G) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{25, 0} }
+
+func (m *GroupOld_G) GetX() int32 {
+ if m != nil && m.X != nil {
+ return *m.X
+ }
+ return 0
+}
+
+type GroupNew struct {
+ G *GroupNew_G `protobuf:"group,101,opt,name=G,json=g" json:"g,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GroupNew) Reset() { *m = GroupNew{} }
+func (m *GroupNew) String() string { return proto.CompactTextString(m) }
+func (*GroupNew) ProtoMessage() {}
+func (*GroupNew) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{26} }
+
+func (m *GroupNew) GetG() *GroupNew_G {
+ if m != nil {
+ return m.G
+ }
+ return nil
+}
+
+type GroupNew_G struct {
+ X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"`
+ Y *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GroupNew_G) Reset() { *m = GroupNew_G{} }
+func (m *GroupNew_G) String() string { return proto.CompactTextString(m) }
+func (*GroupNew_G) ProtoMessage() {}
+func (*GroupNew_G) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{26, 0} }
+
+func (m *GroupNew_G) GetX() int32 {
+ if m != nil && m.X != nil {
+ return *m.X
+ }
+ return 0
+}
+
+func (m *GroupNew_G) GetY() int32 {
+ if m != nil && m.Y != nil {
+ return *m.Y
+ }
+ return 0
+}
+
+type FloatingPoint struct {
+ F *float64 `protobuf:"fixed64,1,req,name=f" json:"f,omitempty"`
+ Exact *bool `protobuf:"varint,2,opt,name=exact" json:"exact,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FloatingPoint) Reset() { *m = FloatingPoint{} }
+func (m *FloatingPoint) String() string { return proto.CompactTextString(m) }
+func (*FloatingPoint) ProtoMessage() {}
+func (*FloatingPoint) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{27} }
+
+func (m *FloatingPoint) GetF() float64 {
+ if m != nil && m.F != nil {
+ return *m.F
+ }
+ return 0
+}
+
+func (m *FloatingPoint) GetExact() bool {
+ if m != nil && m.Exact != nil {
+ return *m.Exact
+ }
+ return false
+}
+
+type MessageWithMap struct {
+ NameMapping map[int32]string `protobuf:"bytes,1,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ MsgMapping map[int64]*FloatingPoint `protobuf:"bytes,2,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ ByteMapping map[bool][]byte `protobuf:"bytes,3,rep,name=byte_mapping,json=byteMapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ StrToStr map[string]string `protobuf:"bytes,4,rep,name=str_to_str,json=strToStr" json:"str_to_str,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MessageWithMap) Reset() { *m = MessageWithMap{} }
+func (m *MessageWithMap) String() string { return proto.CompactTextString(m) }
+func (*MessageWithMap) ProtoMessage() {}
+func (*MessageWithMap) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{28} }
+
+func (m *MessageWithMap) GetNameMapping() map[int32]string {
+ if m != nil {
+ return m.NameMapping
+ }
+ return nil
+}
+
+func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint {
+ if m != nil {
+ return m.MsgMapping
+ }
+ return nil
+}
+
+func (m *MessageWithMap) GetByteMapping() map[bool][]byte {
+ if m != nil {
+ return m.ByteMapping
+ }
+ return nil
+}
+
+func (m *MessageWithMap) GetStrToStr() map[string]string {
+ if m != nil {
+ return m.StrToStr
+ }
+ return nil
+}
+
+type Oneof struct {
+ // Types that are valid to be assigned to Union:
+ // *Oneof_F_Bool
+ // *Oneof_F_Int32
+ // *Oneof_F_Int64
+ // *Oneof_F_Fixed32
+ // *Oneof_F_Fixed64
+ // *Oneof_F_Uint32
+ // *Oneof_F_Uint64
+ // *Oneof_F_Float
+ // *Oneof_F_Double
+ // *Oneof_F_String
+ // *Oneof_F_Bytes
+ // *Oneof_F_Sint32
+ // *Oneof_F_Sint64
+ // *Oneof_F_Enum
+ // *Oneof_F_Message
+ // *Oneof_FGroup
+ // *Oneof_F_Largest_Tag
+ Union isOneof_Union `protobuf_oneof:"union"`
+ // Types that are valid to be assigned to Tormato:
+ // *Oneof_Value
+ Tormato isOneof_Tormato `protobuf_oneof:"tormato"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Oneof) Reset() { *m = Oneof{} }
+func (m *Oneof) String() string { return proto.CompactTextString(m) }
+func (*Oneof) ProtoMessage() {}
+func (*Oneof) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{29} }
+
+type isOneof_Union interface {
+ isOneof_Union()
+}
+type isOneof_Tormato interface {
+ isOneof_Tormato()
+}
+
+type Oneof_F_Bool struct {
+ F_Bool bool `protobuf:"varint,1,opt,name=F_Bool,json=FBool,oneof"`
+}
+type Oneof_F_Int32 struct {
+ F_Int32 int32 `protobuf:"varint,2,opt,name=F_Int32,json=FInt32,oneof"`
+}
+type Oneof_F_Int64 struct {
+ F_Int64 int64 `protobuf:"varint,3,opt,name=F_Int64,json=FInt64,oneof"`
+}
+type Oneof_F_Fixed32 struct {
+ F_Fixed32 uint32 `protobuf:"fixed32,4,opt,name=F_Fixed32,json=FFixed32,oneof"`
+}
+type Oneof_F_Fixed64 struct {
+ F_Fixed64 uint64 `protobuf:"fixed64,5,opt,name=F_Fixed64,json=FFixed64,oneof"`
+}
+type Oneof_F_Uint32 struct {
+ F_Uint32 uint32 `protobuf:"varint,6,opt,name=F_Uint32,json=FUint32,oneof"`
+}
+type Oneof_F_Uint64 struct {
+ F_Uint64 uint64 `protobuf:"varint,7,opt,name=F_Uint64,json=FUint64,oneof"`
+}
+type Oneof_F_Float struct {
+ F_Float float32 `protobuf:"fixed32,8,opt,name=F_Float,json=FFloat,oneof"`
+}
+type Oneof_F_Double struct {
+ F_Double float64 `protobuf:"fixed64,9,opt,name=F_Double,json=FDouble,oneof"`
+}
+type Oneof_F_String struct {
+ F_String string `protobuf:"bytes,10,opt,name=F_String,json=FString,oneof"`
+}
+type Oneof_F_Bytes struct {
+ F_Bytes []byte `protobuf:"bytes,11,opt,name=F_Bytes,json=FBytes,oneof"`
+}
+type Oneof_F_Sint32 struct {
+ F_Sint32 int32 `protobuf:"zigzag32,12,opt,name=F_Sint32,json=FSint32,oneof"`
+}
+type Oneof_F_Sint64 struct {
+ F_Sint64 int64 `protobuf:"zigzag64,13,opt,name=F_Sint64,json=FSint64,oneof"`
+}
+type Oneof_F_Enum struct {
+ F_Enum MyMessage_Color `protobuf:"varint,14,opt,name=F_Enum,json=FEnum,enum=testdata.MyMessage_Color,oneof"`
+}
+type Oneof_F_Message struct {
+ F_Message *GoTestField `protobuf:"bytes,15,opt,name=F_Message,json=FMessage,oneof"`
+}
+type Oneof_FGroup struct {
+ FGroup *Oneof_F_Group `protobuf:"group,16,opt,name=F_Group,json=fGroup,oneof"`
+}
+type Oneof_F_Largest_Tag struct {
+ F_Largest_Tag int32 `protobuf:"varint,536870911,opt,name=F_Largest_Tag,json=FLargestTag,oneof"`
+}
+type Oneof_Value struct {
+ Value int32 `protobuf:"varint,100,opt,name=value,oneof"`
+}
+
+func (*Oneof_F_Bool) isOneof_Union() {}
+func (*Oneof_F_Int32) isOneof_Union() {}
+func (*Oneof_F_Int64) isOneof_Union() {}
+func (*Oneof_F_Fixed32) isOneof_Union() {}
+func (*Oneof_F_Fixed64) isOneof_Union() {}
+func (*Oneof_F_Uint32) isOneof_Union() {}
+func (*Oneof_F_Uint64) isOneof_Union() {}
+func (*Oneof_F_Float) isOneof_Union() {}
+func (*Oneof_F_Double) isOneof_Union() {}
+func (*Oneof_F_String) isOneof_Union() {}
+func (*Oneof_F_Bytes) isOneof_Union() {}
+func (*Oneof_F_Sint32) isOneof_Union() {}
+func (*Oneof_F_Sint64) isOneof_Union() {}
+func (*Oneof_F_Enum) isOneof_Union() {}
+func (*Oneof_F_Message) isOneof_Union() {}
+func (*Oneof_FGroup) isOneof_Union() {}
+func (*Oneof_F_Largest_Tag) isOneof_Union() {}
+func (*Oneof_Value) isOneof_Tormato() {}
+
+func (m *Oneof) GetUnion() isOneof_Union {
+ if m != nil {
+ return m.Union
+ }
+ return nil
+}
+func (m *Oneof) GetTormato() isOneof_Tormato {
+ if m != nil {
+ return m.Tormato
+ }
+ return nil
+}
+
+func (m *Oneof) GetF_Bool() bool {
+ if x, ok := m.GetUnion().(*Oneof_F_Bool); ok {
+ return x.F_Bool
+ }
+ return false
+}
+
+func (m *Oneof) GetF_Int32() int32 {
+ if x, ok := m.GetUnion().(*Oneof_F_Int32); ok {
+ return x.F_Int32
+ }
+ return 0
+}
+
+func (m *Oneof) GetF_Int64() int64 {
+ if x, ok := m.GetUnion().(*Oneof_F_Int64); ok {
+ return x.F_Int64
+ }
+ return 0
+}
+
+func (m *Oneof) GetF_Fixed32() uint32 {
+ if x, ok := m.GetUnion().(*Oneof_F_Fixed32); ok {
+ return x.F_Fixed32
+ }
+ return 0
+}
+
+func (m *Oneof) GetF_Fixed64() uint64 {
+ if x, ok := m.GetUnion().(*Oneof_F_Fixed64); ok {
+ return x.F_Fixed64
+ }
+ return 0
+}
+
+func (m *Oneof) GetF_Uint32() uint32 {
+ if x, ok := m.GetUnion().(*Oneof_F_Uint32); ok {
+ return x.F_Uint32
+ }
+ return 0
+}
+
+func (m *Oneof) GetF_Uint64() uint64 {
+ if x, ok := m.GetUnion().(*Oneof_F_Uint64); ok {
+ return x.F_Uint64
+ }
+ return 0
+}
+
+func (m *Oneof) GetF_Float() float32 {
+ if x, ok := m.GetUnion().(*Oneof_F_Float); ok {
+ return x.F_Float
+ }
+ return 0
+}
+
+func (m *Oneof) GetF_Double() float64 {
+ if x, ok := m.GetUnion().(*Oneof_F_Double); ok {
+ return x.F_Double
+ }
+ return 0
+}
+
+func (m *Oneof) GetF_String() string {
+ if x, ok := m.GetUnion().(*Oneof_F_String); ok {
+ return x.F_String
+ }
+ return ""
+}
+
+func (m *Oneof) GetF_Bytes() []byte {
+ if x, ok := m.GetUnion().(*Oneof_F_Bytes); ok {
+ return x.F_Bytes
+ }
+ return nil
+}
+
+func (m *Oneof) GetF_Sint32() int32 {
+ if x, ok := m.GetUnion().(*Oneof_F_Sint32); ok {
+ return x.F_Sint32
+ }
+ return 0
+}
+
+func (m *Oneof) GetF_Sint64() int64 {
+ if x, ok := m.GetUnion().(*Oneof_F_Sint64); ok {
+ return x.F_Sint64
+ }
+ return 0
+}
+
+func (m *Oneof) GetF_Enum() MyMessage_Color {
+ if x, ok := m.GetUnion().(*Oneof_F_Enum); ok {
+ return x.F_Enum
+ }
+ return MyMessage_RED
+}
+
+func (m *Oneof) GetF_Message() *GoTestField {
+ if x, ok := m.GetUnion().(*Oneof_F_Message); ok {
+ return x.F_Message
+ }
+ return nil
+}
+
+func (m *Oneof) GetFGroup() *Oneof_F_Group {
+ if x, ok := m.GetUnion().(*Oneof_FGroup); ok {
+ return x.FGroup
+ }
+ return nil
+}
+
+func (m *Oneof) GetF_Largest_Tag() int32 {
+ if x, ok := m.GetUnion().(*Oneof_F_Largest_Tag); ok {
+ return x.F_Largest_Tag
+ }
+ return 0
+}
+
+func (m *Oneof) GetValue() int32 {
+ if x, ok := m.GetTormato().(*Oneof_Value); ok {
+ return x.Value
+ }
+ return 0
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*Oneof) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _Oneof_OneofMarshaler, _Oneof_OneofUnmarshaler, _Oneof_OneofSizer, []interface{}{
+ (*Oneof_F_Bool)(nil),
+ (*Oneof_F_Int32)(nil),
+ (*Oneof_F_Int64)(nil),
+ (*Oneof_F_Fixed32)(nil),
+ (*Oneof_F_Fixed64)(nil),
+ (*Oneof_F_Uint32)(nil),
+ (*Oneof_F_Uint64)(nil),
+ (*Oneof_F_Float)(nil),
+ (*Oneof_F_Double)(nil),
+ (*Oneof_F_String)(nil),
+ (*Oneof_F_Bytes)(nil),
+ (*Oneof_F_Sint32)(nil),
+ (*Oneof_F_Sint64)(nil),
+ (*Oneof_F_Enum)(nil),
+ (*Oneof_F_Message)(nil),
+ (*Oneof_FGroup)(nil),
+ (*Oneof_F_Largest_Tag)(nil),
+ (*Oneof_Value)(nil),
+ }
+}
+
+func _Oneof_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*Oneof)
+ // union
+ switch x := m.Union.(type) {
+ case *Oneof_F_Bool:
+ t := uint64(0)
+ if x.F_Bool {
+ t = 1
+ }
+ b.EncodeVarint(1<<3 | proto.WireVarint)
+ b.EncodeVarint(t)
+ case *Oneof_F_Int32:
+ b.EncodeVarint(2<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.F_Int32))
+ case *Oneof_F_Int64:
+ b.EncodeVarint(3<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.F_Int64))
+ case *Oneof_F_Fixed32:
+ b.EncodeVarint(4<<3 | proto.WireFixed32)
+ b.EncodeFixed32(uint64(x.F_Fixed32))
+ case *Oneof_F_Fixed64:
+ b.EncodeVarint(5<<3 | proto.WireFixed64)
+ b.EncodeFixed64(uint64(x.F_Fixed64))
+ case *Oneof_F_Uint32:
+ b.EncodeVarint(6<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.F_Uint32))
+ case *Oneof_F_Uint64:
+ b.EncodeVarint(7<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.F_Uint64))
+ case *Oneof_F_Float:
+ b.EncodeVarint(8<<3 | proto.WireFixed32)
+ b.EncodeFixed32(uint64(math.Float32bits(x.F_Float)))
+ case *Oneof_F_Double:
+ b.EncodeVarint(9<<3 | proto.WireFixed64)
+ b.EncodeFixed64(math.Float64bits(x.F_Double))
+ case *Oneof_F_String:
+ b.EncodeVarint(10<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.F_String)
+ case *Oneof_F_Bytes:
+ b.EncodeVarint(11<<3 | proto.WireBytes)
+ b.EncodeRawBytes(x.F_Bytes)
+ case *Oneof_F_Sint32:
+ b.EncodeVarint(12<<3 | proto.WireVarint)
+ b.EncodeZigzag32(uint64(x.F_Sint32))
+ case *Oneof_F_Sint64:
+ b.EncodeVarint(13<<3 | proto.WireVarint)
+ b.EncodeZigzag64(uint64(x.F_Sint64))
+ case *Oneof_F_Enum:
+ b.EncodeVarint(14<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.F_Enum))
+ case *Oneof_F_Message:
+ b.EncodeVarint(15<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.F_Message); err != nil {
+ return err
+ }
+ case *Oneof_FGroup:
+ b.EncodeVarint(16<<3 | proto.WireStartGroup)
+ if err := b.Marshal(x.FGroup); err != nil {
+ return err
+ }
+ b.EncodeVarint(16<<3 | proto.WireEndGroup)
+ case *Oneof_F_Largest_Tag:
+ b.EncodeVarint(536870911<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.F_Largest_Tag))
+ case nil:
+ default:
+ return fmt.Errorf("Oneof.Union has unexpected type %T", x)
+ }
+ // tormato
+ switch x := m.Tormato.(type) {
+ case *Oneof_Value:
+ b.EncodeVarint(100<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.Value))
+ case nil:
+ default:
+ return fmt.Errorf("Oneof.Tormato has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _Oneof_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*Oneof)
+ switch tag {
+ case 1: // union.F_Bool
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Oneof_F_Bool{x != 0}
+ return true, err
+ case 2: // union.F_Int32
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Oneof_F_Int32{int32(x)}
+ return true, err
+ case 3: // union.F_Int64
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Oneof_F_Int64{int64(x)}
+ return true, err
+ case 4: // union.F_Fixed32
+ if wire != proto.WireFixed32 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed32()
+ m.Union = &Oneof_F_Fixed32{uint32(x)}
+ return true, err
+ case 5: // union.F_Fixed64
+ if wire != proto.WireFixed64 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed64()
+ m.Union = &Oneof_F_Fixed64{x}
+ return true, err
+ case 6: // union.F_Uint32
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Oneof_F_Uint32{uint32(x)}
+ return true, err
+ case 7: // union.F_Uint64
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Oneof_F_Uint64{x}
+ return true, err
+ case 8: // union.F_Float
+ if wire != proto.WireFixed32 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed32()
+ m.Union = &Oneof_F_Float{math.Float32frombits(uint32(x))}
+ return true, err
+ case 9: // union.F_Double
+ if wire != proto.WireFixed64 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed64()
+ m.Union = &Oneof_F_Double{math.Float64frombits(x)}
+ return true, err
+ case 10: // union.F_String
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Union = &Oneof_F_String{x}
+ return true, err
+ case 11: // union.F_Bytes
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeRawBytes(true)
+ m.Union = &Oneof_F_Bytes{x}
+ return true, err
+ case 12: // union.F_Sint32
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeZigzag32()
+ m.Union = &Oneof_F_Sint32{int32(x)}
+ return true, err
+ case 13: // union.F_Sint64
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeZigzag64()
+ m.Union = &Oneof_F_Sint64{int64(x)}
+ return true, err
+ case 14: // union.F_Enum
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Oneof_F_Enum{MyMessage_Color(x)}
+ return true, err
+ case 15: // union.F_Message
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(GoTestField)
+ err := b.DecodeMessage(msg)
+ m.Union = &Oneof_F_Message{msg}
+ return true, err
+ case 16: // union.f_group
+ if wire != proto.WireStartGroup {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Oneof_F_Group)
+ err := b.DecodeGroup(msg)
+ m.Union = &Oneof_FGroup{msg}
+ return true, err
+ case 536870911: // union.F_Largest_Tag
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Oneof_F_Largest_Tag{int32(x)}
+ return true, err
+ case 100: // tormato.value
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Tormato = &Oneof_Value{int32(x)}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _Oneof_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*Oneof)
+ // union
+ switch x := m.Union.(type) {
+ case *Oneof_F_Bool:
+ n += proto.SizeVarint(1<<3 | proto.WireVarint)
+ n += 1
+ case *Oneof_F_Int32:
+ n += proto.SizeVarint(2<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.F_Int32))
+ case *Oneof_F_Int64:
+ n += proto.SizeVarint(3<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.F_Int64))
+ case *Oneof_F_Fixed32:
+ n += proto.SizeVarint(4<<3 | proto.WireFixed32)
+ n += 4
+ case *Oneof_F_Fixed64:
+ n += proto.SizeVarint(5<<3 | proto.WireFixed64)
+ n += 8
+ case *Oneof_F_Uint32:
+ n += proto.SizeVarint(6<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.F_Uint32))
+ case *Oneof_F_Uint64:
+ n += proto.SizeVarint(7<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.F_Uint64))
+ case *Oneof_F_Float:
+ n += proto.SizeVarint(8<<3 | proto.WireFixed32)
+ n += 4
+ case *Oneof_F_Double:
+ n += proto.SizeVarint(9<<3 | proto.WireFixed64)
+ n += 8
+ case *Oneof_F_String:
+ n += proto.SizeVarint(10<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.F_String)))
+ n += len(x.F_String)
+ case *Oneof_F_Bytes:
+ n += proto.SizeVarint(11<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.F_Bytes)))
+ n += len(x.F_Bytes)
+ case *Oneof_F_Sint32:
+ n += proto.SizeVarint(12<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64((uint32(x.F_Sint32) << 1) ^ uint32((int32(x.F_Sint32) >> 31))))
+ case *Oneof_F_Sint64:
+ n += proto.SizeVarint(13<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(uint64(x.F_Sint64<<1) ^ uint64((int64(x.F_Sint64) >> 63))))
+ case *Oneof_F_Enum:
+ n += proto.SizeVarint(14<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.F_Enum))
+ case *Oneof_F_Message:
+ s := proto.Size(x.F_Message)
+ n += proto.SizeVarint(15<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Oneof_FGroup:
+ n += proto.SizeVarint(16<<3 | proto.WireStartGroup)
+ n += proto.Size(x.FGroup)
+ n += proto.SizeVarint(16<<3 | proto.WireEndGroup)
+ case *Oneof_F_Largest_Tag:
+ n += proto.SizeVarint(536870911<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.F_Largest_Tag))
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ // tormato
+ switch x := m.Tormato.(type) {
+ case *Oneof_Value:
+ n += proto.SizeVarint(100<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.Value))
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+type Oneof_F_Group struct {
+ X *int32 `protobuf:"varint,17,opt,name=x" json:"x,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Oneof_F_Group) Reset() { *m = Oneof_F_Group{} }
+func (m *Oneof_F_Group) String() string { return proto.CompactTextString(m) }
+func (*Oneof_F_Group) ProtoMessage() {}
+func (*Oneof_F_Group) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{29, 0} }
+
+func (m *Oneof_F_Group) GetX() int32 {
+ if m != nil && m.X != nil {
+ return *m.X
+ }
+ return 0
+}
+
+type Communique struct {
+ MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"`
+ // This is a oneof, called "union".
+ //
+ // Types that are valid to be assigned to Union:
+ // *Communique_Number
+ // *Communique_Name
+ // *Communique_Data
+ // *Communique_TempC
+ // *Communique_Col
+ // *Communique_Msg
+ Union isCommunique_Union `protobuf_oneof:"union"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Communique) Reset() { *m = Communique{} }
+func (m *Communique) String() string { return proto.CompactTextString(m) }
+func (*Communique) ProtoMessage() {}
+func (*Communique) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{30} }
+
+type isCommunique_Union interface {
+ isCommunique_Union()
+}
+
+type Communique_Number struct {
+ Number int32 `protobuf:"varint,5,opt,name=number,oneof"`
+}
+type Communique_Name struct {
+ Name string `protobuf:"bytes,6,opt,name=name,oneof"`
+}
+type Communique_Data struct {
+ Data []byte `protobuf:"bytes,7,opt,name=data,oneof"`
+}
+type Communique_TempC struct {
+ TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"`
+}
+type Communique_Col struct {
+ Col MyMessage_Color `protobuf:"varint,9,opt,name=col,enum=testdata.MyMessage_Color,oneof"`
+}
+type Communique_Msg struct {
+ Msg *Strings `protobuf:"bytes,10,opt,name=msg,oneof"`
+}
+
+func (*Communique_Number) isCommunique_Union() {}
+func (*Communique_Name) isCommunique_Union() {}
+func (*Communique_Data) isCommunique_Union() {}
+func (*Communique_TempC) isCommunique_Union() {}
+func (*Communique_Col) isCommunique_Union() {}
+func (*Communique_Msg) isCommunique_Union() {}
+
+func (m *Communique) GetUnion() isCommunique_Union {
+ if m != nil {
+ return m.Union
+ }
+ return nil
+}
+
+func (m *Communique) GetMakeMeCry() bool {
+ if m != nil && m.MakeMeCry != nil {
+ return *m.MakeMeCry
+ }
+ return false
+}
+
+func (m *Communique) GetNumber() int32 {
+ if x, ok := m.GetUnion().(*Communique_Number); ok {
+ return x.Number
+ }
+ return 0
+}
+
+func (m *Communique) GetName() string {
+ if x, ok := m.GetUnion().(*Communique_Name); ok {
+ return x.Name
+ }
+ return ""
+}
+
+func (m *Communique) GetData() []byte {
+ if x, ok := m.GetUnion().(*Communique_Data); ok {
+ return x.Data
+ }
+ return nil
+}
+
+func (m *Communique) GetTempC() float64 {
+ if x, ok := m.GetUnion().(*Communique_TempC); ok {
+ return x.TempC
+ }
+ return 0
+}
+
+func (m *Communique) GetCol() MyMessage_Color {
+ if x, ok := m.GetUnion().(*Communique_Col); ok {
+ return x.Col
+ }
+ return MyMessage_RED
+}
+
+func (m *Communique) GetMsg() *Strings {
+ if x, ok := m.GetUnion().(*Communique_Msg); ok {
+ return x.Msg
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{
+ (*Communique_Number)(nil),
+ (*Communique_Name)(nil),
+ (*Communique_Data)(nil),
+ (*Communique_TempC)(nil),
+ (*Communique_Col)(nil),
+ (*Communique_Msg)(nil),
+ }
+}
+
+func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*Communique)
+ // union
+ switch x := m.Union.(type) {
+ case *Communique_Number:
+ b.EncodeVarint(5<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.Number))
+ case *Communique_Name:
+ b.EncodeVarint(6<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.Name)
+ case *Communique_Data:
+ b.EncodeVarint(7<<3 | proto.WireBytes)
+ b.EncodeRawBytes(x.Data)
+ case *Communique_TempC:
+ b.EncodeVarint(8<<3 | proto.WireFixed64)
+ b.EncodeFixed64(math.Float64bits(x.TempC))
+ case *Communique_Col:
+ b.EncodeVarint(9<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.Col))
+ case *Communique_Msg:
+ b.EncodeVarint(10<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Msg); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("Communique.Union has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*Communique)
+ switch tag {
+ case 5: // union.number
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Communique_Number{int32(x)}
+ return true, err
+ case 6: // union.name
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Union = &Communique_Name{x}
+ return true, err
+ case 7: // union.data
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeRawBytes(true)
+ m.Union = &Communique_Data{x}
+ return true, err
+ case 8: // union.temp_c
+ if wire != proto.WireFixed64 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed64()
+ m.Union = &Communique_TempC{math.Float64frombits(x)}
+ return true, err
+ case 9: // union.col
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Communique_Col{MyMessage_Color(x)}
+ return true, err
+ case 10: // union.msg
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Strings)
+ err := b.DecodeMessage(msg)
+ m.Union = &Communique_Msg{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _Communique_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*Communique)
+ // union
+ switch x := m.Union.(type) {
+ case *Communique_Number:
+ n += proto.SizeVarint(5<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.Number))
+ case *Communique_Name:
+ n += proto.SizeVarint(6<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Name)))
+ n += len(x.Name)
+ case *Communique_Data:
+ n += proto.SizeVarint(7<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Data)))
+ n += len(x.Data)
+ case *Communique_TempC:
+ n += proto.SizeVarint(8<<3 | proto.WireFixed64)
+ n += 8
+ case *Communique_Col:
+ n += proto.SizeVarint(9<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.Col))
+ case *Communique_Msg:
+ s := proto.Size(x.Msg)
+ n += proto.SizeVarint(10<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+var E_Greeting = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessage)(nil),
+ ExtensionType: ([]string)(nil),
+ Field: 106,
+ Name: "testdata.greeting",
+ Tag: "bytes,106,rep,name=greeting",
+ Filename: "test.proto",
+}
+
+var E_Complex = &proto.ExtensionDesc{
+ ExtendedType: (*OtherMessage)(nil),
+ ExtensionType: (*ComplexExtension)(nil),
+ Field: 200,
+ Name: "testdata.complex",
+ Tag: "bytes,200,opt,name=complex",
+ Filename: "test.proto",
+}
+
+var E_RComplex = &proto.ExtensionDesc{
+ ExtendedType: (*OtherMessage)(nil),
+ ExtensionType: ([]*ComplexExtension)(nil),
+ Field: 201,
+ Name: "testdata.r_complex",
+ Tag: "bytes,201,rep,name=r_complex,json=rComplex",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultDouble = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*float64)(nil),
+ Field: 101,
+ Name: "testdata.no_default_double",
+ Tag: "fixed64,101,opt,name=no_default_double,json=noDefaultDouble",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultFloat = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*float32)(nil),
+ Field: 102,
+ Name: "testdata.no_default_float",
+ Tag: "fixed32,102,opt,name=no_default_float,json=noDefaultFloat",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultInt32 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*int32)(nil),
+ Field: 103,
+ Name: "testdata.no_default_int32",
+ Tag: "varint,103,opt,name=no_default_int32,json=noDefaultInt32",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultInt64 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*int64)(nil),
+ Field: 104,
+ Name: "testdata.no_default_int64",
+ Tag: "varint,104,opt,name=no_default_int64,json=noDefaultInt64",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultUint32 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*uint32)(nil),
+ Field: 105,
+ Name: "testdata.no_default_uint32",
+ Tag: "varint,105,opt,name=no_default_uint32,json=noDefaultUint32",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultUint64 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*uint64)(nil),
+ Field: 106,
+ Name: "testdata.no_default_uint64",
+ Tag: "varint,106,opt,name=no_default_uint64,json=noDefaultUint64",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultSint32 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*int32)(nil),
+ Field: 107,
+ Name: "testdata.no_default_sint32",
+ Tag: "zigzag32,107,opt,name=no_default_sint32,json=noDefaultSint32",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultSint64 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*int64)(nil),
+ Field: 108,
+ Name: "testdata.no_default_sint64",
+ Tag: "zigzag64,108,opt,name=no_default_sint64,json=noDefaultSint64",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultFixed32 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*uint32)(nil),
+ Field: 109,
+ Name: "testdata.no_default_fixed32",
+ Tag: "fixed32,109,opt,name=no_default_fixed32,json=noDefaultFixed32",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultFixed64 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*uint64)(nil),
+ Field: 110,
+ Name: "testdata.no_default_fixed64",
+ Tag: "fixed64,110,opt,name=no_default_fixed64,json=noDefaultFixed64",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultSfixed32 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*int32)(nil),
+ Field: 111,
+ Name: "testdata.no_default_sfixed32",
+ Tag: "fixed32,111,opt,name=no_default_sfixed32,json=noDefaultSfixed32",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultSfixed64 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*int64)(nil),
+ Field: 112,
+ Name: "testdata.no_default_sfixed64",
+ Tag: "fixed64,112,opt,name=no_default_sfixed64,json=noDefaultSfixed64",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultBool = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 113,
+ Name: "testdata.no_default_bool",
+ Tag: "varint,113,opt,name=no_default_bool,json=noDefaultBool",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultString = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 114,
+ Name: "testdata.no_default_string",
+ Tag: "bytes,114,opt,name=no_default_string,json=noDefaultString",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultBytes = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: ([]byte)(nil),
+ Field: 115,
+ Name: "testdata.no_default_bytes",
+ Tag: "bytes,115,opt,name=no_default_bytes,json=noDefaultBytes",
+ Filename: "test.proto",
+}
+
+var E_NoDefaultEnum = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil),
+ Field: 116,
+ Name: "testdata.no_default_enum",
+ Tag: "varint,116,opt,name=no_default_enum,json=noDefaultEnum,enum=testdata.DefaultsMessage_DefaultsEnum",
+ Filename: "test.proto",
+}
+
+var E_DefaultDouble = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*float64)(nil),
+ Field: 201,
+ Name: "testdata.default_double",
+ Tag: "fixed64,201,opt,name=default_double,json=defaultDouble,def=3.1415",
+ Filename: "test.proto",
+}
+
+var E_DefaultFloat = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*float32)(nil),
+ Field: 202,
+ Name: "testdata.default_float",
+ Tag: "fixed32,202,opt,name=default_float,json=defaultFloat,def=3.14",
+ Filename: "test.proto",
+}
+
+var E_DefaultInt32 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*int32)(nil),
+ Field: 203,
+ Name: "testdata.default_int32",
+ Tag: "varint,203,opt,name=default_int32,json=defaultInt32,def=42",
+ Filename: "test.proto",
+}
+
+var E_DefaultInt64 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*int64)(nil),
+ Field: 204,
+ Name: "testdata.default_int64",
+ Tag: "varint,204,opt,name=default_int64,json=defaultInt64,def=43",
+ Filename: "test.proto",
+}
+
+var E_DefaultUint32 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*uint32)(nil),
+ Field: 205,
+ Name: "testdata.default_uint32",
+ Tag: "varint,205,opt,name=default_uint32,json=defaultUint32,def=44",
+ Filename: "test.proto",
+}
+
+var E_DefaultUint64 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*uint64)(nil),
+ Field: 206,
+ Name: "testdata.default_uint64",
+ Tag: "varint,206,opt,name=default_uint64,json=defaultUint64,def=45",
+ Filename: "test.proto",
+}
+
+var E_DefaultSint32 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*int32)(nil),
+ Field: 207,
+ Name: "testdata.default_sint32",
+ Tag: "zigzag32,207,opt,name=default_sint32,json=defaultSint32,def=46",
+ Filename: "test.proto",
+}
+
+var E_DefaultSint64 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*int64)(nil),
+ Field: 208,
+ Name: "testdata.default_sint64",
+ Tag: "zigzag64,208,opt,name=default_sint64,json=defaultSint64,def=47",
+ Filename: "test.proto",
+}
+
+var E_DefaultFixed32 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*uint32)(nil),
+ Field: 209,
+ Name: "testdata.default_fixed32",
+ Tag: "fixed32,209,opt,name=default_fixed32,json=defaultFixed32,def=48",
+ Filename: "test.proto",
+}
+
+var E_DefaultFixed64 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*uint64)(nil),
+ Field: 210,
+ Name: "testdata.default_fixed64",
+ Tag: "fixed64,210,opt,name=default_fixed64,json=defaultFixed64,def=49",
+ Filename: "test.proto",
+}
+
+var E_DefaultSfixed32 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*int32)(nil),
+ Field: 211,
+ Name: "testdata.default_sfixed32",
+ Tag: "fixed32,211,opt,name=default_sfixed32,json=defaultSfixed32,def=50",
+ Filename: "test.proto",
+}
+
+var E_DefaultSfixed64 = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*int64)(nil),
+ Field: 212,
+ Name: "testdata.default_sfixed64",
+ Tag: "fixed64,212,opt,name=default_sfixed64,json=defaultSfixed64,def=51",
+ Filename: "test.proto",
+}
+
+var E_DefaultBool = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*bool)(nil),
+ Field: 213,
+ Name: "testdata.default_bool",
+ Tag: "varint,213,opt,name=default_bool,json=defaultBool,def=1",
+ Filename: "test.proto",
+}
+
+var E_DefaultString = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 214,
+ Name: "testdata.default_string",
+ Tag: "bytes,214,opt,name=default_string,json=defaultString,def=Hello, string",
+ Filename: "test.proto",
+}
+
+var E_DefaultBytes = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: ([]byte)(nil),
+ Field: 215,
+ Name: "testdata.default_bytes",
+ Tag: "bytes,215,opt,name=default_bytes,json=defaultBytes,def=Hello, bytes",
+ Filename: "test.proto",
+}
+
+var E_DefaultEnum = &proto.ExtensionDesc{
+ ExtendedType: (*DefaultsMessage)(nil),
+ ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil),
+ Field: 216,
+ Name: "testdata.default_enum",
+ Tag: "varint,216,opt,name=default_enum,json=defaultEnum,enum=testdata.DefaultsMessage_DefaultsEnum,def=1",
+ Filename: "test.proto",
+}
+
+var E_X201 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 201,
+ Name: "testdata.x201",
+ Tag: "bytes,201,opt,name=x201",
+ Filename: "test.proto",
+}
+
+var E_X202 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 202,
+ Name: "testdata.x202",
+ Tag: "bytes,202,opt,name=x202",
+ Filename: "test.proto",
+}
+
+var E_X203 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 203,
+ Name: "testdata.x203",
+ Tag: "bytes,203,opt,name=x203",
+ Filename: "test.proto",
+}
+
+var E_X204 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 204,
+ Name: "testdata.x204",
+ Tag: "bytes,204,opt,name=x204",
+ Filename: "test.proto",
+}
+
+var E_X205 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 205,
+ Name: "testdata.x205",
+ Tag: "bytes,205,opt,name=x205",
+ Filename: "test.proto",
+}
+
+var E_X206 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 206,
+ Name: "testdata.x206",
+ Tag: "bytes,206,opt,name=x206",
+ Filename: "test.proto",
+}
+
+var E_X207 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 207,
+ Name: "testdata.x207",
+ Tag: "bytes,207,opt,name=x207",
+ Filename: "test.proto",
+}
+
+var E_X208 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 208,
+ Name: "testdata.x208",
+ Tag: "bytes,208,opt,name=x208",
+ Filename: "test.proto",
+}
+
+var E_X209 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 209,
+ Name: "testdata.x209",
+ Tag: "bytes,209,opt,name=x209",
+ Filename: "test.proto",
+}
+
+var E_X210 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 210,
+ Name: "testdata.x210",
+ Tag: "bytes,210,opt,name=x210",
+ Filename: "test.proto",
+}
+
+var E_X211 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 211,
+ Name: "testdata.x211",
+ Tag: "bytes,211,opt,name=x211",
+ Filename: "test.proto",
+}
+
+var E_X212 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 212,
+ Name: "testdata.x212",
+ Tag: "bytes,212,opt,name=x212",
+ Filename: "test.proto",
+}
+
+var E_X213 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 213,
+ Name: "testdata.x213",
+ Tag: "bytes,213,opt,name=x213",
+ Filename: "test.proto",
+}
+
+var E_X214 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 214,
+ Name: "testdata.x214",
+ Tag: "bytes,214,opt,name=x214",
+ Filename: "test.proto",
+}
+
+var E_X215 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 215,
+ Name: "testdata.x215",
+ Tag: "bytes,215,opt,name=x215",
+ Filename: "test.proto",
+}
+
+var E_X216 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 216,
+ Name: "testdata.x216",
+ Tag: "bytes,216,opt,name=x216",
+ Filename: "test.proto",
+}
+
+var E_X217 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 217,
+ Name: "testdata.x217",
+ Tag: "bytes,217,opt,name=x217",
+ Filename: "test.proto",
+}
+
+var E_X218 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 218,
+ Name: "testdata.x218",
+ Tag: "bytes,218,opt,name=x218",
+ Filename: "test.proto",
+}
+
+var E_X219 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 219,
+ Name: "testdata.x219",
+ Tag: "bytes,219,opt,name=x219",
+ Filename: "test.proto",
+}
+
+var E_X220 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 220,
+ Name: "testdata.x220",
+ Tag: "bytes,220,opt,name=x220",
+ Filename: "test.proto",
+}
+
+var E_X221 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 221,
+ Name: "testdata.x221",
+ Tag: "bytes,221,opt,name=x221",
+ Filename: "test.proto",
+}
+
+var E_X222 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 222,
+ Name: "testdata.x222",
+ Tag: "bytes,222,opt,name=x222",
+ Filename: "test.proto",
+}
+
+var E_X223 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 223,
+ Name: "testdata.x223",
+ Tag: "bytes,223,opt,name=x223",
+ Filename: "test.proto",
+}
+
+var E_X224 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 224,
+ Name: "testdata.x224",
+ Tag: "bytes,224,opt,name=x224",
+ Filename: "test.proto",
+}
+
+var E_X225 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 225,
+ Name: "testdata.x225",
+ Tag: "bytes,225,opt,name=x225",
+ Filename: "test.proto",
+}
+
+var E_X226 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 226,
+ Name: "testdata.x226",
+ Tag: "bytes,226,opt,name=x226",
+ Filename: "test.proto",
+}
+
+var E_X227 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 227,
+ Name: "testdata.x227",
+ Tag: "bytes,227,opt,name=x227",
+ Filename: "test.proto",
+}
+
+var E_X228 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 228,
+ Name: "testdata.x228",
+ Tag: "bytes,228,opt,name=x228",
+ Filename: "test.proto",
+}
+
+var E_X229 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 229,
+ Name: "testdata.x229",
+ Tag: "bytes,229,opt,name=x229",
+ Filename: "test.proto",
+}
+
+var E_X230 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 230,
+ Name: "testdata.x230",
+ Tag: "bytes,230,opt,name=x230",
+ Filename: "test.proto",
+}
+
+var E_X231 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 231,
+ Name: "testdata.x231",
+ Tag: "bytes,231,opt,name=x231",
+ Filename: "test.proto",
+}
+
+var E_X232 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 232,
+ Name: "testdata.x232",
+ Tag: "bytes,232,opt,name=x232",
+ Filename: "test.proto",
+}
+
+var E_X233 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 233,
+ Name: "testdata.x233",
+ Tag: "bytes,233,opt,name=x233",
+ Filename: "test.proto",
+}
+
+var E_X234 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 234,
+ Name: "testdata.x234",
+ Tag: "bytes,234,opt,name=x234",
+ Filename: "test.proto",
+}
+
+var E_X235 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 235,
+ Name: "testdata.x235",
+ Tag: "bytes,235,opt,name=x235",
+ Filename: "test.proto",
+}
+
+var E_X236 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 236,
+ Name: "testdata.x236",
+ Tag: "bytes,236,opt,name=x236",
+ Filename: "test.proto",
+}
+
+var E_X237 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 237,
+ Name: "testdata.x237",
+ Tag: "bytes,237,opt,name=x237",
+ Filename: "test.proto",
+}
+
+var E_X238 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 238,
+ Name: "testdata.x238",
+ Tag: "bytes,238,opt,name=x238",
+ Filename: "test.proto",
+}
+
+var E_X239 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 239,
+ Name: "testdata.x239",
+ Tag: "bytes,239,opt,name=x239",
+ Filename: "test.proto",
+}
+
+var E_X240 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 240,
+ Name: "testdata.x240",
+ Tag: "bytes,240,opt,name=x240",
+ Filename: "test.proto",
+}
+
+var E_X241 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 241,
+ Name: "testdata.x241",
+ Tag: "bytes,241,opt,name=x241",
+ Filename: "test.proto",
+}
+
+var E_X242 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 242,
+ Name: "testdata.x242",
+ Tag: "bytes,242,opt,name=x242",
+ Filename: "test.proto",
+}
+
+var E_X243 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 243,
+ Name: "testdata.x243",
+ Tag: "bytes,243,opt,name=x243",
+ Filename: "test.proto",
+}
+
+var E_X244 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 244,
+ Name: "testdata.x244",
+ Tag: "bytes,244,opt,name=x244",
+ Filename: "test.proto",
+}
+
+var E_X245 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 245,
+ Name: "testdata.x245",
+ Tag: "bytes,245,opt,name=x245",
+ Filename: "test.proto",
+}
+
+var E_X246 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 246,
+ Name: "testdata.x246",
+ Tag: "bytes,246,opt,name=x246",
+ Filename: "test.proto",
+}
+
+var E_X247 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 247,
+ Name: "testdata.x247",
+ Tag: "bytes,247,opt,name=x247",
+ Filename: "test.proto",
+}
+
+var E_X248 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 248,
+ Name: "testdata.x248",
+ Tag: "bytes,248,opt,name=x248",
+ Filename: "test.proto",
+}
+
+var E_X249 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 249,
+ Name: "testdata.x249",
+ Tag: "bytes,249,opt,name=x249",
+ Filename: "test.proto",
+}
+
+var E_X250 = &proto.ExtensionDesc{
+ ExtendedType: (*MyMessageSet)(nil),
+ ExtensionType: (*Empty)(nil),
+ Field: 250,
+ Name: "testdata.x250",
+ Tag: "bytes,250,opt,name=x250",
+ Filename: "test.proto",
+}
+
+func init() {
+ proto.RegisterType((*GoEnum)(nil), "testdata.GoEnum")
+ proto.RegisterType((*GoTestField)(nil), "testdata.GoTestField")
+ proto.RegisterType((*GoTest)(nil), "testdata.GoTest")
+ proto.RegisterType((*GoTest_RequiredGroup)(nil), "testdata.GoTest.RequiredGroup")
+ proto.RegisterType((*GoTest_RepeatedGroup)(nil), "testdata.GoTest.RepeatedGroup")
+ proto.RegisterType((*GoTest_OptionalGroup)(nil), "testdata.GoTest.OptionalGroup")
+ proto.RegisterType((*GoTestRequiredGroupField)(nil), "testdata.GoTestRequiredGroupField")
+ proto.RegisterType((*GoTestRequiredGroupField_Group)(nil), "testdata.GoTestRequiredGroupField.Group")
+ proto.RegisterType((*GoSkipTest)(nil), "testdata.GoSkipTest")
+ proto.RegisterType((*GoSkipTest_SkipGroup)(nil), "testdata.GoSkipTest.SkipGroup")
+ proto.RegisterType((*NonPackedTest)(nil), "testdata.NonPackedTest")
+ proto.RegisterType((*PackedTest)(nil), "testdata.PackedTest")
+ proto.RegisterType((*MaxTag)(nil), "testdata.MaxTag")
+ proto.RegisterType((*OldMessage)(nil), "testdata.OldMessage")
+ proto.RegisterType((*OldMessage_Nested)(nil), "testdata.OldMessage.Nested")
+ proto.RegisterType((*NewMessage)(nil), "testdata.NewMessage")
+ proto.RegisterType((*NewMessage_Nested)(nil), "testdata.NewMessage.Nested")
+ proto.RegisterType((*InnerMessage)(nil), "testdata.InnerMessage")
+ proto.RegisterType((*OtherMessage)(nil), "testdata.OtherMessage")
+ proto.RegisterType((*RequiredInnerMessage)(nil), "testdata.RequiredInnerMessage")
+ proto.RegisterType((*MyMessage)(nil), "testdata.MyMessage")
+ proto.RegisterType((*MyMessage_SomeGroup)(nil), "testdata.MyMessage.SomeGroup")
+ proto.RegisterType((*Ext)(nil), "testdata.Ext")
+ proto.RegisterType((*ComplexExtension)(nil), "testdata.ComplexExtension")
+ proto.RegisterType((*DefaultsMessage)(nil), "testdata.DefaultsMessage")
+ proto.RegisterType((*MyMessageSet)(nil), "testdata.MyMessageSet")
+ proto.RegisterType((*Empty)(nil), "testdata.Empty")
+ proto.RegisterType((*MessageList)(nil), "testdata.MessageList")
+ proto.RegisterType((*MessageList_Message)(nil), "testdata.MessageList.Message")
+ proto.RegisterType((*Strings)(nil), "testdata.Strings")
+ proto.RegisterType((*Defaults)(nil), "testdata.Defaults")
+ proto.RegisterType((*SubDefaults)(nil), "testdata.SubDefaults")
+ proto.RegisterType((*RepeatedEnum)(nil), "testdata.RepeatedEnum")
+ proto.RegisterType((*MoreRepeated)(nil), "testdata.MoreRepeated")
+ proto.RegisterType((*GroupOld)(nil), "testdata.GroupOld")
+ proto.RegisterType((*GroupOld_G)(nil), "testdata.GroupOld.G")
+ proto.RegisterType((*GroupNew)(nil), "testdata.GroupNew")
+ proto.RegisterType((*GroupNew_G)(nil), "testdata.GroupNew.G")
+ proto.RegisterType((*FloatingPoint)(nil), "testdata.FloatingPoint")
+ proto.RegisterType((*MessageWithMap)(nil), "testdata.MessageWithMap")
+ proto.RegisterType((*Oneof)(nil), "testdata.Oneof")
+ proto.RegisterType((*Oneof_F_Group)(nil), "testdata.Oneof.F_Group")
+ proto.RegisterType((*Communique)(nil), "testdata.Communique")
+ proto.RegisterEnum("testdata.FOO", FOO_name, FOO_value)
+ proto.RegisterEnum("testdata.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value)
+ proto.RegisterEnum("testdata.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value)
+ proto.RegisterEnum("testdata.DefaultsMessage_DefaultsEnum", DefaultsMessage_DefaultsEnum_name, DefaultsMessage_DefaultsEnum_value)
+ proto.RegisterEnum("testdata.Defaults_Color", Defaults_Color_name, Defaults_Color_value)
+ proto.RegisterEnum("testdata.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value)
+ proto.RegisterExtension(E_Ext_More)
+ proto.RegisterExtension(E_Ext_Text)
+ proto.RegisterExtension(E_Ext_Number)
+ proto.RegisterExtension(E_Greeting)
+ proto.RegisterExtension(E_Complex)
+ proto.RegisterExtension(E_RComplex)
+ proto.RegisterExtension(E_NoDefaultDouble)
+ proto.RegisterExtension(E_NoDefaultFloat)
+ proto.RegisterExtension(E_NoDefaultInt32)
+ proto.RegisterExtension(E_NoDefaultInt64)
+ proto.RegisterExtension(E_NoDefaultUint32)
+ proto.RegisterExtension(E_NoDefaultUint64)
+ proto.RegisterExtension(E_NoDefaultSint32)
+ proto.RegisterExtension(E_NoDefaultSint64)
+ proto.RegisterExtension(E_NoDefaultFixed32)
+ proto.RegisterExtension(E_NoDefaultFixed64)
+ proto.RegisterExtension(E_NoDefaultSfixed32)
+ proto.RegisterExtension(E_NoDefaultSfixed64)
+ proto.RegisterExtension(E_NoDefaultBool)
+ proto.RegisterExtension(E_NoDefaultString)
+ proto.RegisterExtension(E_NoDefaultBytes)
+ proto.RegisterExtension(E_NoDefaultEnum)
+ proto.RegisterExtension(E_DefaultDouble)
+ proto.RegisterExtension(E_DefaultFloat)
+ proto.RegisterExtension(E_DefaultInt32)
+ proto.RegisterExtension(E_DefaultInt64)
+ proto.RegisterExtension(E_DefaultUint32)
+ proto.RegisterExtension(E_DefaultUint64)
+ proto.RegisterExtension(E_DefaultSint32)
+ proto.RegisterExtension(E_DefaultSint64)
+ proto.RegisterExtension(E_DefaultFixed32)
+ proto.RegisterExtension(E_DefaultFixed64)
+ proto.RegisterExtension(E_DefaultSfixed32)
+ proto.RegisterExtension(E_DefaultSfixed64)
+ proto.RegisterExtension(E_DefaultBool)
+ proto.RegisterExtension(E_DefaultString)
+ proto.RegisterExtension(E_DefaultBytes)
+ proto.RegisterExtension(E_DefaultEnum)
+ proto.RegisterExtension(E_X201)
+ proto.RegisterExtension(E_X202)
+ proto.RegisterExtension(E_X203)
+ proto.RegisterExtension(E_X204)
+ proto.RegisterExtension(E_X205)
+ proto.RegisterExtension(E_X206)
+ proto.RegisterExtension(E_X207)
+ proto.RegisterExtension(E_X208)
+ proto.RegisterExtension(E_X209)
+ proto.RegisterExtension(E_X210)
+ proto.RegisterExtension(E_X211)
+ proto.RegisterExtension(E_X212)
+ proto.RegisterExtension(E_X213)
+ proto.RegisterExtension(E_X214)
+ proto.RegisterExtension(E_X215)
+ proto.RegisterExtension(E_X216)
+ proto.RegisterExtension(E_X217)
+ proto.RegisterExtension(E_X218)
+ proto.RegisterExtension(E_X219)
+ proto.RegisterExtension(E_X220)
+ proto.RegisterExtension(E_X221)
+ proto.RegisterExtension(E_X222)
+ proto.RegisterExtension(E_X223)
+ proto.RegisterExtension(E_X224)
+ proto.RegisterExtension(E_X225)
+ proto.RegisterExtension(E_X226)
+ proto.RegisterExtension(E_X227)
+ proto.RegisterExtension(E_X228)
+ proto.RegisterExtension(E_X229)
+ proto.RegisterExtension(E_X230)
+ proto.RegisterExtension(E_X231)
+ proto.RegisterExtension(E_X232)
+ proto.RegisterExtension(E_X233)
+ proto.RegisterExtension(E_X234)
+ proto.RegisterExtension(E_X235)
+ proto.RegisterExtension(E_X236)
+ proto.RegisterExtension(E_X237)
+ proto.RegisterExtension(E_X238)
+ proto.RegisterExtension(E_X239)
+ proto.RegisterExtension(E_X240)
+ proto.RegisterExtension(E_X241)
+ proto.RegisterExtension(E_X242)
+ proto.RegisterExtension(E_X243)
+ proto.RegisterExtension(E_X244)
+ proto.RegisterExtension(E_X245)
+ proto.RegisterExtension(E_X246)
+ proto.RegisterExtension(E_X247)
+ proto.RegisterExtension(E_X248)
+ proto.RegisterExtension(E_X249)
+ proto.RegisterExtension(E_X250)
+}
+
+func init() { proto.RegisterFile("test.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 4453 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x5a, 0xc9, 0x77, 0xdb, 0x48,
+ 0x7a, 0x37, 0xc0, 0xfd, 0x23, 0x25, 0x42, 0x65, 0xb5, 0x9b, 0x96, 0xbc, 0xc0, 0x9c, 0xe9, 0x6e,
+ 0x7a, 0xd3, 0x48, 0x20, 0x44, 0xdb, 0x74, 0xa7, 0xdf, 0xf3, 0x42, 0xca, 0x7a, 0x63, 0x89, 0x0a,
+ 0xa4, 0xee, 0x7e, 0xd3, 0x39, 0xf0, 0x51, 0x22, 0x44, 0xb3, 0x4d, 0x02, 0x34, 0x09, 0xc5, 0x52,
+ 0x72, 0xe9, 0x4b, 0x72, 0xcd, 0x76, 0xc9, 0x35, 0xa7, 0x9c, 0x92, 0xbc, 0x97, 0x7f, 0x22, 0xe9,
+ 0xee, 0x59, 0x7b, 0xd6, 0xac, 0x93, 0x7d, 0x99, 0xec, 0xdb, 0x4c, 0x92, 0x4b, 0xcf, 0xab, 0xaf,
+ 0x0a, 0x40, 0x01, 0x24, 0x20, 0xf9, 0x24, 0x56, 0xd5, 0xef, 0xf7, 0xd5, 0xf6, 0xab, 0xef, 0xab,
+ 0xaf, 0x20, 0x00, 0xc7, 0x9c, 0x38, 0x2b, 0xa3, 0xb1, 0xed, 0xd8, 0x24, 0x4b, 0x7f, 0x77, 0x3b,
+ 0x4e, 0xa7, 0x7c, 0x1d, 0xd2, 0x1b, 0x76, 0xc3, 0x3a, 0x1a, 0x92, 0xab, 0x90, 0x38, 0xb4, 0xed,
+ 0x92, 0xa4, 0xca, 0x95, 0x79, 0x6d, 0x6e, 0xc5, 0x45, 0xac, 0x34, 0x5b, 0x2d, 0x83, 0xb6, 0x94,
+ 0xef, 0x40, 0x7e, 0xc3, 0xde, 0x33, 0x27, 0x4e, 0xb3, 0x6f, 0x0e, 0xba, 0x64, 0x11, 0x52, 0x4f,
+ 0x3b, 0xfb, 0xe6, 0x00, 0x19, 0x39, 0x83, 0x15, 0x08, 0x81, 0xe4, 0xde, 0xc9, 0xc8, 0x2c, 0xc9,
+ 0x58, 0x89, 0xbf, 0xcb, 0xbf, 0x72, 0x85, 0x76, 0x42, 0x99, 0xe4, 0x3a, 0x24, 0xbf, 0xdc, 0xb7,
+ 0xba, 0xbc, 0x97, 0xd7, 0xfc, 0x5e, 0x58, 0xfb, 0xca, 0x97, 0x37, 0xb7, 0x1f, 0x1b, 0x08, 0xa1,
+ 0xf6, 0xf7, 0x3a, 0xfb, 0x03, 0x6a, 0x4a, 0xa2, 0xf6, 0xb1, 0x40, 0x6b, 0x77, 0x3a, 0xe3, 0xce,
+ 0xb0, 0x94, 0x50, 0xa5, 0x4a, 0xca, 0x60, 0x05, 0x72, 0x1f, 0xe6, 0x0c, 0xf3, 0xc5, 0x51, 0x7f,
+ 0x6c, 0x76, 0x71, 0x70, 0xa5, 0xa4, 0x2a, 0x57, 0xf2, 0xd3, 0xf6, 0xb1, 0xd1, 0x08, 0x62, 0x19,
+ 0x79, 0x64, 0x76, 0x1c, 0x97, 0x9c, 0x52, 0x13, 0xb1, 0x64, 0x01, 0x4b, 0xc9, 0xad, 0x91, 0xd3,
+ 0xb7, 0xad, 0xce, 0x80, 0x91, 0xd3, 0xaa, 0x14, 0x43, 0x0e, 0x60, 0xc9, 0x9b, 0x50, 0x6c, 0xb6,
+ 0x1f, 0xda, 0xf6, 0xa0, 0x3d, 0xe6, 0x23, 0x2a, 0x81, 0x2a, 0x57, 0xb2, 0xc6, 0x5c, 0x93, 0xd6,
+ 0xba, 0xc3, 0x24, 0x15, 0x50, 0x9a, 0xed, 0x4d, 0xcb, 0xa9, 0x6a, 0x3e, 0x30, 0xaf, 0xca, 0x95,
+ 0x94, 0x31, 0xdf, 0xc4, 0xea, 0x29, 0x64, 0x4d, 0xf7, 0x91, 0x05, 0x55, 0xae, 0x24, 0x18, 0xb2,
+ 0xa6, 0x7b, 0xc8, 0x5b, 0x40, 0x9a, 0xed, 0x66, 0xff, 0xd8, 0xec, 0x8a, 0x56, 0xe7, 0x54, 0xb9,
+ 0x92, 0x31, 0x94, 0x26, 0x6f, 0x98, 0x81, 0x16, 0x2d, 0xcf, 0xab, 0x72, 0x25, 0xed, 0xa2, 0x05,
+ 0xdb, 0x37, 0x60, 0xa1, 0xd9, 0x7e, 0xb7, 0x1f, 0x1c, 0x70, 0x51, 0x95, 0x2b, 0x73, 0x46, 0xb1,
+ 0xc9, 0xea, 0xa7, 0xb1, 0xa2, 0x61, 0x45, 0x95, 0x2b, 0x49, 0x8e, 0x15, 0xec, 0xe2, 0xec, 0x9a,
+ 0x03, 0xbb, 0xe3, 0xf8, 0xd0, 0x05, 0x55, 0xae, 0xc8, 0xc6, 0x7c, 0x13, 0xab, 0x83, 0x56, 0x1f,
+ 0xdb, 0x47, 0xfb, 0x03, 0xd3, 0x87, 0x12, 0x55, 0xae, 0x48, 0x46, 0xb1, 0xc9, 0xea, 0x83, 0xd8,
+ 0x5d, 0x67, 0xdc, 0xb7, 0x7a, 0x3e, 0xf6, 0x3c, 0xea, 0xb7, 0xd8, 0x64, 0xf5, 0xc1, 0x11, 0x3c,
+ 0x3c, 0x71, 0xcc, 0x89, 0x0f, 0x35, 0x55, 0xb9, 0x52, 0x30, 0xe6, 0x9b, 0x58, 0x1d, 0xb2, 0x1a,
+ 0x5a, 0x83, 0x43, 0x55, 0xae, 0x2c, 0x50, 0xab, 0x33, 0xd6, 0x60, 0x37, 0xb4, 0x06, 0x3d, 0x55,
+ 0xae, 0x10, 0x8e, 0x15, 0xd6, 0x40, 0xd4, 0x0c, 0x13, 0x62, 0x69, 0x51, 0x4d, 0x08, 0x9a, 0x61,
+ 0x95, 0x41, 0xcd, 0x70, 0xe0, 0x6b, 0x6a, 0x42, 0xd4, 0x4c, 0x08, 0x89, 0x9d, 0x73, 0xe4, 0x05,
+ 0x35, 0x21, 0x6a, 0x86, 0x23, 0x43, 0x9a, 0xe1, 0xd8, 0xd7, 0xd5, 0x44, 0x50, 0x33, 0x53, 0x68,
+ 0xd1, 0x72, 0x49, 0x4d, 0x04, 0x35, 0xc3, 0xd1, 0x41, 0xcd, 0x70, 0xf0, 0x45, 0x35, 0x11, 0xd0,
+ 0x4c, 0x18, 0x2b, 0x1a, 0x5e, 0x52, 0x13, 0x01, 0xcd, 0x88, 0xb3, 0x73, 0x35, 0xc3, 0xa1, 0xcb,
+ 0x6a, 0x42, 0xd4, 0x8c, 0x68, 0xd5, 0xd3, 0x0c, 0x87, 0x5e, 0x52, 0x13, 0x01, 0xcd, 0x88, 0x58,
+ 0x4f, 0x33, 0x1c, 0x7b, 0x59, 0x4d, 0x04, 0x34, 0xc3, 0xb1, 0xd7, 0x45, 0xcd, 0x70, 0xe8, 0xc7,
+ 0x92, 0x9a, 0x10, 0x45, 0xc3, 0xa1, 0x37, 0x03, 0xa2, 0xe1, 0xd8, 0x4f, 0x28, 0x56, 0x54, 0x4d,
+ 0x18, 0x2c, 0xae, 0xc2, 0xa7, 0x14, 0x2c, 0xca, 0x86, 0x83, 0x7d, 0xd9, 0xd8, 0xdc, 0x05, 0x95,
+ 0xae, 0xa8, 0x92, 0x27, 0x1b, 0xd7, 0x2f, 0x89, 0xb2, 0xf1, 0x80, 0x57, 0xd1, 0xd5, 0x72, 0xd9,
+ 0x4c, 0x21, 0x6b, 0xba, 0x8f, 0x54, 0x55, 0xc9, 0x97, 0x8d, 0x87, 0x0c, 0xc8, 0xc6, 0xc3, 0x5e,
+ 0x53, 0x25, 0x51, 0x36, 0x33, 0xd0, 0xa2, 0xe5, 0xb2, 0x2a, 0x89, 0xb2, 0xf1, 0xd0, 0xa2, 0x6c,
+ 0x3c, 0xf0, 0x17, 0x54, 0x49, 0x90, 0xcd, 0x34, 0x56, 0x34, 0xfc, 0x45, 0x55, 0x12, 0x64, 0x13,
+ 0x9c, 0x1d, 0x93, 0x8d, 0x07, 0x7d, 0x43, 0x95, 0x7c, 0xd9, 0x04, 0xad, 0x72, 0xd9, 0x78, 0xd0,
+ 0x37, 0x55, 0x49, 0x90, 0x4d, 0x10, 0xcb, 0x65, 0xe3, 0x61, 0xdf, 0xc2, 0xf8, 0xe6, 0xca, 0xc6,
+ 0xc3, 0x0a, 0xb2, 0xf1, 0xa0, 0xbf, 0x43, 0x63, 0xa1, 0x27, 0x1b, 0x0f, 0x2a, 0xca, 0xc6, 0xc3,
+ 0xfe, 0x2e, 0xc5, 0xfa, 0xb2, 0x99, 0x06, 0x8b, 0xab, 0xf0, 0x7b, 0x14, 0xec, 0xcb, 0xc6, 0x03,
+ 0xaf, 0xe0, 0x20, 0xa8, 0x6c, 0xba, 0xe6, 0x61, 0xe7, 0x68, 0x40, 0x25, 0x56, 0xa1, 0xba, 0xa9,
+ 0x27, 0x9d, 0xf1, 0x91, 0x49, 0x47, 0x62, 0xdb, 0x83, 0xc7, 0x6e, 0x1b, 0x59, 0xa1, 0xc6, 0x99,
+ 0x7c, 0x7c, 0xc2, 0x75, 0xaa, 0x9f, 0xba, 0x5c, 0xd5, 0x8c, 0x22, 0xd3, 0xd0, 0x34, 0xbe, 0xa6,
+ 0x0b, 0xf8, 0x1b, 0x54, 0x45, 0x75, 0xb9, 0xa6, 0x33, 0x7c, 0x4d, 0xf7, 0xf1, 0x55, 0x38, 0xef,
+ 0x4b, 0xc9, 0x67, 0xdc, 0xa4, 0x5a, 0xaa, 0x27, 0xaa, 0xda, 0xaa, 0xb1, 0xe0, 0x0a, 0x6a, 0x16,
+ 0x29, 0xd0, 0xcd, 0x2d, 0x2a, 0xa9, 0x7a, 0xa2, 0xa6, 0x7b, 0x24, 0xb1, 0x27, 0x8d, 0xca, 0x90,
+ 0x0b, 0xcb, 0xe7, 0xdc, 0xa6, 0xca, 0xaa, 0x27, 0xab, 0xda, 0xea, 0xaa, 0xa1, 0x70, 0x7d, 0xcd,
+ 0xe0, 0x04, 0xfa, 0x59, 0xa1, 0x0a, 0xab, 0x27, 0x6b, 0xba, 0xc7, 0x09, 0xf6, 0xb3, 0xe0, 0x0a,
+ 0xcd, 0xa7, 0x7c, 0x89, 0x2a, 0xad, 0x9e, 0xae, 0xae, 0xe9, 0x6b, 0xeb, 0xf7, 0x8c, 0x22, 0x53,
+ 0x9c, 0xcf, 0xd1, 0x69, 0x3f, 0x5c, 0x72, 0x3e, 0x69, 0x95, 0x6a, 0xae, 0x9e, 0xd6, 0xee, 0xac,
+ 0xdd, 0xd5, 0xee, 0x1a, 0x0a, 0xd7, 0x9e, 0xcf, 0x7a, 0x87, 0xb2, 0xb8, 0xf8, 0x7c, 0xd6, 0x1a,
+ 0x55, 0x5f, 0x5d, 0x79, 0x66, 0x0e, 0x06, 0xf6, 0x2d, 0xb5, 0xfc, 0xd2, 0x1e, 0x0f, 0xba, 0xd7,
+ 0xca, 0x60, 0x28, 0x5c, 0x8f, 0x62, 0xaf, 0x0b, 0xae, 0x20, 0x7d, 0xfa, 0xaf, 0xd1, 0x7b, 0x58,
+ 0xa1, 0x9e, 0x79, 0xd8, 0xef, 0x59, 0xf6, 0xc4, 0x34, 0x8a, 0x4c, 0x9a, 0xa1, 0x35, 0xd9, 0x0d,
+ 0xaf, 0xe3, 0xaf, 0x53, 0xda, 0x42, 0x3d, 0x71, 0xbb, 0xaa, 0xd1, 0x9e, 0x66, 0xad, 0xe3, 0x6e,
+ 0x78, 0x1d, 0x7f, 0x83, 0x72, 0x48, 0x3d, 0x71, 0xbb, 0xa6, 0x73, 0x8e, 0xb8, 0x8e, 0x77, 0xe0,
+ 0x42, 0x28, 0x2e, 0xb6, 0x47, 0x9d, 0x83, 0xe7, 0x66, 0xb7, 0xa4, 0xd1, 0xf0, 0xf8, 0x50, 0x56,
+ 0x24, 0xe3, 0x7c, 0x20, 0x44, 0xee, 0x60, 0x33, 0xb9, 0x07, 0xaf, 0x87, 0x03, 0xa5, 0xcb, 0xac,
+ 0xd2, 0x78, 0x89, 0xcc, 0xc5, 0x60, 0xcc, 0x0c, 0x51, 0x05, 0x07, 0xec, 0x52, 0x75, 0x1a, 0x40,
+ 0x7d, 0xaa, 0xef, 0x89, 0x39, 0xf5, 0x67, 0xe0, 0xe2, 0x74, 0x28, 0x75, 0xc9, 0xeb, 0x34, 0xa2,
+ 0x22, 0xf9, 0x42, 0x38, 0xaa, 0x4e, 0xd1, 0x67, 0xf4, 0x5d, 0xa3, 0x21, 0x56, 0xa4, 0x4f, 0xf5,
+ 0x7e, 0x1f, 0x4a, 0x53, 0xc1, 0xd6, 0x65, 0xdf, 0xa1, 0x31, 0x17, 0xd9, 0xaf, 0x85, 0xe2, 0x6e,
+ 0x98, 0x3c, 0xa3, 0xeb, 0xbb, 0x34, 0x08, 0x0b, 0xe4, 0xa9, 0x9e, 0x71, 0xc9, 0x82, 0xe1, 0xd8,
+ 0xe5, 0xde, 0xa3, 0x51, 0x99, 0x2f, 0x59, 0x20, 0x32, 0x8b, 0xfd, 0x86, 0xe2, 0xb3, 0xcb, 0xad,
+ 0xd3, 0x30, 0xcd, 0xfb, 0x0d, 0x86, 0x6a, 0x4e, 0x7e, 0x9b, 0x92, 0x77, 0x67, 0xcf, 0xf8, 0xc7,
+ 0x09, 0x1a, 0x60, 0x39, 0x7b, 0x77, 0xd6, 0x94, 0x3d, 0xf6, 0x8c, 0x29, 0xff, 0x84, 0xb2, 0x89,
+ 0xc0, 0x9e, 0x9a, 0xf3, 0x63, 0x98, 0x73, 0x6f, 0x75, 0xbd, 0xb1, 0x7d, 0x34, 0x2a, 0x35, 0x55,
+ 0xb9, 0x02, 0xda, 0x95, 0xa9, 0xec, 0xc7, 0xbd, 0xe4, 0x6d, 0x50, 0x94, 0x11, 0x24, 0x31, 0x2b,
+ 0xcc, 0x2e, 0xb3, 0xb2, 0xa3, 0x26, 0x22, 0xac, 0x30, 0x94, 0x67, 0x45, 0x20, 0x51, 0x2b, 0xae,
+ 0xd3, 0x67, 0x56, 0x3e, 0x50, 0xa5, 0x99, 0x56, 0xdc, 0x10, 0xc0, 0xad, 0x04, 0x48, 0x4b, 0xeb,
+ 0x7e, 0xbe, 0x85, 0xed, 0xe4, 0x8b, 0xe1, 0x04, 0x6c, 0x03, 0xef, 0xcf, 0xc1, 0x4a, 0x46, 0x13,
+ 0x06, 0x37, 0x4d, 0xfb, 0xd9, 0x08, 0x5a, 0x60, 0x34, 0xd3, 0xb4, 0x9f, 0x9b, 0x41, 0x2b, 0xff,
+ 0xa6, 0x04, 0x49, 0x9a, 0x4f, 0x92, 0x2c, 0x24, 0xdf, 0x6b, 0x6d, 0x3e, 0x56, 0xce, 0xd1, 0x5f,
+ 0x0f, 0x5b, 0xad, 0xa7, 0x8a, 0x44, 0x72, 0x90, 0x7a, 0xf8, 0x95, 0xbd, 0xc6, 0xae, 0x22, 0x93,
+ 0x22, 0xe4, 0x9b, 0x9b, 0xdb, 0x1b, 0x0d, 0x63, 0xc7, 0xd8, 0xdc, 0xde, 0x53, 0x12, 0xb4, 0xad,
+ 0xf9, 0xb4, 0xf5, 0x60, 0x4f, 0x49, 0x92, 0x0c, 0x24, 0x68, 0x5d, 0x8a, 0x00, 0xa4, 0x77, 0xf7,
+ 0x8c, 0xcd, 0xed, 0x0d, 0x25, 0x4d, 0xad, 0xec, 0x6d, 0x6e, 0x35, 0x94, 0x0c, 0x45, 0xee, 0xbd,
+ 0xbb, 0xf3, 0xb4, 0xa1, 0x64, 0xe9, 0xcf, 0x07, 0x86, 0xf1, 0xe0, 0x2b, 0x4a, 0x8e, 0x92, 0xb6,
+ 0x1e, 0xec, 0x28, 0x80, 0xcd, 0x0f, 0x1e, 0x3e, 0x6d, 0x28, 0x79, 0x52, 0x80, 0x6c, 0xf3, 0xdd,
+ 0xed, 0x47, 0x7b, 0x9b, 0xad, 0x6d, 0xa5, 0x50, 0x3e, 0x81, 0x12, 0x5b, 0xe6, 0xc0, 0x2a, 0xb2,
+ 0xa4, 0xf0, 0x1d, 0x48, 0xb1, 0x9d, 0x91, 0x50, 0x25, 0x95, 0xf0, 0xce, 0x4c, 0x53, 0x56, 0xd8,
+ 0x1e, 0x31, 0xda, 0xd2, 0x65, 0x48, 0xb1, 0x55, 0x5a, 0x84, 0x14, 0x5b, 0x1d, 0x19, 0x53, 0x45,
+ 0x56, 0x28, 0xff, 0x96, 0x0c, 0xb0, 0x61, 0xef, 0x3e, 0xef, 0x8f, 0x30, 0x21, 0xbf, 0x0c, 0x30,
+ 0x79, 0xde, 0x1f, 0xb5, 0x51, 0xf5, 0x3c, 0xa9, 0xcc, 0xd1, 0x1a, 0xf4, 0x77, 0xe4, 0x1a, 0x14,
+ 0xb0, 0xf9, 0x90, 0x79, 0x21, 0xcc, 0x25, 0x33, 0x46, 0x9e, 0xd6, 0x71, 0xc7, 0x14, 0x84, 0xd4,
+ 0x74, 0x4c, 0x21, 0xd3, 0x02, 0xa4, 0xa6, 0x93, 0xab, 0x80, 0xc5, 0xf6, 0x04, 0x23, 0x0a, 0xa6,
+ 0x8d, 0x39, 0x03, 0xfb, 0x65, 0x31, 0x86, 0xbc, 0x0d, 0xd8, 0x27, 0x9b, 0x77, 0x71, 0xfa, 0x74,
+ 0xb8, 0xc3, 0x5d, 0xa1, 0x3f, 0xd8, 0x6c, 0x7d, 0xc2, 0x52, 0x0b, 0x72, 0x5e, 0x3d, 0xed, 0x0b,
+ 0x6b, 0xf9, 0x8c, 0x14, 0x9c, 0x11, 0x60, 0x95, 0x37, 0x25, 0x06, 0xe0, 0xa3, 0x59, 0xc0, 0xd1,
+ 0x30, 0x12, 0x1b, 0x4e, 0xf9, 0x32, 0xcc, 0x6d, 0xdb, 0x16, 0x3b, 0xbd, 0xb8, 0x4a, 0x05, 0x90,
+ 0x3a, 0x25, 0x09, 0xb3, 0x27, 0xa9, 0x53, 0xbe, 0x02, 0x20, 0xb4, 0x29, 0x20, 0xed, 0xb3, 0x36,
+ 0xf4, 0x01, 0xd2, 0x7e, 0xf9, 0x26, 0xa4, 0xb7, 0x3a, 0xc7, 0x7b, 0x9d, 0x1e, 0xb9, 0x06, 0x30,
+ 0xe8, 0x4c, 0x9c, 0xf6, 0x21, 0xee, 0xc3, 0xe7, 0x9f, 0x7f, 0xfe, 0xb9, 0x84, 0x97, 0xbd, 0x1c,
+ 0xad, 0x65, 0xfb, 0xf1, 0x02, 0xa0, 0x35, 0xe8, 0x6e, 0x99, 0x93, 0x49, 0xa7, 0x67, 0x92, 0x2a,
+ 0xa4, 0x2d, 0x73, 0x42, 0xa3, 0x9d, 0x84, 0xef, 0x08, 0xcb, 0xfe, 0x2a, 0xf8, 0xa8, 0x95, 0x6d,
+ 0x84, 0x18, 0x1c, 0x4a, 0x14, 0x48, 0x58, 0x47, 0x43, 0x7c, 0x27, 0x49, 0x19, 0xf4, 0xe7, 0xd2,
+ 0x25, 0x48, 0x33, 0x0c, 0x21, 0x90, 0xb4, 0x3a, 0x43, 0xb3, 0xc4, 0xfa, 0xc5, 0xdf, 0xe5, 0x5f,
+ 0x95, 0x00, 0xb6, 0xcd, 0x97, 0x67, 0xe8, 0xd3, 0x47, 0xc5, 0xf4, 0x99, 0x60, 0x7d, 0xde, 0x8f,
+ 0xeb, 0x93, 0xea, 0xec, 0xd0, 0xb6, 0xbb, 0x6d, 0xb6, 0xc5, 0xec, 0x49, 0x27, 0x47, 0x6b, 0x70,
+ 0xd7, 0xca, 0x1f, 0x40, 0x61, 0xd3, 0xb2, 0xcc, 0xb1, 0x3b, 0x26, 0x02, 0xc9, 0x67, 0xf6, 0xc4,
+ 0xe1, 0x6f, 0x4b, 0xf8, 0x9b, 0x94, 0x20, 0x39, 0xb2, 0xc7, 0x0e, 0x9b, 0x67, 0x3d, 0xa9, 0xaf,
+ 0xae, 0xae, 0x1a, 0x58, 0x43, 0x2e, 0x41, 0xee, 0xc0, 0xb6, 0x2c, 0xf3, 0x80, 0x4e, 0x22, 0x81,
+ 0x69, 0x8d, 0x5f, 0x51, 0xfe, 0x65, 0x09, 0x0a, 0x2d, 0xe7, 0x99, 0x6f, 0x5c, 0x81, 0xc4, 0x73,
+ 0xf3, 0x04, 0x87, 0x97, 0x30, 0xe8, 0x4f, 0x7a, 0x54, 0x7e, 0xbe, 0x33, 0x38, 0x62, 0x6f, 0x4d,
+ 0x05, 0x83, 0x15, 0xc8, 0x05, 0x48, 0xbf, 0x34, 0xfb, 0xbd, 0x67, 0x0e, 0xda, 0x94, 0x0d, 0x5e,
+ 0x22, 0xb7, 0x20, 0xd5, 0xa7, 0x83, 0x2d, 0x25, 0x71, 0xbd, 0x2e, 0xf8, 0xeb, 0x25, 0xce, 0xc1,
+ 0x60, 0xa0, 0x1b, 0xd9, 0x6c, 0x57, 0xf9, 0xe8, 0xa3, 0x8f, 0x3e, 0x92, 0xcb, 0x87, 0xb0, 0xe8,
+ 0x1e, 0xde, 0xc0, 0x64, 0xb7, 0xa1, 0x34, 0x30, 0xed, 0xf6, 0x61, 0xdf, 0xea, 0x0c, 0x06, 0x27,
+ 0xed, 0x97, 0xb6, 0xd5, 0xee, 0x58, 0x6d, 0x7b, 0x72, 0xd0, 0x19, 0xe3, 0x02, 0x44, 0x77, 0xb1,
+ 0x38, 0x30, 0xed, 0x26, 0xa3, 0xbd, 0x6f, 0x5b, 0x0f, 0xac, 0x16, 0xe5, 0x94, 0xff, 0x20, 0x09,
+ 0xb9, 0xad, 0x13, 0xd7, 0xfa, 0x22, 0xa4, 0x0e, 0xec, 0x23, 0x8b, 0xad, 0x65, 0xca, 0x60, 0x05,
+ 0x6f, 0x8f, 0x64, 0x61, 0x8f, 0x16, 0x21, 0xf5, 0xe2, 0xc8, 0x76, 0x4c, 0x9c, 0x6e, 0xce, 0x60,
+ 0x05, 0xba, 0x5a, 0x23, 0xd3, 0x29, 0x25, 0x31, 0xb9, 0xa5, 0x3f, 0xfd, 0xf9, 0xa7, 0xce, 0x30,
+ 0x7f, 0xb2, 0x02, 0x69, 0x9b, 0xae, 0xfe, 0xa4, 0x94, 0xc6, 0x77, 0x35, 0x01, 0x2e, 0xee, 0x8a,
+ 0xc1, 0x51, 0x64, 0x13, 0x16, 0x5e, 0x9a, 0xed, 0xe1, 0xd1, 0xc4, 0x69, 0xf7, 0xec, 0x76, 0xd7,
+ 0x34, 0x47, 0xe6, 0xb8, 0x34, 0x87, 0x3d, 0x09, 0x3e, 0x61, 0xd6, 0x42, 0x1a, 0xf3, 0x2f, 0xcd,
+ 0xad, 0xa3, 0x89, 0xb3, 0x61, 0x3f, 0x46, 0x16, 0xa9, 0x42, 0x6e, 0x6c, 0x52, 0x4f, 0x40, 0x07,
+ 0x5b, 0x08, 0xf7, 0x1e, 0xa0, 0x66, 0xc7, 0xe6, 0x08, 0x2b, 0xc8, 0x3a, 0x64, 0xf7, 0xfb, 0xcf,
+ 0xcd, 0xc9, 0x33, 0xb3, 0x5b, 0xca, 0xa8, 0x52, 0x65, 0x5e, 0xbb, 0xe8, 0x73, 0xbc, 0x65, 0x5d,
+ 0x79, 0x64, 0x0f, 0xec, 0xb1, 0xe1, 0x41, 0xc9, 0x7d, 0xc8, 0x4d, 0xec, 0xa1, 0xc9, 0xf4, 0x9d,
+ 0xc5, 0xa0, 0x7a, 0x79, 0x16, 0x6f, 0xd7, 0x1e, 0x9a, 0xae, 0x07, 0x73, 0xf1, 0x64, 0x99, 0x0d,
+ 0x74, 0x9f, 0x5e, 0x9d, 0x4b, 0x80, 0x4f, 0x03, 0x74, 0x40, 0x78, 0x95, 0x26, 0x4b, 0x74, 0x40,
+ 0xbd, 0x43, 0x7a, 0x23, 0x2a, 0xe5, 0x31, 0xaf, 0xf4, 0xca, 0x4b, 0xb7, 0x20, 0xe7, 0x19, 0xf4,
+ 0x5d, 0x1f, 0x73, 0x37, 0x39, 0xf4, 0x07, 0xcc, 0xf5, 0x31, 0x5f, 0xf3, 0x06, 0xa4, 0x70, 0xd8,
+ 0x34, 0x42, 0x19, 0x0d, 0x1a, 0x10, 0x73, 0x90, 0xda, 0x30, 0x1a, 0x8d, 0x6d, 0x45, 0xc2, 0xd8,
+ 0xf8, 0xf4, 0xdd, 0x86, 0x22, 0x0b, 0x8a, 0xfd, 0x6d, 0x09, 0x12, 0x8d, 0x63, 0x54, 0x0b, 0x9d,
+ 0x86, 0x7b, 0xa2, 0xe9, 0x6f, 0xad, 0x06, 0xc9, 0xa1, 0x3d, 0x36, 0xc9, 0xf9, 0x19, 0xb3, 0x2c,
+ 0xf5, 0x70, 0xbf, 0x84, 0x57, 0xe4, 0xc6, 0xb1, 0x63, 0x20, 0x5e, 0x7b, 0x0b, 0x92, 0x8e, 0x79,
+ 0xec, 0xcc, 0xe6, 0x3d, 0x63, 0x1d, 0x50, 0x80, 0x76, 0x13, 0xd2, 0xd6, 0xd1, 0x70, 0xdf, 0x1c,
+ 0xcf, 0x86, 0xf6, 0x71, 0x7a, 0x1c, 0x52, 0x7e, 0x0f, 0x94, 0x47, 0xf6, 0x70, 0x34, 0x30, 0x8f,
+ 0x1b, 0xc7, 0x8e, 0x69, 0x4d, 0xfa, 0xb6, 0x45, 0xf5, 0x7c, 0xd8, 0x1f, 0xa3, 0x17, 0xc1, 0xb7,
+ 0x62, 0x2c, 0xd0, 0x53, 0x3d, 0x31, 0x0f, 0x6c, 0xab, 0xcb, 0x1d, 0x26, 0x2f, 0x51, 0xb4, 0xf3,
+ 0xac, 0x3f, 0xa6, 0x0e, 0x84, 0xfa, 0x79, 0x56, 0x28, 0x6f, 0x40, 0x91, 0xe7, 0x18, 0x13, 0xde,
+ 0x71, 0xf9, 0x06, 0x14, 0xdc, 0x2a, 0x7c, 0x38, 0xcf, 0x42, 0xf2, 0x83, 0x86, 0xd1, 0x52, 0xce,
+ 0xd1, 0x65, 0x6d, 0x6d, 0x37, 0x14, 0x89, 0xfe, 0xd8, 0x7b, 0xbf, 0x15, 0x58, 0xca, 0x4b, 0x50,
+ 0xf0, 0xc6, 0xbe, 0x6b, 0x3a, 0xd8, 0x42, 0x03, 0x42, 0xa6, 0x2e, 0x67, 0xa5, 0x72, 0x06, 0x52,
+ 0x8d, 0xe1, 0xc8, 0x39, 0x29, 0xff, 0x22, 0xe4, 0x39, 0xe8, 0x69, 0x7f, 0xe2, 0x90, 0x3b, 0x90,
+ 0x19, 0xf2, 0xf9, 0x4a, 0x78, 0xdd, 0x13, 0x35, 0xe5, 0xe3, 0xdc, 0xdf, 0x86, 0x8b, 0x5e, 0xaa,
+ 0x42, 0x46, 0xf0, 0xa5, 0xfc, 0xa8, 0xcb, 0xe2, 0x51, 0x67, 0x4e, 0x21, 0x21, 0x38, 0x85, 0xf2,
+ 0x16, 0x64, 0x58, 0x04, 0x9c, 0x60, 0x54, 0x67, 0xa9, 0x22, 0x13, 0x13, 0xdb, 0xf9, 0x3c, 0xab,
+ 0x63, 0x17, 0x95, 0xab, 0x90, 0x47, 0xc1, 0x72, 0x04, 0x73, 0x9d, 0x80, 0x55, 0x4c, 0x6e, 0xbf,
+ 0x9f, 0x82, 0xac, 0xbb, 0x52, 0x64, 0x19, 0xd2, 0x2c, 0x3f, 0x43, 0x53, 0xee, 0xfb, 0x41, 0x0a,
+ 0x33, 0x32, 0xb2, 0x0c, 0x19, 0x9e, 0x83, 0x71, 0xef, 0x2e, 0x57, 0x35, 0x23, 0xcd, 0x72, 0x2e,
+ 0xaf, 0xb1, 0xa6, 0xa3, 0x63, 0x62, 0x2f, 0x03, 0x69, 0x96, 0x55, 0x11, 0x15, 0x72, 0x5e, 0x1e,
+ 0x85, 0xfe, 0x98, 0x3f, 0x03, 0x64, 0xdd, 0xc4, 0x49, 0x40, 0xd4, 0x74, 0xf4, 0x58, 0x3c, 0xe7,
+ 0xcf, 0x36, 0xfd, 0xeb, 0x49, 0xd6, 0xcd, 0x86, 0xf0, 0xf9, 0xde, 0x4d, 0xf0, 0x33, 0x3c, 0xff,
+ 0xf1, 0x01, 0x35, 0x1d, 0x5d, 0x82, 0x9b, 0xcd, 0x67, 0x78, 0x8e, 0x43, 0xae, 0xd2, 0x21, 0x62,
+ 0xce, 0x82, 0x47, 0xdf, 0x4f, 0xdd, 0xd3, 0x2c, 0x93, 0x21, 0xd7, 0xa8, 0x05, 0x96, 0x98, 0xe0,
+ 0xb9, 0xf4, 0xf3, 0xf4, 0x0c, 0xcf, 0x57, 0xc8, 0x4d, 0x0a, 0x61, 0xcb, 0x5f, 0x82, 0x88, 0xa4,
+ 0x3c, 0xc3, 0x93, 0x72, 0xa2, 0xd2, 0x0e, 0xd1, 0x3d, 0xa0, 0x4b, 0x10, 0x12, 0xf0, 0x34, 0x4b,
+ 0xc0, 0xc9, 0x15, 0x34, 0xc7, 0x26, 0x55, 0xf0, 0x93, 0xed, 0x0c, 0x4f, 0x70, 0xfc, 0x76, 0xbc,
+ 0xb2, 0x79, 0x89, 0x75, 0x86, 0xa7, 0x30, 0xa4, 0x46, 0xf7, 0x8b, 0xea, 0xbb, 0x34, 0x8f, 0x4e,
+ 0xb0, 0xe4, 0x0b, 0xcf, 0xdd, 0x53, 0xe6, 0x03, 0xeb, 0xcc, 0x83, 0x18, 0xa9, 0x26, 0x9e, 0x86,
+ 0x25, 0xca, 0xdb, 0xe9, 0x5b, 0x87, 0xa5, 0x22, 0xae, 0x44, 0xa2, 0x6f, 0x1d, 0x1a, 0xa9, 0x26,
+ 0xad, 0x61, 0x1a, 0xd8, 0xa6, 0x6d, 0x0a, 0xb6, 0x25, 0x6f, 0xb3, 0x46, 0x5a, 0x45, 0x4a, 0x90,
+ 0x6a, 0xb6, 0xb7, 0x3b, 0x56, 0x69, 0x81, 0xf1, 0xac, 0x8e, 0x65, 0x24, 0x9b, 0xdb, 0x1d, 0x8b,
+ 0xbc, 0x05, 0x89, 0xc9, 0xd1, 0x7e, 0x89, 0x84, 0xbf, 0xac, 0xec, 0x1e, 0xed, 0xbb, 0x43, 0x31,
+ 0x28, 0x82, 0x2c, 0x43, 0x76, 0xe2, 0x8c, 0xdb, 0xbf, 0x60, 0x8e, 0xed, 0xd2, 0x79, 0x5c, 0xc2,
+ 0x73, 0x46, 0x66, 0xe2, 0x8c, 0x3f, 0x30, 0xc7, 0xf6, 0x19, 0x9d, 0x5f, 0xf9, 0x0a, 0xe4, 0x05,
+ 0xbb, 0xa4, 0x08, 0x92, 0xc5, 0x6e, 0x0a, 0x75, 0xe9, 0x8e, 0x21, 0x59, 0xe5, 0x3d, 0x28, 0xb8,
+ 0x39, 0x0c, 0xce, 0x57, 0xa3, 0x27, 0x69, 0x60, 0x8f, 0xf1, 0x7c, 0xce, 0x6b, 0x97, 0xc4, 0x10,
+ 0xe5, 0xc3, 0x78, 0xb8, 0x60, 0xd0, 0xb2, 0x12, 0x1a, 0x8a, 0x54, 0xfe, 0xa1, 0x04, 0x85, 0x2d,
+ 0x7b, 0xec, 0x3f, 0x30, 0x2f, 0x42, 0x6a, 0xdf, 0xb6, 0x07, 0x13, 0x34, 0x9b, 0x35, 0x58, 0x81,
+ 0xbc, 0x01, 0x05, 0xfc, 0xe1, 0xe6, 0x9e, 0xb2, 0xf7, 0xb4, 0x91, 0xc7, 0x7a, 0x9e, 0x70, 0x12,
+ 0x48, 0xf6, 0x2d, 0x67, 0xc2, 0x3d, 0x19, 0xfe, 0x26, 0x5f, 0x80, 0x3c, 0xfd, 0xeb, 0x32, 0x93,
+ 0xde, 0x85, 0x15, 0x68, 0x35, 0x27, 0xbe, 0x05, 0x73, 0xb8, 0xfb, 0x1e, 0x2c, 0xe3, 0x3d, 0x63,
+ 0x14, 0x58, 0x03, 0x07, 0x96, 0x20, 0xc3, 0x5c, 0xc1, 0x04, 0xbf, 0x96, 0xe5, 0x0c, 0xb7, 0x48,
+ 0xdd, 0x2b, 0x66, 0x02, 0x2c, 0xdc, 0x67, 0x0c, 0x5e, 0x2a, 0x3f, 0x80, 0x2c, 0x46, 0xa9, 0xd6,
+ 0xa0, 0x4b, 0xca, 0x20, 0xf5, 0x4a, 0x26, 0xc6, 0xc8, 0x45, 0xe1, 0x9a, 0xcf, 0x9b, 0x57, 0x36,
+ 0x0c, 0xa9, 0xb7, 0xb4, 0x00, 0xd2, 0x06, 0xbd, 0x77, 0x1f, 0x73, 0x37, 0x2d, 0x1d, 0x97, 0x5b,
+ 0xdc, 0xc4, 0xb6, 0xf9, 0x32, 0xce, 0xc4, 0xb6, 0xf9, 0x92, 0x99, 0xb8, 0x3a, 0x65, 0x82, 0x96,
+ 0x4e, 0xf8, 0xa7, 0x43, 0xe9, 0xa4, 0x5c, 0x85, 0x39, 0x3c, 0x9e, 0x7d, 0xab, 0xb7, 0x63, 0xf7,
+ 0x2d, 0xbc, 0xe7, 0x1f, 0xe2, 0x3d, 0x49, 0x32, 0xa4, 0x43, 0xba, 0x07, 0xe6, 0x71, 0xe7, 0x80,
+ 0xdd, 0x38, 0xb3, 0x06, 0x2b, 0x94, 0x3f, 0x4b, 0xc2, 0x3c, 0x77, 0xad, 0xef, 0xf7, 0x9d, 0x67,
+ 0x5b, 0x9d, 0x11, 0x79, 0x0a, 0x05, 0xea, 0x55, 0xdb, 0xc3, 0xce, 0x68, 0x44, 0x8f, 0xaf, 0x84,
+ 0x57, 0x8d, 0xeb, 0x53, 0xae, 0x9a, 0xe3, 0x57, 0xb6, 0x3b, 0x43, 0x73, 0x8b, 0x61, 0x1b, 0x96,
+ 0x33, 0x3e, 0x31, 0xf2, 0x96, 0x5f, 0x43, 0x36, 0x21, 0x3f, 0x9c, 0xf4, 0x3c, 0x63, 0x32, 0x1a,
+ 0xab, 0x44, 0x1a, 0xdb, 0x9a, 0xf4, 0x02, 0xb6, 0x60, 0xe8, 0x55, 0xd0, 0x81, 0x51, 0x7f, 0xec,
+ 0xd9, 0x4a, 0x9c, 0x32, 0x30, 0xea, 0x3a, 0x82, 0x03, 0xdb, 0xf7, 0x6b, 0xc8, 0x63, 0x00, 0x7a,
+ 0xbc, 0x1c, 0x9b, 0xa6, 0x4e, 0xa8, 0xa0, 0xbc, 0xf6, 0x66, 0xa4, 0xad, 0x5d, 0x67, 0xbc, 0x67,
+ 0xef, 0x3a, 0x63, 0x66, 0x88, 0x1e, 0x4c, 0x2c, 0x2e, 0xbd, 0x03, 0x4a, 0x78, 0xfe, 0xe2, 0x8d,
+ 0x3c, 0x35, 0xe3, 0x46, 0x9e, 0xe3, 0x37, 0xf2, 0xba, 0x7c, 0x57, 0x5a, 0x7a, 0x0f, 0x8a, 0xa1,
+ 0x29, 0x8b, 0x74, 0xc2, 0xe8, 0xb7, 0x45, 0x7a, 0x5e, 0x7b, 0x5d, 0xf8, 0x9c, 0x2d, 0x6e, 0xb8,
+ 0x68, 0xf7, 0x1d, 0x50, 0xc2, 0xd3, 0x17, 0x0d, 0x67, 0x63, 0x32, 0x05, 0xe4, 0xdf, 0x87, 0xb9,
+ 0xc0, 0x94, 0x45, 0x72, 0xee, 0x94, 0x49, 0x95, 0x7f, 0x29, 0x05, 0xa9, 0x96, 0x65, 0xda, 0x87,
+ 0xe4, 0xf5, 0x60, 0x9c, 0x7c, 0x72, 0xce, 0x8d, 0x91, 0x17, 0x43, 0x31, 0xf2, 0xc9, 0x39, 0x2f,
+ 0x42, 0x5e, 0x0c, 0x45, 0x48, 0xb7, 0xa9, 0xa6, 0x93, 0xcb, 0x53, 0xf1, 0xf1, 0xc9, 0x39, 0x21,
+ 0x38, 0x5e, 0x9e, 0x0a, 0x8e, 0x7e, 0x73, 0x4d, 0xa7, 0x0e, 0x35, 0x18, 0x19, 0x9f, 0x9c, 0xf3,
+ 0xa3, 0xe2, 0x72, 0x38, 0x2a, 0x7a, 0x8d, 0x35, 0x9d, 0x0d, 0x49, 0x88, 0x88, 0x38, 0x24, 0x16,
+ 0x0b, 0x97, 0xc3, 0xb1, 0x10, 0x79, 0x3c, 0x0a, 0x2e, 0x87, 0xa3, 0x20, 0x36, 0xf2, 0xa8, 0x77,
+ 0x31, 0x14, 0xf5, 0xd0, 0x28, 0x0b, 0x77, 0xcb, 0xe1, 0x70, 0xc7, 0x78, 0xc2, 0x48, 0xc5, 0x58,
+ 0xe7, 0x35, 0xd6, 0x74, 0xa2, 0x85, 0x02, 0x5d, 0xf4, 0x6d, 0x1f, 0xf7, 0x02, 0x9d, 0xbe, 0x4e,
+ 0x97, 0xcd, 0xbd, 0x88, 0x16, 0x63, 0xbe, 0xf8, 0xe3, 0x6a, 0xba, 0x17, 0x31, 0x0d, 0x32, 0x87,
+ 0x3c, 0x01, 0x56, 0xd0, 0x73, 0x09, 0xb2, 0xc4, 0xcd, 0x5f, 0x69, 0xb6, 0xd1, 0x83, 0xd1, 0x79,
+ 0x1d, 0xb2, 0x3b, 0x7d, 0x05, 0xe6, 0x9a, 0xed, 0xa7, 0x9d, 0x71, 0xcf, 0x9c, 0x38, 0xed, 0xbd,
+ 0x4e, 0xcf, 0x7b, 0x44, 0xa0, 0xfb, 0x9f, 0x6f, 0xf2, 0x96, 0xbd, 0x4e, 0x8f, 0x5c, 0x70, 0xc5,
+ 0xd5, 0xc5, 0x56, 0x89, 0xcb, 0x6b, 0xe9, 0x75, 0xba, 0x68, 0xcc, 0x18, 0xfa, 0xc2, 0x05, 0xee,
+ 0x0b, 0x1f, 0x66, 0x20, 0x75, 0x64, 0xf5, 0x6d, 0xeb, 0x61, 0x0e, 0x32, 0x8e, 0x3d, 0x1e, 0x76,
+ 0x1c, 0xbb, 0xfc, 0x23, 0x09, 0xe0, 0x91, 0x3d, 0x1c, 0x1e, 0x59, 0xfd, 0x17, 0x47, 0x26, 0xb9,
+ 0x02, 0xf9, 0x61, 0xe7, 0xb9, 0xd9, 0x1e, 0x9a, 0xed, 0x83, 0xb1, 0x7b, 0x0e, 0x72, 0xb4, 0x6a,
+ 0xcb, 0x7c, 0x34, 0x3e, 0x21, 0x25, 0xf7, 0x8a, 0x8e, 0xda, 0x41, 0x49, 0xf2, 0x2b, 0xfb, 0x22,
+ 0xbf, 0x74, 0xa6, 0xf9, 0x1e, 0xba, 0xd7, 0x4e, 0x96, 0x47, 0x64, 0xf8, 0xee, 0x61, 0x89, 0x4a,
+ 0xde, 0x31, 0x87, 0xa3, 0xf6, 0x01, 0x4a, 0x85, 0xca, 0x21, 0x45, 0xcb, 0x8f, 0xc8, 0x6d, 0x48,
+ 0x1c, 0xd8, 0x03, 0x14, 0xc9, 0x29, 0xfb, 0x42, 0x71, 0xe4, 0x0d, 0x48, 0x0c, 0x27, 0x4c, 0x36,
+ 0x79, 0x6d, 0x41, 0xb8, 0x27, 0xb0, 0xd0, 0x44, 0x61, 0xc3, 0x49, 0xcf, 0x9b, 0xf7, 0x8d, 0x22,
+ 0x24, 0x9a, 0xad, 0x16, 0x8d, 0xfd, 0xcd, 0x56, 0x6b, 0x4d, 0x91, 0xea, 0x5f, 0x82, 0x6c, 0x6f,
+ 0x6c, 0x9a, 0xd4, 0x3d, 0xcc, 0xce, 0x39, 0x3e, 0xc4, 0x58, 0xe7, 0x81, 0xea, 0x5b, 0x90, 0x39,
+ 0x60, 0x59, 0x07, 0x89, 0x48, 0x6b, 0x4b, 0x7f, 0xc8, 0x1e, 0x55, 0x96, 0xfc, 0xe6, 0x70, 0x9e,
+ 0x62, 0xb8, 0x36, 0xea, 0x3b, 0x90, 0x1b, 0xb7, 0x4f, 0x33, 0xf8, 0x31, 0x8b, 0x2e, 0x71, 0x06,
+ 0xb3, 0x63, 0x5e, 0x55, 0x6f, 0xc0, 0x82, 0x65, 0xbb, 0xdf, 0x50, 0xda, 0x5d, 0x76, 0xc6, 0x2e,
+ 0x4e, 0x5f, 0xe5, 0x5c, 0xe3, 0x26, 0xfb, 0x6e, 0x69, 0xd9, 0xbc, 0x81, 0x9d, 0xca, 0xfa, 0x23,
+ 0x50, 0x04, 0x33, 0x98, 0x7a, 0xc6, 0x59, 0x39, 0x64, 0x1f, 0x4a, 0x3d, 0x2b, 0x78, 0xee, 0x43,
+ 0x46, 0xd8, 0xc9, 0x8c, 0x31, 0xd2, 0x63, 0x5f, 0x9d, 0x3d, 0x23, 0xe8, 0xea, 0xa6, 0x8d, 0x50,
+ 0x5f, 0x13, 0x6d, 0xe4, 0x19, 0xfb, 0x20, 0x2d, 0x1a, 0xa9, 0xe9, 0xa1, 0x55, 0x39, 0x3a, 0x75,
+ 0x28, 0x7d, 0xf6, 0x3d, 0xd9, 0xb3, 0xc2, 0x1c, 0xe0, 0x0c, 0x33, 0xf1, 0x83, 0xf9, 0x90, 0x7d,
+ 0x6a, 0x0e, 0x98, 0x99, 0x1a, 0xcd, 0xe4, 0xd4, 0xd1, 0x3c, 0x67, 0xdf, 0x75, 0x3d, 0x33, 0xbb,
+ 0xb3, 0x46, 0x33, 0x39, 0x75, 0x34, 0x03, 0xf6, 0xc5, 0x37, 0x60, 0xa6, 0xa6, 0xd7, 0x37, 0x80,
+ 0x88, 0x5b, 0xcd, 0xe3, 0x44, 0x8c, 0x9d, 0x21, 0xfb, 0x8e, 0xef, 0x6f, 0x36, 0xa3, 0xcc, 0x32,
+ 0x14, 0x3f, 0x20, 0x8b, 0x7d, 0xe2, 0x0f, 0x1a, 0xaa, 0xe9, 0xf5, 0x4d, 0x38, 0x2f, 0x4e, 0xec,
+ 0x0c, 0x43, 0xb2, 0x55, 0xa9, 0x52, 0x34, 0x16, 0xfc, 0xa9, 0x71, 0xce, 0x4c, 0x53, 0xf1, 0x83,
+ 0x1a, 0xa9, 0x52, 0x45, 0x99, 0x32, 0x55, 0xd3, 0xeb, 0x0f, 0xa0, 0x28, 0x98, 0xda, 0xc7, 0x08,
+ 0x1d, 0x6d, 0xe6, 0x05, 0xfb, 0x5f, 0x0b, 0xcf, 0x0c, 0x8d, 0xe8, 0xe1, 0x1d, 0xe3, 0x31, 0x2e,
+ 0xda, 0xc8, 0x98, 0xfd, 0xa3, 0x80, 0x3f, 0x16, 0x64, 0x84, 0x8e, 0x04, 0xe6, 0xdf, 0x71, 0x56,
+ 0x26, 0xec, 0x5f, 0x08, 0xfc, 0xa1, 0x50, 0x42, 0xbd, 0x1f, 0x98, 0x8e, 0x49, 0x83, 0x5c, 0x8c,
+ 0x0d, 0x07, 0x3d, 0xf2, 0x9b, 0x91, 0x80, 0x15, 0xf1, 0x81, 0x44, 0x98, 0x36, 0x2d, 0xd6, 0x37,
+ 0x61, 0xfe, 0xec, 0x0e, 0xe9, 0x63, 0x89, 0x65, 0xcb, 0xd5, 0x15, 0x9a, 0x50, 0x1b, 0x73, 0xdd,
+ 0x80, 0x5f, 0x6a, 0xc0, 0xdc, 0x99, 0x9d, 0xd2, 0x27, 0x12, 0xcb, 0x39, 0xa9, 0x25, 0xa3, 0xd0,
+ 0x0d, 0x7a, 0xa6, 0xb9, 0x33, 0xbb, 0xa5, 0x4f, 0x25, 0xf6, 0x40, 0xa1, 0x6b, 0x9e, 0x11, 0xd7,
+ 0x33, 0xcd, 0x9d, 0xd9, 0x2d, 0x7d, 0x95, 0x65, 0x94, 0xb2, 0x5e, 0x15, 0x8d, 0xa0, 0x2f, 0x98,
+ 0x3f, 0xbb, 0x5b, 0xfa, 0x9a, 0x84, 0x8f, 0x15, 0xb2, 0xae, 0x7b, 0xeb, 0xe2, 0x79, 0xa6, 0xf9,
+ 0xb3, 0xbb, 0xa5, 0xaf, 0x4b, 0xf8, 0xa4, 0x21, 0xeb, 0xeb, 0x01, 0x33, 0xc1, 0xd1, 0x9c, 0xee,
+ 0x96, 0xbe, 0x21, 0xe1, 0x2b, 0x83, 0xac, 0xd7, 0x3c, 0x33, 0xbb, 0x53, 0xa3, 0x39, 0xdd, 0x2d,
+ 0x7d, 0x13, 0x6f, 0xf1, 0x75, 0x59, 0xbf, 0x13, 0x30, 0x83, 0x9e, 0xa9, 0xf8, 0x0a, 0x6e, 0xe9,
+ 0x5b, 0x12, 0x3e, 0x06, 0xc9, 0xfa, 0x5d, 0xc3, 0xed, 0xdd, 0xf7, 0x4c, 0xc5, 0x57, 0x70, 0x4b,
+ 0x9f, 0x49, 0xf8, 0x66, 0x24, 0xeb, 0xf7, 0x82, 0x86, 0xd0, 0x33, 0x29, 0xaf, 0xe2, 0x96, 0xbe,
+ 0x4d, 0x2d, 0x15, 0xeb, 0xf2, 0xfa, 0xaa, 0xe1, 0x0e, 0x40, 0xf0, 0x4c, 0xca, 0xab, 0xb8, 0xa5,
+ 0xef, 0x50, 0x53, 0x4a, 0x5d, 0x5e, 0x5f, 0x0b, 0x99, 0xaa, 0xe9, 0xf5, 0x47, 0x50, 0x38, 0xab,
+ 0x5b, 0xfa, 0xae, 0xf8, 0x16, 0x97, 0xef, 0x0a, 0xbe, 0x69, 0x47, 0xd8, 0xb3, 0x53, 0x1d, 0xd3,
+ 0xf7, 0x30, 0xc7, 0xa9, 0xcf, 0x3d, 0x61, 0xef, 0x55, 0x8c, 0xe0, 0x6f, 0x1f, 0x73, 0x53, 0x5b,
+ 0xfe, 0xf9, 0x38, 0xd5, 0x47, 0x7d, 0x5f, 0xc2, 0x47, 0xad, 0x02, 0x37, 0x88, 0x78, 0xef, 0xa4,
+ 0x30, 0x87, 0xf5, 0xa1, 0x3f, 0xcb, 0xd3, 0xbc, 0xd5, 0x0f, 0xa4, 0x57, 0x71, 0x57, 0xf5, 0x44,
+ 0x6b, 0xbb, 0xe1, 0x2d, 0x06, 0xd6, 0xbc, 0x0d, 0xc9, 0x63, 0x6d, 0x75, 0x4d, 0xbc, 0x92, 0x89,
+ 0x6f, 0xb9, 0xcc, 0x49, 0xe5, 0xb5, 0xa2, 0xf0, 0xdc, 0x3d, 0x1c, 0x39, 0x27, 0x06, 0xb2, 0x38,
+ 0x5b, 0x8b, 0x64, 0x7f, 0x12, 0xc3, 0xd6, 0x38, 0xbb, 0x1a, 0xc9, 0xfe, 0x34, 0x86, 0x5d, 0xe5,
+ 0x6c, 0x3d, 0x92, 0xfd, 0xd5, 0x18, 0xb6, 0xce, 0xd9, 0xeb, 0x91, 0xec, 0xaf, 0xc5, 0xb0, 0xd7,
+ 0x39, 0xbb, 0x16, 0xc9, 0xfe, 0x7a, 0x0c, 0xbb, 0xc6, 0xd9, 0x77, 0x22, 0xd9, 0xdf, 0x88, 0x61,
+ 0xdf, 0xe1, 0xec, 0xbb, 0x91, 0xec, 0x6f, 0xc6, 0xb0, 0xef, 0x72, 0xf6, 0xbd, 0x48, 0xf6, 0xb7,
+ 0x62, 0xd8, 0xf7, 0x18, 0x7b, 0x6d, 0x35, 0x92, 0xfd, 0x59, 0x34, 0x7b, 0x6d, 0x95, 0xb3, 0xa3,
+ 0xb5, 0xf6, 0xed, 0x18, 0x36, 0xd7, 0xda, 0x5a, 0xb4, 0xd6, 0xbe, 0x13, 0xc3, 0xe6, 0x5a, 0x5b,
+ 0x8b, 0xd6, 0xda, 0x77, 0x63, 0xd8, 0x5c, 0x6b, 0x6b, 0xd1, 0x5a, 0xfb, 0x5e, 0x0c, 0x9b, 0x6b,
+ 0x6d, 0x2d, 0x5a, 0x6b, 0xdf, 0x8f, 0x61, 0x73, 0xad, 0xad, 0x45, 0x6b, 0xed, 0x07, 0x31, 0x6c,
+ 0xae, 0xb5, 0xb5, 0x68, 0xad, 0xfd, 0x51, 0x0c, 0x9b, 0x6b, 0x6d, 0x2d, 0x5a, 0x6b, 0x7f, 0x1c,
+ 0xc3, 0xe6, 0x5a, 0x5b, 0x8b, 0xd6, 0xda, 0x9f, 0xc4, 0xb0, 0xb9, 0xd6, 0xb4, 0x68, 0xad, 0xfd,
+ 0x69, 0x34, 0x5b, 0xe3, 0x5a, 0xd3, 0xa2, 0xb5, 0xf6, 0x67, 0x31, 0x6c, 0xae, 0x35, 0x2d, 0x5a,
+ 0x6b, 0x7f, 0x1e, 0xc3, 0xe6, 0x5a, 0xd3, 0xa2, 0xb5, 0xf6, 0xc3, 0x18, 0x36, 0xd7, 0x9a, 0x16,
+ 0xad, 0xb5, 0xbf, 0x88, 0x61, 0x73, 0xad, 0x69, 0xd1, 0x5a, 0xfb, 0xcb, 0x18, 0x36, 0xd7, 0x9a,
+ 0x16, 0xad, 0xb5, 0xbf, 0x8a, 0x61, 0x73, 0xad, 0x69, 0xd1, 0x5a, 0xfb, 0xeb, 0x18, 0x36, 0xd7,
+ 0x9a, 0x16, 0xad, 0xb5, 0xbf, 0x89, 0x61, 0x73, 0xad, 0x69, 0xd1, 0x5a, 0xfb, 0xdb, 0x18, 0x36,
+ 0xd7, 0x5a, 0x35, 0x5a, 0x6b, 0x7f, 0x17, 0xcd, 0xae, 0x72, 0xad, 0x55, 0xa3, 0xb5, 0xf6, 0xf7,
+ 0x31, 0x6c, 0xae, 0xb5, 0x6a, 0xb4, 0xd6, 0xfe, 0x21, 0x86, 0xcd, 0xb5, 0x56, 0x8d, 0xd6, 0xda,
+ 0x3f, 0xc6, 0xb0, 0xb9, 0xd6, 0xaa, 0xd1, 0x5a, 0xfb, 0x51, 0x0c, 0x9b, 0x6b, 0xad, 0x1a, 0xad,
+ 0xb5, 0x7f, 0x8a, 0x61, 0x73, 0xad, 0x55, 0xa3, 0xb5, 0xf6, 0xcf, 0x31, 0x6c, 0xae, 0xb5, 0x6a,
+ 0xb4, 0xd6, 0xfe, 0x25, 0x86, 0xcd, 0xb5, 0x56, 0x8d, 0xd6, 0xda, 0xbf, 0xc6, 0xb0, 0xb9, 0xd6,
+ 0xaa, 0xd1, 0x5a, 0xfb, 0xb7, 0x18, 0x36, 0xd7, 0x9a, 0x1e, 0xad, 0xb5, 0x7f, 0x8f, 0x66, 0xeb,
+ 0x5c, 0x6b, 0x7a, 0xb4, 0xd6, 0xfe, 0x23, 0x86, 0xcd, 0xb5, 0xa6, 0x47, 0x6b, 0xed, 0x3f, 0x63,
+ 0xd8, 0x5c, 0x6b, 0x7a, 0xb4, 0xd6, 0xfe, 0x2b, 0x86, 0xcd, 0xb5, 0xa6, 0x47, 0x6b, 0xed, 0xbf,
+ 0x63, 0xd8, 0x5c, 0x6b, 0x7a, 0xb4, 0xd6, 0xfe, 0x27, 0x86, 0xcd, 0xb5, 0xa6, 0x47, 0x6b, 0xed,
+ 0xc7, 0x31, 0x6c, 0xae, 0x35, 0x3d, 0x5a, 0x6b, 0x3f, 0x89, 0x61, 0x73, 0xad, 0xe9, 0xd1, 0x5a,
+ 0xfb, 0xdf, 0x18, 0x36, 0xd7, 0x9a, 0x1e, 0xad, 0xb5, 0xff, 0x8b, 0x61, 0x73, 0xad, 0xad, 0x47,
+ 0x6b, 0xed, 0xff, 0xa3, 0xd9, 0xeb, 0xab, 0x3f, 0x0d, 0x00, 0x00, 0xff, 0xff, 0xaa, 0x00, 0xcd,
+ 0x32, 0x57, 0x39, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/proto/testdata/test.proto b/vendor/github.com/golang/protobuf/proto/testdata/test.proto
new file mode 100644
index 0000000..70e3cfc
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/proto/testdata/test.proto
@@ -0,0 +1,548 @@
+// 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 feature-rich test file for the protocol compiler and libraries.
+
+syntax = "proto2";
+
+package testdata;
+
+enum FOO { FOO1 = 1; };
+
+message GoEnum {
+ required FOO foo = 1;
+}
+
+message GoTestField {
+ required string Label = 1;
+ required string Type = 2;
+}
+
+message GoTest {
+ // An enum, for completeness.
+ enum KIND {
+ VOID = 0;
+
+ // Basic types
+ BOOL = 1;
+ BYTES = 2;
+ FINGERPRINT = 3;
+ FLOAT = 4;
+ INT = 5;
+ STRING = 6;
+ TIME = 7;
+
+ // Groupings
+ TUPLE = 8;
+ ARRAY = 9;
+ MAP = 10;
+
+ // Table types
+ TABLE = 11;
+
+ // Functions
+ FUNCTION = 12; // last tag
+ };
+
+ // Some typical parameters
+ required KIND Kind = 1;
+ optional string Table = 2;
+ optional int32 Param = 3;
+
+ // Required, repeated and optional foreign fields.
+ required GoTestField RequiredField = 4;
+ repeated GoTestField RepeatedField = 5;
+ optional GoTestField OptionalField = 6;
+
+ // Required fields of all basic types
+ required bool F_Bool_required = 10;
+ required int32 F_Int32_required = 11;
+ required int64 F_Int64_required = 12;
+ required fixed32 F_Fixed32_required = 13;
+ required fixed64 F_Fixed64_required = 14;
+ required uint32 F_Uint32_required = 15;
+ required uint64 F_Uint64_required = 16;
+ required float F_Float_required = 17;
+ required double F_Double_required = 18;
+ required string F_String_required = 19;
+ required bytes F_Bytes_required = 101;
+ required sint32 F_Sint32_required = 102;
+ required sint64 F_Sint64_required = 103;
+
+ // Repeated fields of all basic types
+ repeated bool F_Bool_repeated = 20;
+ repeated int32 F_Int32_repeated = 21;
+ repeated int64 F_Int64_repeated = 22;
+ repeated fixed32 F_Fixed32_repeated = 23;
+ repeated fixed64 F_Fixed64_repeated = 24;
+ repeated uint32 F_Uint32_repeated = 25;
+ repeated uint64 F_Uint64_repeated = 26;
+ repeated float F_Float_repeated = 27;
+ repeated double F_Double_repeated = 28;
+ repeated string F_String_repeated = 29;
+ repeated bytes F_Bytes_repeated = 201;
+ repeated sint32 F_Sint32_repeated = 202;
+ repeated sint64 F_Sint64_repeated = 203;
+
+ // Optional fields of all basic types
+ optional bool F_Bool_optional = 30;
+ optional int32 F_Int32_optional = 31;
+ optional int64 F_Int64_optional = 32;
+ optional fixed32 F_Fixed32_optional = 33;
+ optional fixed64 F_Fixed64_optional = 34;
+ optional uint32 F_Uint32_optional = 35;
+ optional uint64 F_Uint64_optional = 36;
+ optional float F_Float_optional = 37;
+ optional double F_Double_optional = 38;
+ optional string F_String_optional = 39;
+ optional bytes F_Bytes_optional = 301;
+ optional sint32 F_Sint32_optional = 302;
+ optional sint64 F_Sint64_optional = 303;
+
+ // Default-valued fields of all basic types
+ optional bool F_Bool_defaulted = 40 [default=true];
+ optional int32 F_Int32_defaulted = 41 [default=32];
+ optional int64 F_Int64_defaulted = 42 [default=64];
+ optional fixed32 F_Fixed32_defaulted = 43 [default=320];
+ optional fixed64 F_Fixed64_defaulted = 44 [default=640];
+ optional uint32 F_Uint32_defaulted = 45 [default=3200];
+ optional uint64 F_Uint64_defaulted = 46 [default=6400];
+ optional float F_Float_defaulted = 47 [default=314159.];
+ optional double F_Double_defaulted = 48 [default=271828.];
+ optional string F_String_defaulted = 49 [default="hello, \"world!\"\n"];
+ optional bytes F_Bytes_defaulted = 401 [default="Bignose"];
+ optional sint32 F_Sint32_defaulted = 402 [default = -32];
+ optional sint64 F_Sint64_defaulted = 403 [default = -64];
+
+ // Packed repeated fields (no string or bytes).
+ repeated bool F_Bool_repeated_packed = 50 [packed=true];
+ repeated int32 F_Int32_repeated_packed = 51 [packed=true];
+ repeated int64 F_Int64_repeated_packed = 52 [packed=true];
+ repeated fixed32 F_Fixed32_repeated_packed = 53 [packed=true];
+ repeated fixed64 F_Fixed64_repeated_packed = 54 [packed=true];
+ repeated uint32 F_Uint32_repeated_packed = 55 [packed=true];
+ repeated uint64 F_Uint64_repeated_packed = 56 [packed=true];
+ repeated float F_Float_repeated_packed = 57 [packed=true];
+ repeated double F_Double_repeated_packed = 58 [packed=true];
+ repeated sint32 F_Sint32_repeated_packed = 502 [packed=true];
+ repeated sint64 F_Sint64_repeated_packed = 503 [packed=true];
+
+ // Required, repeated, and optional groups.
+ required group RequiredGroup = 70 {
+ required string RequiredField = 71;
+ };
+
+ repeated group RepeatedGroup = 80 {
+ required string RequiredField = 81;
+ };
+
+ optional group OptionalGroup = 90 {
+ required string RequiredField = 91;
+ };
+}
+
+// For testing a group containing a required field.
+message GoTestRequiredGroupField {
+ required group Group = 1 {
+ required int32 Field = 2;
+ };
+}
+
+// For testing skipping of unrecognized fields.
+// Numbers are all big, larger than tag numbers in GoTestField,
+// the message used in the corresponding test.
+message GoSkipTest {
+ required int32 skip_int32 = 11;
+ required fixed32 skip_fixed32 = 12;
+ required fixed64 skip_fixed64 = 13;
+ required string skip_string = 14;
+ required group SkipGroup = 15 {
+ required int32 group_int32 = 16;
+ required string group_string = 17;
+ }
+}
+
+// For testing packed/non-packed decoder switching.
+// A serialized instance of one should be deserializable as the other.
+message NonPackedTest {
+ repeated int32 a = 1;
+}
+
+message PackedTest {
+ repeated int32 b = 1 [packed=true];
+}
+
+message MaxTag {
+ // Maximum possible tag number.
+ optional string last_field = 536870911;
+}
+
+message OldMessage {
+ message Nested {
+ optional string name = 1;
+ }
+ optional Nested nested = 1;
+
+ optional int32 num = 2;
+}
+
+// NewMessage is wire compatible with OldMessage;
+// imagine it as a future version.
+message NewMessage {
+ message Nested {
+ optional string name = 1;
+ optional string food_group = 2;
+ }
+ optional Nested nested = 1;
+
+ // This is an int32 in OldMessage.
+ optional int64 num = 2;
+}
+
+// Smaller tests for ASCII formatting.
+
+message InnerMessage {
+ required string host = 1;
+ optional int32 port = 2 [default=4000];
+ optional bool connected = 3;
+}
+
+message OtherMessage {
+ optional int64 key = 1;
+ optional bytes value = 2;
+ optional float weight = 3;
+ optional InnerMessage inner = 4;
+
+ extensions 100 to max;
+}
+
+message RequiredInnerMessage {
+ required InnerMessage leo_finally_won_an_oscar = 1;
+}
+
+message MyMessage {
+ required int32 count = 1;
+ optional string name = 2;
+ optional string quote = 3;
+ repeated string pet = 4;
+ optional InnerMessage inner = 5;
+ repeated OtherMessage others = 6;
+ optional RequiredInnerMessage we_must_go_deeper = 13;
+ repeated InnerMessage rep_inner = 12;
+
+ enum Color {
+ RED = 0;
+ GREEN = 1;
+ BLUE = 2;
+ };
+ optional Color bikeshed = 7;
+
+ optional group SomeGroup = 8 {
+ optional int32 group_field = 9;
+ }
+
+ // This field becomes [][]byte in the generated code.
+ repeated bytes rep_bytes = 10;
+
+ optional double bigfloat = 11;
+
+ extensions 100 to max;
+}
+
+message Ext {
+ extend MyMessage {
+ optional Ext more = 103;
+ optional string text = 104;
+ optional int32 number = 105;
+ }
+
+ optional string data = 1;
+}
+
+extend MyMessage {
+ repeated string greeting = 106;
+}
+
+message ComplexExtension {
+ optional int32 first = 1;
+ optional int32 second = 2;
+ repeated int32 third = 3;
+}
+
+extend OtherMessage {
+ optional ComplexExtension complex = 200;
+ repeated ComplexExtension r_complex = 201;
+}
+
+message DefaultsMessage {
+ enum DefaultsEnum {
+ ZERO = 0;
+ ONE = 1;
+ TWO = 2;
+ };
+ extensions 100 to max;
+}
+
+extend DefaultsMessage {
+ optional double no_default_double = 101;
+ optional float no_default_float = 102;
+ optional int32 no_default_int32 = 103;
+ optional int64 no_default_int64 = 104;
+ optional uint32 no_default_uint32 = 105;
+ optional uint64 no_default_uint64 = 106;
+ optional sint32 no_default_sint32 = 107;
+ optional sint64 no_default_sint64 = 108;
+ optional fixed32 no_default_fixed32 = 109;
+ optional fixed64 no_default_fixed64 = 110;
+ optional sfixed32 no_default_sfixed32 = 111;
+ optional sfixed64 no_default_sfixed64 = 112;
+ optional bool no_default_bool = 113;
+ optional string no_default_string = 114;
+ optional bytes no_default_bytes = 115;
+ optional DefaultsMessage.DefaultsEnum no_default_enum = 116;
+
+ optional double default_double = 201 [default = 3.1415];
+ optional float default_float = 202 [default = 3.14];
+ optional int32 default_int32 = 203 [default = 42];
+ optional int64 default_int64 = 204 [default = 43];
+ optional uint32 default_uint32 = 205 [default = 44];
+ optional uint64 default_uint64 = 206 [default = 45];
+ optional sint32 default_sint32 = 207 [default = 46];
+ optional sint64 default_sint64 = 208 [default = 47];
+ optional fixed32 default_fixed32 = 209 [default = 48];
+ optional fixed64 default_fixed64 = 210 [default = 49];
+ optional sfixed32 default_sfixed32 = 211 [default = 50];
+ optional sfixed64 default_sfixed64 = 212 [default = 51];
+ optional bool default_bool = 213 [default = true];
+ optional string default_string = 214 [default = "Hello, string"];
+ optional bytes default_bytes = 215 [default = "Hello, bytes"];
+ optional DefaultsMessage.DefaultsEnum default_enum = 216 [default = ONE];
+}
+
+message MyMessageSet {
+ option message_set_wire_format = true;
+ extensions 100 to max;
+}
+
+message Empty {
+}
+
+extend MyMessageSet {
+ optional Empty x201 = 201;
+ optional Empty x202 = 202;
+ optional Empty x203 = 203;
+ optional Empty x204 = 204;
+ optional Empty x205 = 205;
+ optional Empty x206 = 206;
+ optional Empty x207 = 207;
+ optional Empty x208 = 208;
+ optional Empty x209 = 209;
+ optional Empty x210 = 210;
+ optional Empty x211 = 211;
+ optional Empty x212 = 212;
+ optional Empty x213 = 213;
+ optional Empty x214 = 214;
+ optional Empty x215 = 215;
+ optional Empty x216 = 216;
+ optional Empty x217 = 217;
+ optional Empty x218 = 218;
+ optional Empty x219 = 219;
+ optional Empty x220 = 220;
+ optional Empty x221 = 221;
+ optional Empty x222 = 222;
+ optional Empty x223 = 223;
+ optional Empty x224 = 224;
+ optional Empty x225 = 225;
+ optional Empty x226 = 226;
+ optional Empty x227 = 227;
+ optional Empty x228 = 228;
+ optional Empty x229 = 229;
+ optional Empty x230 = 230;
+ optional Empty x231 = 231;
+ optional Empty x232 = 232;
+ optional Empty x233 = 233;
+ optional Empty x234 = 234;
+ optional Empty x235 = 235;
+ optional Empty x236 = 236;
+ optional Empty x237 = 237;
+ optional Empty x238 = 238;
+ optional Empty x239 = 239;
+ optional Empty x240 = 240;
+ optional Empty x241 = 241;
+ optional Empty x242 = 242;
+ optional Empty x243 = 243;
+ optional Empty x244 = 244;
+ optional Empty x245 = 245;
+ optional Empty x246 = 246;
+ optional Empty x247 = 247;
+ optional Empty x248 = 248;
+ optional Empty x249 = 249;
+ optional Empty x250 = 250;
+}
+
+message MessageList {
+ repeated group Message = 1 {
+ required string name = 2;
+ required int32 count = 3;
+ }
+}
+
+message Strings {
+ optional string string_field = 1;
+ optional bytes bytes_field = 2;
+}
+
+message Defaults {
+ enum Color {
+ RED = 0;
+ GREEN = 1;
+ BLUE = 2;
+ }
+
+ // Default-valued fields of all basic types.
+ // Same as GoTest, but copied here to make testing easier.
+ optional bool F_Bool = 1 [default=true];
+ optional int32 F_Int32 = 2 [default=32];
+ optional int64 F_Int64 = 3 [default=64];
+ optional fixed32 F_Fixed32 = 4 [default=320];
+ optional fixed64 F_Fixed64 = 5 [default=640];
+ optional uint32 F_Uint32 = 6 [default=3200];
+ optional uint64 F_Uint64 = 7 [default=6400];
+ optional float F_Float = 8 [default=314159.];
+ optional double F_Double = 9 [default=271828.];
+ optional string F_String = 10 [default="hello, \"world!\"\n"];
+ optional bytes F_Bytes = 11 [default="Bignose"];
+ optional sint32 F_Sint32 = 12 [default=-32];
+ optional sint64 F_Sint64 = 13 [default=-64];
+ optional Color F_Enum = 14 [default=GREEN];
+
+ // More fields with crazy defaults.
+ optional float F_Pinf = 15 [default=inf];
+ optional float F_Ninf = 16 [default=-inf];
+ optional float F_Nan = 17 [default=nan];
+
+ // Sub-message.
+ optional SubDefaults sub = 18;
+
+ // Redundant but explicit defaults.
+ optional string str_zero = 19 [default=""];
+}
+
+message SubDefaults {
+ optional int64 n = 1 [default=7];
+}
+
+message RepeatedEnum {
+ enum Color {
+ RED = 1;
+ }
+ repeated Color color = 1;
+}
+
+message MoreRepeated {
+ repeated bool bools = 1;
+ repeated bool bools_packed = 2 [packed=true];
+ repeated int32 ints = 3;
+ repeated int32 ints_packed = 4 [packed=true];
+ repeated int64 int64s_packed = 7 [packed=true];
+ repeated string strings = 5;
+ repeated fixed32 fixeds = 6;
+}
+
+// GroupOld and GroupNew have the same wire format.
+// GroupNew has a new field inside a group.
+
+message GroupOld {
+ optional group G = 101 {
+ optional int32 x = 2;
+ }
+}
+
+message GroupNew {
+ optional group G = 101 {
+ optional int32 x = 2;
+ optional int32 y = 3;
+ }
+}
+
+message FloatingPoint {
+ required double f = 1;
+ optional bool exact = 2;
+}
+
+message MessageWithMap {
+ map name_mapping = 1;
+ map msg_mapping = 2;
+ map byte_mapping = 3;
+ map str_to_str = 4;
+}
+
+message Oneof {
+ oneof union {
+ bool F_Bool = 1;
+ int32 F_Int32 = 2;
+ int64 F_Int64 = 3;
+ fixed32 F_Fixed32 = 4;
+ fixed64 F_Fixed64 = 5;
+ uint32 F_Uint32 = 6;
+ uint64 F_Uint64 = 7;
+ float F_Float = 8;
+ double F_Double = 9;
+ string F_String = 10;
+ bytes F_Bytes = 11;
+ sint32 F_Sint32 = 12;
+ sint64 F_Sint64 = 13;
+ MyMessage.Color F_Enum = 14;
+ GoTestField F_Message = 15;
+ group F_Group = 16 {
+ optional int32 x = 17;
+ }
+ int32 F_Largest_Tag = 536870911;
+ }
+
+ oneof tormato {
+ int32 value = 100;
+ }
+}
+
+message Communique {
+ optional bool make_me_cry = 1;
+
+ // This is a oneof, called "union".
+ oneof union {
+ int32 number = 5;
+ string name = 6;
+ bytes data = 7;
+ double temp_c = 8;
+ MyMessage.Color col = 9;
+ Strings msg = 10;
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/proto/text.go b/vendor/github.com/golang/protobuf/proto/text.go
index 754bdd5..965876b 100644
--- a/vendor/github.com/golang/protobuf/proto/text.go
+++ b/vendor/github.com/golang/protobuf/proto/text.go
@@ -37,6 +37,7 @@ import (
"bufio"
"bytes"
"encoding"
+ "errors"
"fmt"
"io"
"log"
@@ -153,7 +154,7 @@ func (w *textWriter) indent() { w.ind++ }
func (w *textWriter) unindent() {
if w.ind == 0 {
- log.Printf("proto: textWriter unindented too far")
+ log.Print("proto: textWriter unindented too far")
return
}
w.ind--
@@ -169,20 +170,98 @@ func writeName(w *textWriter, props *Properties) error {
return nil
}
-var (
- messageSetType = reflect.TypeOf((*MessageSet)(nil)).Elem()
-)
-
// raw is the interface satisfied by RawMessage.
type raw interface {
Bytes() []byte
}
-func writeStruct(w *textWriter, sv reflect.Value) error {
- if sv.Type() == messageSetType {
- return writeMessageSet(w, sv.Addr().Interface().(*MessageSet))
+func requiresQuotes(u string) bool {
+ // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted.
+ for _, ch := range u {
+ switch {
+ case ch == '.' || ch == '/' || ch == '_':
+ continue
+ case '0' <= ch && ch <= '9':
+ continue
+ case 'A' <= ch && ch <= 'Z':
+ continue
+ case 'a' <= ch && ch <= 'z':
+ continue
+ default:
+ return true
+ }
+ }
+ return false
+}
+
+// isAny reports whether sv is a google.protobuf.Any message
+func isAny(sv reflect.Value) bool {
+ type wkt interface {
+ XXX_WellKnownType() string
+ }
+ t, ok := sv.Addr().Interface().(wkt)
+ return ok && t.XXX_WellKnownType() == "Any"
+}
+
+// writeProto3Any writes an expanded google.protobuf.Any message.
+//
+// It returns (false, nil) if sv value can't be unmarshaled (e.g. because
+// required messages are not linked in).
+//
+// It returns (true, error) when sv was written in expanded format or an error
+// was encountered.
+func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) {
+ turl := sv.FieldByName("TypeUrl")
+ val := sv.FieldByName("Value")
+ if !turl.IsValid() || !val.IsValid() {
+ return true, errors.New("proto: invalid google.protobuf.Any message")
}
+ b, ok := val.Interface().([]byte)
+ if !ok {
+ return true, errors.New("proto: invalid google.protobuf.Any message")
+ }
+
+ parts := strings.Split(turl.String(), "/")
+ mt := MessageType(parts[len(parts)-1])
+ if mt == nil {
+ return false, nil
+ }
+ m := reflect.New(mt.Elem())
+ if err := Unmarshal(b, m.Interface().(Message)); err != nil {
+ return false, nil
+ }
+ w.Write([]byte("["))
+ u := turl.String()
+ if requiresQuotes(u) {
+ writeString(w, u)
+ } else {
+ w.Write([]byte(u))
+ }
+ if w.compact {
+ w.Write([]byte("]:<"))
+ } else {
+ w.Write([]byte("]: <\n"))
+ w.ind++
+ }
+ if err := tm.writeStruct(w, m.Elem()); err != nil {
+ return true, err
+ }
+ if w.compact {
+ w.Write([]byte("> "))
+ } else {
+ w.ind--
+ w.Write([]byte(">\n"))
+ }
+ return true, nil
+}
+
+func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error {
+ if tm.ExpandAny && isAny(sv) {
+ if canExpand, err := tm.writeProto3Any(w, sv); canExpand {
+ return err
+ }
+ }
st := sv.Type()
sprops := GetProperties(st)
for i := 0; i < sv.NumField(); i++ {
@@ -234,7 +313,7 @@ func writeStruct(w *textWriter, sv reflect.Value) error {
}
continue
}
- if err := writeAny(w, v, props); err != nil {
+ if err := tm.writeAny(w, v, props); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
@@ -245,7 +324,7 @@ func writeStruct(w *textWriter, sv reflect.Value) error {
}
if fv.Kind() == reflect.Map {
// Map fields are rendered as a repeated struct with key/value fields.
- keys := fv.MapKeys() // TODO: should we sort these for deterministic output?
+ keys := fv.MapKeys()
sort.Sort(mapKeys(keys))
for _, key := range keys {
val := fv.MapIndex(key)
@@ -276,7 +355,7 @@ func writeStruct(w *textWriter, sv reflect.Value) error {
return err
}
}
- if err := writeAny(w, key, props.mkeyprop); err != nil {
+ if err := tm.writeAny(w, key, props.mkeyprop); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
@@ -293,7 +372,7 @@ func writeStruct(w *textWriter, sv reflect.Value) error {
return err
}
}
- if err := writeAny(w, val, props.mvalprop); err != nil {
+ if err := tm.writeAny(w, val, props.mvalprop); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
@@ -317,26 +396,34 @@ func writeStruct(w *textWriter, sv reflect.Value) error {
}
if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
// proto3 non-repeated scalar field; skip if zero value
- switch fv.Kind() {
- case reflect.Bool:
- if !fv.Bool() {
+ if isProto3Zero(fv) {
+ continue
+ }
+ }
+
+ if fv.Kind() == reflect.Interface {
+ // Check if it is a oneof.
+ if st.Field(i).Tag.Get("protobuf_oneof") != "" {
+ // fv is nil, or holds a pointer to generated struct.
+ // That generated struct has exactly one field,
+ // which has a protobuf struct tag.
+ if fv.IsNil() {
continue
}
- case reflect.Int32, reflect.Int64:
- if fv.Int() == 0 {
- continue
- }
- case reflect.Uint32, reflect.Uint64:
- if fv.Uint() == 0 {
- continue
- }
- case reflect.Float32, reflect.Float64:
- if fv.Float() == 0 {
- continue
- }
- case reflect.String:
- if fv.String() == "" {
- continue
+ inner := fv.Elem().Elem() // interface -> *T -> T
+ tag := inner.Type().Field(0).Tag.Get("protobuf")
+ props = new(Properties) // Overwrite the outer props var, but not its pointee.
+ props.Parse(tag)
+ // Write the value in the oneof, not the oneof itself.
+ fv = inner.Field(0)
+
+ // Special case to cope with malformed messages gracefully:
+ // If the value in the oneof is a nil pointer, don't panic
+ // in writeAny.
+ if fv.Kind() == reflect.Ptr && fv.IsNil() {
+ // Use errors.New so writeAny won't render quotes.
+ msg := errors.New("/* nil */")
+ fv = reflect.ValueOf(&msg).Elem()
}
}
}
@@ -357,7 +444,7 @@ func writeStruct(w *textWriter, sv reflect.Value) error {
}
// Enums have a String method, so writeAny will work fine.
- if err := writeAny(w, fv, props); err != nil {
+ if err := tm.writeAny(w, fv, props); err != nil {
return err
}
@@ -368,8 +455,8 @@ func writeStruct(w *textWriter, sv reflect.Value) error {
// Extensions (the XXX_extensions field).
pv := sv.Addr()
- if pv.Type().Implements(extendableProtoType) {
- if err := writeExtensions(w, pv); err != nil {
+ if _, ok := extendable(pv.Interface()); ok {
+ if err := tm.writeExtensions(w, pv); err != nil {
return err
}
}
@@ -399,7 +486,7 @@ func writeRaw(w *textWriter, b []byte) error {
}
// writeAny writes an arbitrary field.
-func writeAny(w *textWriter, v reflect.Value, props *Properties) error {
+func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error {
v = reflect.Indirect(v)
// Floats have special cases.
@@ -426,7 +513,7 @@ func writeAny(w *textWriter, v reflect.Value, props *Properties) error {
switch v.Kind() {
case reflect.Slice:
// Should only be a []byte; repeated fields are handled in writeStruct.
- if err := writeString(w, string(v.Interface().([]byte))); err != nil {
+ if err := writeString(w, string(v.Bytes())); err != nil {
return err
}
case reflect.String:
@@ -448,15 +535,15 @@ func writeAny(w *textWriter, v reflect.Value, props *Properties) error {
}
}
w.indent()
- if tm, ok := v.Interface().(encoding.TextMarshaler); ok {
- text, err := tm.MarshalText()
+ if etm, ok := v.Interface().(encoding.TextMarshaler); ok {
+ text, err := etm.MarshalText()
if err != nil {
return err
}
if _, err = w.Write(text); err != nil {
return err
}
- } else if err := writeStruct(w, v); err != nil {
+ } else if err := tm.writeStruct(w, v); err != nil {
return err
}
w.unindent()
@@ -516,44 +603,6 @@ func writeString(w *textWriter, s string) error {
return w.WriteByte('"')
}
-func writeMessageSet(w *textWriter, ms *MessageSet) error {
- for _, item := range ms.Item {
- id := *item.TypeId
- if msd, ok := messageSetMap[id]; ok {
- // Known message set type.
- if _, err := fmt.Fprintf(w, "[%s]: <\n", msd.name); err != nil {
- return err
- }
- w.indent()
-
- pb := reflect.New(msd.t.Elem())
- if err := Unmarshal(item.Message, pb.Interface().(Message)); err != nil {
- if _, err := fmt.Fprintf(w, "/* bad message: %v */\n", err); err != nil {
- return err
- }
- } else {
- if err := writeStruct(w, pb.Elem()); err != nil {
- return err
- }
- }
- } else {
- // Unknown type.
- if _, err := fmt.Fprintf(w, "[%d]: <\n", id); err != nil {
- return err
- }
- w.indent()
- if err := writeUnknownStruct(w, item.Message); err != nil {
- return err
- }
- }
- w.unindent()
- if _, err := w.Write(gtNewline); err != nil {
- return err
- }
- }
- return nil
-}
-
func writeUnknownStruct(w *textWriter, data []byte) (err error) {
if !w.compact {
if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
@@ -638,19 +687,24 @@ func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// writeExtensions writes all the extensions in pv.
// pv is assumed to be a pointer to a protocol message struct that is extendable.
-func writeExtensions(w *textWriter, pv reflect.Value) error {
+func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error {
emap := extensionMaps[pv.Type().Elem()]
- ep := pv.Interface().(extendableProto)
+ ep, _ := extendable(pv.Interface())
// Order the extensions by ID.
// This isn't strictly necessary, but it will give us
// canonical output, which will also make testing easier.
- m := ep.ExtensionMap()
+ m, mu := ep.extensionsRead()
+ if m == nil {
+ return nil
+ }
+ mu.Lock()
ids := make([]int32, 0, len(m))
for id := range m {
ids = append(ids, id)
}
sort.Sort(int32Slice(ids))
+ mu.Unlock()
for _, extNum := range ids {
ext := m[extNum]
@@ -673,13 +727,13 @@ func writeExtensions(w *textWriter, pv reflect.Value) error {
// Repeated extensions will appear as a slice.
if !desc.repeated() {
- if err := writeExtension(w, desc.Name, pb); err != nil {
+ if err := tm.writeExtension(w, desc.Name, pb); err != nil {
return err
}
} else {
v := reflect.ValueOf(pb)
for i := 0; i < v.Len(); i++ {
- if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
+ if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
return err
}
}
@@ -688,7 +742,7 @@ func writeExtensions(w *textWriter, pv reflect.Value) error {
return nil
}
-func writeExtension(w *textWriter, name string, pb interface{}) error {
+func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error {
if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
return err
}
@@ -697,7 +751,7 @@ func writeExtension(w *textWriter, name string, pb interface{}) error {
return err
}
}
- if err := writeAny(w, reflect.ValueOf(pb), nil); err != nil {
+ if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil {
return err
}
if err := w.WriteByte('\n'); err != nil {
@@ -722,7 +776,15 @@ func (w *textWriter) writeIndent() {
w.complete = false
}
-func marshalText(w io.Writer, pb Message, compact bool) error {
+// TextMarshaler is a configurable text format marshaler.
+type TextMarshaler struct {
+ Compact bool // use compact text format (one line).
+ ExpandAny bool // expand google.protobuf.Any messages of known types
+}
+
+// Marshal writes a given protocol buffer in text format.
+// The only errors returned are from w.
+func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error {
val := reflect.ValueOf(pb)
if pb == nil || val.IsNil() {
w.Write([]byte(""))
@@ -737,11 +799,11 @@ func marshalText(w io.Writer, pb Message, compact bool) error {
aw := &textWriter{
w: ww,
complete: true,
- compact: compact,
+ compact: tm.Compact,
}
- if tm, ok := pb.(encoding.TextMarshaler); ok {
- text, err := tm.MarshalText()
+ if etm, ok := pb.(encoding.TextMarshaler); ok {
+ text, err := etm.MarshalText()
if err != nil {
return err
}
@@ -755,7 +817,7 @@ func marshalText(w io.Writer, pb Message, compact bool) error {
}
// Dereference the received pointer so we don't have outer < and >.
v := reflect.Indirect(val)
- if err := writeStruct(aw, v); err != nil {
+ if err := tm.writeStruct(aw, v); err != nil {
return err
}
if bw != nil {
@@ -764,25 +826,29 @@ func marshalText(w io.Writer, pb Message, compact bool) error {
return nil
}
+// Text is the same as Marshal, but returns the string directly.
+func (tm *TextMarshaler) Text(pb Message) string {
+ var buf bytes.Buffer
+ tm.Marshal(&buf, pb)
+ return buf.String()
+}
+
+var (
+ defaultTextMarshaler = TextMarshaler{}
+ compactTextMarshaler = TextMarshaler{Compact: true}
+)
+
+// TODO: consider removing some of the Marshal functions below.
+
// MarshalText writes a given protocol buffer in text format.
// The only errors returned are from w.
-func MarshalText(w io.Writer, pb Message) error {
- return marshalText(w, pb, false)
-}
+func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) }
// MarshalTextString is the same as MarshalText, but returns the string directly.
-func MarshalTextString(pb Message) string {
- var buf bytes.Buffer
- marshalText(&buf, pb, false)
- return buf.String()
-}
+func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) }
// CompactText writes a given protocol buffer in compact text format (one line).
-func CompactText(w io.Writer, pb Message) error { return marshalText(w, pb, true) }
+func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) }
// CompactTextString is the same as CompactText, but returns the string directly.
-func CompactTextString(pb Message) string {
- var buf bytes.Buffer
- marshalText(&buf, pb, true)
- return buf.String()
-}
+func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }
diff --git a/vendor/github.com/golang/protobuf/proto/text_parser.go b/vendor/github.com/golang/protobuf/proto/text_parser.go
index 5c466d5..5e14513 100644
--- a/vendor/github.com/golang/protobuf/proto/text_parser.go
+++ b/vendor/github.com/golang/protobuf/proto/text_parser.go
@@ -44,6 +44,9 @@ import (
"unicode/utf8"
)
+// Error string emitted when deserializing Any and fields are already set
+const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set"
+
type ParseError struct {
Message string
Line int // 1-based line number
@@ -119,6 +122,14 @@ func isWhitespace(c byte) bool {
return false
}
+func isQuote(c byte) bool {
+ switch c {
+ case '"', '\'':
+ return true
+ }
+ return false
+}
+
func (p *textParser) skipWhitespace() {
i := 0
for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
@@ -155,7 +166,7 @@ func (p *textParser) advance() {
p.cur.offset, p.cur.line = p.offset, p.line
p.cur.unquoted = ""
switch p.s[0] {
- case '<', '>', '{', '}', ':', '[', ']', ';', ',':
+ case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/':
// Single symbol
p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
case '"', '\'':
@@ -174,7 +185,7 @@ func (p *textParser) advance() {
}
unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
if err != nil {
- p.errorf("invalid quoted string %v", p.s[0:i+1])
+ p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
return
}
p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
@@ -333,13 +344,13 @@ func (p *textParser) next() *token {
p.advance()
if p.done {
p.cur.value = ""
- } else if len(p.cur.value) > 0 && p.cur.value[0] == '"' {
+ } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) {
// Look for multiple quoted strings separated by whitespace,
// and concatenate them.
cat := p.cur
for {
p.skipWhitespace()
- if p.done || p.s[0] != '"' {
+ if p.done || !isQuote(p.s[0]) {
break
}
p.advance()
@@ -385,8 +396,7 @@ func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSet
}
// Returns the index in the struct for the named field, as well as the parsed tag properties.
-func structFieldByName(st reflect.Type, name string) (int, *Properties, bool) {
- sprops := GetProperties(st)
+func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) {
i, ok := sprops.decoderOrigNames[name]
if ok {
return i, sprops.Prop[i], true
@@ -438,12 +448,16 @@ func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseEr
func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
st := sv.Type()
- reqCount := GetProperties(st).reqCount
+ sprops := GetProperties(st)
+ reqCount := sprops.reqCount
var reqFieldErr error
fieldSet := make(map[string]bool)
// A struct is a sequence of "name: value", terminated by one of
// '>' or '}', or the end of the input. A name may also be
- // "[extension]".
+ // "[extension]" or "[type/url]".
+ //
+ // The whole struct can also be an expanded Any message, like:
+ // [type/url] < ... struct contents ... >
for {
tok := p.next()
if tok.err != nil {
@@ -453,33 +467,74 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
break
}
if tok.value == "[" {
- // Looks like an extension.
+ // Looks like an extension or an Any.
//
// TODO: Check whether we need to handle
// namespace rooted names (e.g. ".something.Foo").
- tok = p.next()
- if tok.err != nil {
- return tok.err
+ extName, err := p.consumeExtName()
+ if err != nil {
+ return err
}
+
+ if s := strings.LastIndex(extName, "/"); s >= 0 {
+ // If it contains a slash, it's an Any type URL.
+ messageName := extName[s+1:]
+ mt := MessageType(messageName)
+ if mt == nil {
+ return p.errorf("unrecognized message %q in google.protobuf.Any", messageName)
+ }
+ tok = p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ // consume an optional colon
+ if tok.value == ":" {
+ tok = p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ }
+ var terminator string
+ switch tok.value {
+ case "<":
+ terminator = ">"
+ case "{":
+ terminator = "}"
+ default:
+ return p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+ v := reflect.New(mt.Elem())
+ if pe := p.readStruct(v.Elem(), terminator); pe != nil {
+ return pe
+ }
+ b, err := Marshal(v.Interface().(Message))
+ if err != nil {
+ return p.errorf("failed to marshal message of type %q: %v", messageName, err)
+ }
+ if fieldSet["type_url"] {
+ return p.errorf(anyRepeatedlyUnpacked, "type_url")
+ }
+ if fieldSet["value"] {
+ return p.errorf(anyRepeatedlyUnpacked, "value")
+ }
+ sv.FieldByName("TypeUrl").SetString(extName)
+ sv.FieldByName("Value").SetBytes(b)
+ fieldSet["type_url"] = true
+ fieldSet["value"] = true
+ continue
+ }
+
var desc *ExtensionDesc
// This could be faster, but it's functional.
// TODO: Do something smarter than a linear scan.
for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
- if d.Name == tok.value {
+ if d.Name == extName {
desc = d
break
}
}
if desc == nil {
- return p.errorf("unrecognized extension %q", tok.value)
- }
- // Check the extension terminator.
- tok = p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != "]" {
- return p.errorf("unrecognized extension terminator %q", tok.value)
+ return p.errorf("unrecognized extension %q", extName)
}
props := &Properties{}
@@ -506,7 +561,7 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
}
reqFieldErr = err
}
- ep := sv.Addr().Interface().(extendableProto)
+ ep := sv.Addr().Interface().(Message)
if !rep {
SetExtension(ep, desc, ext.Interface())
} else {
@@ -520,95 +575,120 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
sl = reflect.Append(sl, ext)
SetExtension(ep, desc, sl.Interface())
}
- } else {
- // This is a normal, non-extension field.
- name := tok.value
- fi, props, ok := structFieldByName(st, name)
- if !ok {
- return p.errorf("unknown field name %q in %v", name, st)
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
}
+ continue
+ }
- dst := sv.Field(fi)
-
- if dst.Kind() == reflect.Map {
- // Consume any colon.
- if err := p.checkForColon(props, dst.Type()); err != nil {
- return err
- }
-
- // Construct the map if it doesn't already exist.
- if dst.IsNil() {
- dst.Set(reflect.MakeMap(dst.Type()))
- }
- key := reflect.New(dst.Type().Key()).Elem()
- val := reflect.New(dst.Type().Elem()).Elem()
-
- // The map entry should be this sequence of tokens:
- // < key : KEY value : VALUE >
- // Technically the "key" and "value" could come in any order,
- // but in practice they won't.
-
- tok := p.next()
- var terminator string
- switch tok.value {
- case "<":
- terminator = ">"
- case "{":
- terminator = "}"
- default:
- return p.errorf("expected '{' or '<', found %q", tok.value)
- }
- if err := p.consumeToken("key"); err != nil {
- return err
- }
- if err := p.consumeToken(":"); err != nil {
- return err
- }
- if err := p.readAny(key, props.mkeyprop); err != nil {
- return err
- }
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
- if err := p.consumeToken("value"); err != nil {
- return err
- }
- if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil {
- return err
- }
- if err := p.readAny(val, props.mvalprop); err != nil {
- return err
- }
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
- if err := p.consumeToken(terminator); err != nil {
- return err
- }
-
- dst.SetMapIndex(key, val)
- continue
+ // This is a normal, non-extension field.
+ name := tok.value
+ var dst reflect.Value
+ fi, props, ok := structFieldByName(sprops, name)
+ if ok {
+ dst = sv.Field(fi)
+ } else if oop, ok := sprops.OneofTypes[name]; ok {
+ // It is a oneof.
+ props = oop.Prop
+ nv := reflect.New(oop.Type.Elem())
+ dst = nv.Elem().Field(0)
+ field := sv.Field(oop.Field)
+ if !field.IsNil() {
+ return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name)
}
+ field.Set(nv)
+ }
+ if !dst.IsValid() {
+ return p.errorf("unknown field name %q in %v", name, st)
+ }
- // Check that it's not already set if it's not a repeated field.
- if !props.Repeated && fieldSet[name] {
- return p.errorf("non-repeated field %q was repeated", name)
- }
-
- if err := p.checkForColon(props, st.Field(fi).Type); err != nil {
+ if dst.Kind() == reflect.Map {
+ // Consume any colon.
+ if err := p.checkForColon(props, dst.Type()); err != nil {
return err
}
- // Parse into the field.
- fieldSet[name] = true
- if err := p.readAny(dst, props); err != nil {
- if _, ok := err.(*RequiredNotSetError); !ok {
- return err
- }
- reqFieldErr = err
- } else if props.Required {
- reqCount--
+ // Construct the map if it doesn't already exist.
+ if dst.IsNil() {
+ dst.Set(reflect.MakeMap(dst.Type()))
}
+ key := reflect.New(dst.Type().Key()).Elem()
+ val := reflect.New(dst.Type().Elem()).Elem()
+
+ // The map entry should be this sequence of tokens:
+ // < key : KEY value : VALUE >
+ // However, implementations may omit key or value, and technically
+ // we should support them in any order. See b/28924776 for a time
+ // this went wrong.
+
+ tok := p.next()
+ var terminator string
+ switch tok.value {
+ case "<":
+ terminator = ">"
+ case "{":
+ terminator = "}"
+ default:
+ return p.errorf("expected '{' or '<', found %q", tok.value)
+ }
+ for {
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value == terminator {
+ break
+ }
+ switch tok.value {
+ case "key":
+ if err := p.consumeToken(":"); err != nil {
+ return err
+ }
+ if err := p.readAny(key, props.mkeyprop); err != nil {
+ return err
+ }
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+ case "value":
+ if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil {
+ return err
+ }
+ if err := p.readAny(val, props.mvalprop); err != nil {
+ return err
+ }
+ if err := p.consumeOptionalSeparator(); err != nil {
+ return err
+ }
+ default:
+ p.back()
+ return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value)
+ }
+ }
+
+ dst.SetMapIndex(key, val)
+ continue
+ }
+
+ // Check that it's not already set if it's not a repeated field.
+ if !props.Repeated && fieldSet[name] {
+ return p.errorf("non-repeated field %q was repeated", name)
+ }
+
+ if err := p.checkForColon(props, dst.Type()); err != nil {
+ return err
+ }
+
+ // Parse into the field.
+ fieldSet[name] = true
+ if err := p.readAny(dst, props); err != nil {
+ if _, ok := err.(*RequiredNotSetError); !ok {
+ return err
+ }
+ reqFieldErr = err
+ }
+ if props.Required {
+ reqCount--
}
if err := p.consumeOptionalSeparator(); err != nil {
@@ -623,6 +703,35 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
return reqFieldErr
}
+// consumeExtName consumes extension name or expanded Any type URL and the
+// following ']'. It returns the name or URL consumed.
+func (p *textParser) consumeExtName() (string, error) {
+ tok := p.next()
+ if tok.err != nil {
+ return "", tok.err
+ }
+
+ // If extension name or type url is quoted, it's a single token.
+ if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] {
+ name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0]))
+ if err != nil {
+ return "", err
+ }
+ return name, p.consumeToken("]")
+ }
+
+ // Consume everything up to "]"
+ var parts []string
+ for tok.value != "]" {
+ parts = append(parts, tok.value)
+ tok = p.next()
+ if tok.err != nil {
+ return "", p.errorf("unrecognized type_url or extension name: %s", tok.err)
+ }
+ }
+ return strings.Join(parts, ""), nil
+}
+
// consumeOptionalSeparator consumes an optional semicolon or comma.
// It is used in readStruct to provide backward compatibility.
func (p *textParser) consumeOptionalSeparator() error {
@@ -660,25 +769,39 @@ func (p *textParser) readAny(v reflect.Value, props *Properties) error {
fv.Set(reflect.ValueOf(bytes))
return nil
}
- // Repeated field. May already exist.
- flen := fv.Len()
- if flen == fv.Cap() {
- nav := reflect.MakeSlice(at, flen, 2*flen+1)
- reflect.Copy(nav, fv)
- fv.Set(nav)
+ // Repeated field.
+ if tok.value == "[" {
+ // Repeated field with list notation, like [1,2,3].
+ for {
+ fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
+ err := p.readAny(fv.Index(fv.Len()-1), props)
+ if err != nil {
+ return err
+ }
+ tok := p.next()
+ if tok.err != nil {
+ return tok.err
+ }
+ if tok.value == "]" {
+ break
+ }
+ if tok.value != "," {
+ return p.errorf("Expected ']' or ',' found %q", tok.value)
+ }
+ }
+ return nil
}
- fv.SetLen(flen + 1)
-
- // Read one.
+ // One value of the repeated field.
p.back()
- return p.readAny(fv.Index(flen), props)
+ fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
+ return p.readAny(fv.Index(fv.Len()-1), props)
case reflect.Bool:
- // Either "true", "false", 1 or 0.
+ // true/1/t/True or false/f/0/False.
switch tok.value {
- case "true", "1":
+ case "true", "1", "t", "True":
fv.SetBool(true)
return nil
- case "false", "0":
+ case "false", "0", "f", "False":
fv.SetBool(false)
return nil
}
@@ -742,7 +865,7 @@ func (p *textParser) readAny(v reflect.Value, props *Properties) error {
return p.readStruct(fv, terminator)
case reflect.Uint32:
if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
- fv.SetUint(uint64(x))
+ fv.SetUint(x)
return nil
}
case reflect.Uint64:
diff --git a/vendor/github.com/golang/protobuf/proto/text_parser_test.go b/vendor/github.com/golang/protobuf/proto/text_parser_test.go
index cfc0db6..8f7cb4d 100644
--- a/vendor/github.com/golang/protobuf/proto/text_parser_test.go
+++ b/vendor/github.com/golang/protobuf/proto/text_parser_test.go
@@ -95,7 +95,7 @@ var unMarshalTextTests = []UnmarshalTextTest{
},
},
- // Quoted string concatenation
+ // Quoted string concatenation with double quotes
{
in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`,
out: &MyMessage{
@@ -104,6 +104,31 @@ var unMarshalTextTests = []UnmarshalTextTest{
},
},
+ // Quoted string concatenation with single quotes
+ {
+ in: "count:42 name: 'My name is '\n'elsewhere'",
+ out: &MyMessage{
+ Count: Int32(42),
+ Name: String("My name is elsewhere"),
+ },
+ },
+
+ // Quoted string concatenations with mixed quotes
+ {
+ in: "count:42 name: 'My name is '\n\"elsewhere\"",
+ out: &MyMessage{
+ Count: Int32(42),
+ Name: String("My name is elsewhere"),
+ },
+ },
+ {
+ in: "count:42 name: \"My name is \"\n'elsewhere'",
+ out: &MyMessage{
+ Count: Int32(42),
+ Name: String("My name is elsewhere"),
+ },
+ },
+
// Quoted string with escaped apostrophe
{
in: `count:42 name: "HOLIDAY - New Year\'s Day"`,
@@ -152,7 +177,7 @@ var unMarshalTextTests = []UnmarshalTextTest{
// Bad quoted string
{
in: `inner: < host: "\0" >` + "\n",
- err: `line 1.15: invalid quoted string "\0"`,
+ err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`,
},
// Number too large for int64
@@ -256,6 +281,15 @@ var unMarshalTextTests = []UnmarshalTextTest{
},
},
+ // Repeated field with list notation
+ {
+ in: `count:42 pet: ["horsey", "bunny"]`,
+ out: &MyMessage{
+ Count: Int32(42),
+ Pet: []string{"horsey", "bunny"},
+ },
+ },
+
// Repeated message with/without colon and <>/{}
{
in: `count:42 others:{} others{} others:<> others:{}`,
@@ -302,6 +336,16 @@ var unMarshalTextTests = []UnmarshalTextTest{
},
},
+ // Missing required field in a required submessage
+ {
+ in: `count: 42 we_must_go_deeper < leo_finally_won_an_oscar <> >`,
+ err: `proto: required field "testdata.InnerMessage.host" not set`,
+ out: &MyMessage{
+ Count: Int32(42),
+ WeMustGoDeeper: &RequiredInnerMessage{LeoFinallyWonAnOscar: &InnerMessage{}},
+ },
+ },
+
// Repeated non-repeated field
{
in: `name: "Rob" name: "Russ"`,
@@ -336,6 +380,95 @@ var unMarshalTextTests = []UnmarshalTextTest{
},
},
+ // Boolean false
+ {
+ in: `count:42 inner { host: "example.com" connected: false }`,
+ out: &MyMessage{
+ Count: Int32(42),
+ Inner: &InnerMessage{
+ Host: String("example.com"),
+ Connected: Bool(false),
+ },
+ },
+ },
+ // Boolean true
+ {
+ in: `count:42 inner { host: "example.com" connected: true }`,
+ out: &MyMessage{
+ Count: Int32(42),
+ Inner: &InnerMessage{
+ Host: String("example.com"),
+ Connected: Bool(true),
+ },
+ },
+ },
+ // Boolean 0
+ {
+ in: `count:42 inner { host: "example.com" connected: 0 }`,
+ out: &MyMessage{
+ Count: Int32(42),
+ Inner: &InnerMessage{
+ Host: String("example.com"),
+ Connected: Bool(false),
+ },
+ },
+ },
+ // Boolean 1
+ {
+ in: `count:42 inner { host: "example.com" connected: 1 }`,
+ out: &MyMessage{
+ Count: Int32(42),
+ Inner: &InnerMessage{
+ Host: String("example.com"),
+ Connected: Bool(true),
+ },
+ },
+ },
+ // Boolean f
+ {
+ in: `count:42 inner { host: "example.com" connected: f }`,
+ out: &MyMessage{
+ Count: Int32(42),
+ Inner: &InnerMessage{
+ Host: String("example.com"),
+ Connected: Bool(false),
+ },
+ },
+ },
+ // Boolean t
+ {
+ in: `count:42 inner { host: "example.com" connected: t }`,
+ out: &MyMessage{
+ Count: Int32(42),
+ Inner: &InnerMessage{
+ Host: String("example.com"),
+ Connected: Bool(true),
+ },
+ },
+ },
+ // Boolean False
+ {
+ in: `count:42 inner { host: "example.com" connected: False }`,
+ out: &MyMessage{
+ Count: Int32(42),
+ Inner: &InnerMessage{
+ Host: String("example.com"),
+ Connected: Bool(false),
+ },
+ },
+ },
+ // Boolean True
+ {
+ in: `count:42 inner { host: "example.com" connected: True }`,
+ out: &MyMessage{
+ Count: Int32(42),
+ Inner: &InnerMessage{
+ Host: String("example.com"),
+ Connected: Bool(true),
+ },
+ },
+ },
+
// Extension
buildExtStructTest(`count: 42 [testdata.Ext.more]:`),
buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`),
@@ -464,7 +597,10 @@ func TestMapParsing(t *testing.T) {
const in = `name_mapping: name_mapping:` +
`msg_mapping:,>` + // separating commas are okay
`msg_mapping>` + // no colon after "value"
- `byte_mapping:`
+ `msg_mapping:>` + // omitted key
+ `msg_mapping:` + // omitted value
+ `byte_mapping:` +
+ `byte_mapping:<>` // omitted key and value
want := &MessageWithMap{
NameMapping: map[int32]string{
1: "Beatles",
@@ -473,9 +609,12 @@ func TestMapParsing(t *testing.T) {
MsgMapping: map[int64]*FloatingPoint{
-4: {F: Float64(2.0)},
-2: {F: Float64(4.0)},
+ 0: {F: Float64(5.0)},
+ 1: nil,
},
ByteMapping: map[bool][]byte{
- true: []byte("so be it"),
+ false: nil,
+ true: []byte("so be it"),
},
}
if err := UnmarshalText(in, m); err != nil {
@@ -486,6 +625,29 @@ func TestMapParsing(t *testing.T) {
}
}
+func TestOneofParsing(t *testing.T) {
+ const in = `name:"Shrek"`
+ m := new(Communique)
+ want := &Communique{Union: &Communique_Name{"Shrek"}}
+ if err := UnmarshalText(in, m); err != nil {
+ t.Fatal(err)
+ }
+ if !Equal(m, want) {
+ t.Errorf("\n got %v\nwant %v", m, want)
+ }
+
+ const inOverwrite = `name:"Shrek" number:42`
+ m = new(Communique)
+ testErr := "line 1.13: field 'number' would overwrite already parsed oneof 'Union'"
+ if err := UnmarshalText(inOverwrite, m); err == nil {
+ t.Errorf("TestOneofParsing: Didn't get expected error: %v", testErr)
+ } else if err.Error() != testErr {
+ t.Errorf("TestOneofParsing: Incorrect error.\nHave: %v\nWant: %v",
+ err.Error(), testErr)
+ }
+
+}
+
var benchInput string
func init() {
diff --git a/vendor/github.com/golang/protobuf/proto/text_test.go b/vendor/github.com/golang/protobuf/proto/text_test.go
index 39861d1..3eabaca 100644
--- a/vendor/github.com/golang/protobuf/proto/text_test.go
+++ b/vendor/github.com/golang/protobuf/proto/text_test.go
@@ -208,6 +208,30 @@ func TestMarshalTextUnknownEnum(t *testing.T) {
}
}
+func TestTextOneof(t *testing.T) {
+ tests := []struct {
+ m proto.Message
+ want string
+ }{
+ // zero message
+ {&pb.Communique{}, ``},
+ // scalar field
+ {&pb.Communique{Union: &pb.Communique_Number{4}}, `number:4`},
+ // message field
+ {&pb.Communique{Union: &pb.Communique_Msg{
+ &pb.Strings{StringField: proto.String("why hello!")},
+ }}, `msg:`},
+ // bad oneof (should not panic)
+ {&pb.Communique{Union: &pb.Communique_Msg{nil}}, `msg:/* nil */`},
+ }
+ for _, test := range tests {
+ got := strings.TrimSpace(test.m.String())
+ if got != test.want {
+ t.Errorf("\n got %s\nwant %s", got, test.want)
+ }
+ }
+}
+
func BenchmarkMarshalTextBuffered(b *testing.B) {
buf := new(bytes.Buffer)
m := newTestMessage()
@@ -421,10 +445,19 @@ func TestProto3Text(t *testing.T) {
{&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`},
// empty map
{&pb.MessageWithMap{}, ``},
- // non-empty map; current map format is the same as a repeated struct
+ // non-empty map; map format is the same as a repeated struct,
+ // and they are sorted by key (numerically for numeric keys).
{
- &pb.MessageWithMap{NameMapping: map[int32]string{1234: "Feist"}},
- `name_mapping:`,
+ &pb.MessageWithMap{NameMapping: map[int32]string{
+ -1: "Negatory",
+ 7: "Lucky",
+ 1234: "Feist",
+ 6345789: "Otis",
+ }},
+ `name_mapping: ` +
+ `name_mapping: ` +
+ `name_mapping: ` +
+ `name_mapping:`,
},
// map with nil value; not well-defined, but we shouldn't crash
{
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/Makefile b/vendor/github.com/golang/protobuf/protoc-gen-go/Makefile
new file mode 100644
index 0000000..a42cc37
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/Makefile
@@ -0,0 +1,33 @@
+# 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.
+
+test:
+ cd testdata && make test
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/Makefile b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/Makefile
new file mode 100644
index 0000000..f706871
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/Makefile
@@ -0,0 +1,37 @@
+# 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.
+
+# Not stored here, but descriptor.proto is in https://github.com/google/protobuf/
+# at src/google/protobuf/descriptor.proto
+regenerate:
+ @echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION
+ cp $(HOME)/src/protobuf/include/google/protobuf/descriptor.proto .
+ protoc --go_out=../../../../.. -I$(HOME)/src/protobuf/include $(HOME)/src/protobuf/include/google/protobuf/descriptor.proto
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go
new file mode 100644
index 0000000..c6a91bc
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go
@@ -0,0 +1,2215 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: google/protobuf/descriptor.proto
+
+/*
+Package descriptor is a generated protocol buffer package.
+
+It is generated from these files:
+ google/protobuf/descriptor.proto
+
+It has these top-level messages:
+ FileDescriptorSet
+ FileDescriptorProto
+ DescriptorProto
+ ExtensionRangeOptions
+ FieldDescriptorProto
+ OneofDescriptorProto
+ EnumDescriptorProto
+ EnumValueDescriptorProto
+ ServiceDescriptorProto
+ MethodDescriptorProto
+ FileOptions
+ MessageOptions
+ FieldOptions
+ OneofOptions
+ EnumOptions
+ EnumValueOptions
+ ServiceOptions
+ MethodOptions
+ UninterpretedOption
+ SourceCodeInfo
+ GeneratedCodeInfo
+*/
+package descriptor
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+type FieldDescriptorProto_Type int32
+
+const (
+ // 0 is reserved for errors.
+ // Order is weird for historical reasons.
+ FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1
+ FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
+ // negative values are likely.
+ FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3
+ FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
+ // negative values are likely.
+ FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5
+ FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6
+ FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7
+ FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8
+ FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9
+ // Tag-delimited aggregate.
+ // Group type is deprecated and not supported in proto3. However, Proto3
+ // implementations should still be able to parse the group wire format and
+ // treat group fields as unknown fields.
+ FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10
+ FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11
+ // New in version 2.
+ FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12
+ FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13
+ FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14
+ FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15
+ FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16
+ FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17
+ FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18
+)
+
+var FieldDescriptorProto_Type_name = map[int32]string{
+ 1: "TYPE_DOUBLE",
+ 2: "TYPE_FLOAT",
+ 3: "TYPE_INT64",
+ 4: "TYPE_UINT64",
+ 5: "TYPE_INT32",
+ 6: "TYPE_FIXED64",
+ 7: "TYPE_FIXED32",
+ 8: "TYPE_BOOL",
+ 9: "TYPE_STRING",
+ 10: "TYPE_GROUP",
+ 11: "TYPE_MESSAGE",
+ 12: "TYPE_BYTES",
+ 13: "TYPE_UINT32",
+ 14: "TYPE_ENUM",
+ 15: "TYPE_SFIXED32",
+ 16: "TYPE_SFIXED64",
+ 17: "TYPE_SINT32",
+ 18: "TYPE_SINT64",
+}
+var FieldDescriptorProto_Type_value = map[string]int32{
+ "TYPE_DOUBLE": 1,
+ "TYPE_FLOAT": 2,
+ "TYPE_INT64": 3,
+ "TYPE_UINT64": 4,
+ "TYPE_INT32": 5,
+ "TYPE_FIXED64": 6,
+ "TYPE_FIXED32": 7,
+ "TYPE_BOOL": 8,
+ "TYPE_STRING": 9,
+ "TYPE_GROUP": 10,
+ "TYPE_MESSAGE": 11,
+ "TYPE_BYTES": 12,
+ "TYPE_UINT32": 13,
+ "TYPE_ENUM": 14,
+ "TYPE_SFIXED32": 15,
+ "TYPE_SFIXED64": 16,
+ "TYPE_SINT32": 17,
+ "TYPE_SINT64": 18,
+}
+
+func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type {
+ p := new(FieldDescriptorProto_Type)
+ *p = x
+ return p
+}
+func (x FieldDescriptorProto_Type) String() string {
+ return proto.EnumName(FieldDescriptorProto_Type_name, int32(x))
+}
+func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type")
+ if err != nil {
+ return err
+ }
+ *x = FieldDescriptorProto_Type(value)
+ return nil
+}
+func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{4, 0} }
+
+type FieldDescriptorProto_Label int32
+
+const (
+ // 0 is reserved for errors
+ FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1
+ FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2
+ FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3
+)
+
+var FieldDescriptorProto_Label_name = map[int32]string{
+ 1: "LABEL_OPTIONAL",
+ 2: "LABEL_REQUIRED",
+ 3: "LABEL_REPEATED",
+}
+var FieldDescriptorProto_Label_value = map[string]int32{
+ "LABEL_OPTIONAL": 1,
+ "LABEL_REQUIRED": 2,
+ "LABEL_REPEATED": 3,
+}
+
+func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label {
+ p := new(FieldDescriptorProto_Label)
+ *p = x
+ return p
+}
+func (x FieldDescriptorProto_Label) String() string {
+ return proto.EnumName(FieldDescriptorProto_Label_name, int32(x))
+}
+func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label")
+ if err != nil {
+ return err
+ }
+ *x = FieldDescriptorProto_Label(value)
+ return nil
+}
+func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{4, 1}
+}
+
+// Generated classes can be optimized for speed or code size.
+type FileOptions_OptimizeMode int32
+
+const (
+ FileOptions_SPEED FileOptions_OptimizeMode = 1
+ // etc.
+ FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2
+ FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3
+)
+
+var FileOptions_OptimizeMode_name = map[int32]string{
+ 1: "SPEED",
+ 2: "CODE_SIZE",
+ 3: "LITE_RUNTIME",
+}
+var FileOptions_OptimizeMode_value = map[string]int32{
+ "SPEED": 1,
+ "CODE_SIZE": 2,
+ "LITE_RUNTIME": 3,
+}
+
+func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode {
+ p := new(FileOptions_OptimizeMode)
+ *p = x
+ return p
+}
+func (x FileOptions_OptimizeMode) String() string {
+ return proto.EnumName(FileOptions_OptimizeMode_name, int32(x))
+}
+func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode")
+ if err != nil {
+ return err
+ }
+ *x = FileOptions_OptimizeMode(value)
+ return nil
+}
+func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{10, 0} }
+
+type FieldOptions_CType int32
+
+const (
+ // Default mode.
+ FieldOptions_STRING FieldOptions_CType = 0
+ FieldOptions_CORD FieldOptions_CType = 1
+ FieldOptions_STRING_PIECE FieldOptions_CType = 2
+)
+
+var FieldOptions_CType_name = map[int32]string{
+ 0: "STRING",
+ 1: "CORD",
+ 2: "STRING_PIECE",
+}
+var FieldOptions_CType_value = map[string]int32{
+ "STRING": 0,
+ "CORD": 1,
+ "STRING_PIECE": 2,
+}
+
+func (x FieldOptions_CType) Enum() *FieldOptions_CType {
+ p := new(FieldOptions_CType)
+ *p = x
+ return p
+}
+func (x FieldOptions_CType) String() string {
+ return proto.EnumName(FieldOptions_CType_name, int32(x))
+}
+func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType")
+ if err != nil {
+ return err
+ }
+ *x = FieldOptions_CType(value)
+ return nil
+}
+func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{12, 0} }
+
+type FieldOptions_JSType int32
+
+const (
+ // Use the default type.
+ FieldOptions_JS_NORMAL FieldOptions_JSType = 0
+ // Use JavaScript strings.
+ FieldOptions_JS_STRING FieldOptions_JSType = 1
+ // Use JavaScript numbers.
+ FieldOptions_JS_NUMBER FieldOptions_JSType = 2
+)
+
+var FieldOptions_JSType_name = map[int32]string{
+ 0: "JS_NORMAL",
+ 1: "JS_STRING",
+ 2: "JS_NUMBER",
+}
+var FieldOptions_JSType_value = map[string]int32{
+ "JS_NORMAL": 0,
+ "JS_STRING": 1,
+ "JS_NUMBER": 2,
+}
+
+func (x FieldOptions_JSType) Enum() *FieldOptions_JSType {
+ p := new(FieldOptions_JSType)
+ *p = x
+ return p
+}
+func (x FieldOptions_JSType) String() string {
+ return proto.EnumName(FieldOptions_JSType_name, int32(x))
+}
+func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType")
+ if err != nil {
+ return err
+ }
+ *x = FieldOptions_JSType(value)
+ return nil
+}
+func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{12, 1} }
+
+// Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
+// or neither? HTTP based RPC implementation may choose GET verb for safe
+// methods, and PUT verb for idempotent methods instead of the default POST.
+type MethodOptions_IdempotencyLevel int32
+
+const (
+ MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0
+ MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1
+ MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2
+)
+
+var MethodOptions_IdempotencyLevel_name = map[int32]string{
+ 0: "IDEMPOTENCY_UNKNOWN",
+ 1: "NO_SIDE_EFFECTS",
+ 2: "IDEMPOTENT",
+}
+var MethodOptions_IdempotencyLevel_value = map[string]int32{
+ "IDEMPOTENCY_UNKNOWN": 0,
+ "NO_SIDE_EFFECTS": 1,
+ "IDEMPOTENT": 2,
+}
+
+func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel {
+ p := new(MethodOptions_IdempotencyLevel)
+ *p = x
+ return p
+}
+func (x MethodOptions_IdempotencyLevel) String() string {
+ return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x))
+}
+func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel")
+ if err != nil {
+ return err
+ }
+ *x = MethodOptions_IdempotencyLevel(value)
+ return nil
+}
+func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{17, 0}
+}
+
+// The protocol compiler can output a FileDescriptorSet containing the .proto
+// files it parses.
+type FileDescriptorSet struct {
+ File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} }
+func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) }
+func (*FileDescriptorSet) ProtoMessage() {}
+func (*FileDescriptorSet) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+
+func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto {
+ if m != nil {
+ return m.File
+ }
+ return nil
+}
+
+// Describes a complete .proto file.
+type FileDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"`
+ // Names of files imported by this file.
+ Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"`
+ // Indexes of the public imported files in the dependency list above.
+ PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"`
+ // Indexes of the weak imported files in the dependency list.
+ // For Google-internal migration only. Do not use.
+ WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"`
+ // All top-level definitions in this file.
+ MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"`
+ EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
+ Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"`
+ Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"`
+ Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
+ // This field contains optional information about the original source code.
+ // You may safely remove this entire field without harming runtime
+ // functionality of the descriptors -- the information is needed only by
+ // development tools.
+ SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"`
+ // The syntax of the proto file.
+ // The supported values are "proto2" and "proto3".
+ Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} }
+func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*FileDescriptorProto) ProtoMessage() {}
+func (*FileDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+
+func (m *FileDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *FileDescriptorProto) GetPackage() string {
+ if m != nil && m.Package != nil {
+ return *m.Package
+ }
+ return ""
+}
+
+func (m *FileDescriptorProto) GetDependency() []string {
+ if m != nil {
+ return m.Dependency
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetPublicDependency() []int32 {
+ if m != nil {
+ return m.PublicDependency
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetWeakDependency() []int32 {
+ if m != nil {
+ return m.WeakDependency
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto {
+ if m != nil {
+ return m.MessageType
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto {
+ if m != nil {
+ return m.EnumType
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto {
+ if m != nil {
+ return m.Service
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto {
+ if m != nil {
+ return m.Extension
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetOptions() *FileOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo {
+ if m != nil {
+ return m.SourceCodeInfo
+ }
+ return nil
+}
+
+func (m *FileDescriptorProto) GetSyntax() string {
+ if m != nil && m.Syntax != nil {
+ return *m.Syntax
+ }
+ return ""
+}
+
+// Describes a message type.
+type DescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"`
+ Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"`
+ NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"`
+ EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
+ ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"`
+ OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"`
+ Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"`
+ ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"`
+ // Reserved field names, which may not be used by fields in the same message.
+ // A given name may only be reserved once.
+ ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *DescriptorProto) Reset() { *m = DescriptorProto{} }
+func (m *DescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*DescriptorProto) ProtoMessage() {}
+func (*DescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
+
+func (m *DescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *DescriptorProto) GetField() []*FieldDescriptorProto {
+ if m != nil {
+ return m.Field
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto {
+ if m != nil {
+ return m.Extension
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetNestedType() []*DescriptorProto {
+ if m != nil {
+ return m.NestedType
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto {
+ if m != nil {
+ return m.EnumType
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange {
+ if m != nil {
+ return m.ExtensionRange
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto {
+ if m != nil {
+ return m.OneofDecl
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetOptions() *MessageOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange {
+ if m != nil {
+ return m.ReservedRange
+ }
+ return nil
+}
+
+func (m *DescriptorProto) GetReservedName() []string {
+ if m != nil {
+ return m.ReservedName
+ }
+ return nil
+}
+
+type DescriptorProto_ExtensionRange struct {
+ Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
+ End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
+ Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} }
+func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) }
+func (*DescriptorProto_ExtensionRange) ProtoMessage() {}
+func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{2, 0}
+}
+
+func (m *DescriptorProto_ExtensionRange) GetStart() int32 {
+ if m != nil && m.Start != nil {
+ return *m.Start
+ }
+ return 0
+}
+
+func (m *DescriptorProto_ExtensionRange) GetEnd() int32 {
+ if m != nil && m.End != nil {
+ return *m.End
+ }
+ return 0
+}
+
+func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Range of reserved tag numbers. Reserved tag numbers may not be used by
+// fields or extension ranges in the same message. Reserved ranges may
+// not overlap.
+type DescriptorProto_ReservedRange struct {
+ Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
+ End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} }
+func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) }
+func (*DescriptorProto_ReservedRange) ProtoMessage() {}
+func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{2, 1}
+}
+
+func (m *DescriptorProto_ReservedRange) GetStart() int32 {
+ if m != nil && m.Start != nil {
+ return *m.Start
+ }
+ return 0
+}
+
+func (m *DescriptorProto_ReservedRange) GetEnd() int32 {
+ if m != nil && m.End != nil {
+ return *m.End
+ }
+ return 0
+}
+
+type ExtensionRangeOptions struct {
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} }
+func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) }
+func (*ExtensionRangeOptions) ProtoMessage() {}
+func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
+
+var extRange_ExtensionRangeOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_ExtensionRangeOptions
+}
+
+func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+// Describes a field within a message.
+type FieldDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"`
+ Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"`
+ // If type_name is set, this need not be set. If both this and type_name
+ // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
+ Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"`
+ // For message and enum types, this is the name of the type. If the name
+ // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
+ // rules are used to find the type (i.e. first the nested types within this
+ // message are searched, then within the parent, on up to the root
+ // namespace).
+ TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"`
+ // For extensions, this is the name of the type being extended. It is
+ // resolved in the same manner as type_name.
+ Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"`
+ // For numeric types, contains the original text representation of the value.
+ // For booleans, "true" or "false".
+ // For strings, contains the default text contents (not escaped in any way).
+ // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
+ // TODO(kenton): Base-64 encode?
+ DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"`
+ // If set, gives the index of a oneof in the containing type's oneof_decl
+ // list. This field is a member of that oneof.
+ OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"`
+ // JSON name of this field. The value is set by protocol compiler. If the
+ // user has set a "json_name" option on this field, that option's value
+ // will be used. Otherwise, it's deduced from the field's name by converting
+ // it to camelCase.
+ JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"`
+ Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} }
+func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*FieldDescriptorProto) ProtoMessage() {}
+func (*FieldDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
+
+func (m *FieldDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetNumber() int32 {
+ if m != nil && m.Number != nil {
+ return *m.Number
+ }
+ return 0
+}
+
+func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label {
+ if m != nil && m.Label != nil {
+ return *m.Label
+ }
+ return FieldDescriptorProto_LABEL_OPTIONAL
+}
+
+func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type {
+ if m != nil && m.Type != nil {
+ return *m.Type
+ }
+ return FieldDescriptorProto_TYPE_DOUBLE
+}
+
+func (m *FieldDescriptorProto) GetTypeName() string {
+ if m != nil && m.TypeName != nil {
+ return *m.TypeName
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetExtendee() string {
+ if m != nil && m.Extendee != nil {
+ return *m.Extendee
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetDefaultValue() string {
+ if m != nil && m.DefaultValue != nil {
+ return *m.DefaultValue
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetOneofIndex() int32 {
+ if m != nil && m.OneofIndex != nil {
+ return *m.OneofIndex
+ }
+ return 0
+}
+
+func (m *FieldDescriptorProto) GetJsonName() string {
+ if m != nil && m.JsonName != nil {
+ return *m.JsonName
+ }
+ return ""
+}
+
+func (m *FieldDescriptorProto) GetOptions() *FieldOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a oneof.
+type OneofDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} }
+func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*OneofDescriptorProto) ProtoMessage() {}
+func (*OneofDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
+
+func (m *OneofDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *OneofDescriptorProto) GetOptions() *OneofOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes an enum type.
+type EnumDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"`
+ Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} }
+func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*EnumDescriptorProto) ProtoMessage() {}
+func (*EnumDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
+
+func (m *EnumDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto {
+ if m != nil {
+ return m.Value
+ }
+ return nil
+}
+
+func (m *EnumDescriptorProto) GetOptions() *EnumOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a value within an enum.
+type EnumValueDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"`
+ Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} }
+func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*EnumValueDescriptorProto) ProtoMessage() {}
+func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} }
+
+func (m *EnumValueDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *EnumValueDescriptorProto) GetNumber() int32 {
+ if m != nil && m.Number != nil {
+ return *m.Number
+ }
+ return 0
+}
+
+func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a service.
+type ServiceDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"`
+ Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} }
+func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*ServiceDescriptorProto) ProtoMessage() {}
+func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} }
+
+func (m *ServiceDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto {
+ if m != nil {
+ return m.Method
+ }
+ return nil
+}
+
+func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+// Describes a method of a service.
+type MethodDescriptorProto struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ // Input and output type names. These are resolved in the same way as
+ // FieldDescriptorProto.type_name, but must refer to a message type.
+ InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"`
+ OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"`
+ Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"`
+ // Identifies if client streams multiple client messages
+ ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"`
+ // Identifies if server streams multiple server messages
+ ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} }
+func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) }
+func (*MethodDescriptorProto) ProtoMessage() {}
+func (*MethodDescriptorProto) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{9} }
+
+const Default_MethodDescriptorProto_ClientStreaming bool = false
+const Default_MethodDescriptorProto_ServerStreaming bool = false
+
+func (m *MethodDescriptorProto) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+func (m *MethodDescriptorProto) GetInputType() string {
+ if m != nil && m.InputType != nil {
+ return *m.InputType
+ }
+ return ""
+}
+
+func (m *MethodDescriptorProto) GetOutputType() string {
+ if m != nil && m.OutputType != nil {
+ return *m.OutputType
+ }
+ return ""
+}
+
+func (m *MethodDescriptorProto) GetOptions() *MethodOptions {
+ if m != nil {
+ return m.Options
+ }
+ return nil
+}
+
+func (m *MethodDescriptorProto) GetClientStreaming() bool {
+ if m != nil && m.ClientStreaming != nil {
+ return *m.ClientStreaming
+ }
+ return Default_MethodDescriptorProto_ClientStreaming
+}
+
+func (m *MethodDescriptorProto) GetServerStreaming() bool {
+ if m != nil && m.ServerStreaming != nil {
+ return *m.ServerStreaming
+ }
+ return Default_MethodDescriptorProto_ServerStreaming
+}
+
+type FileOptions struct {
+ // Sets the Java package where classes generated from this .proto will be
+ // placed. By default, the proto package is used, but this is often
+ // inappropriate because proto packages do not normally start with backwards
+ // domain names.
+ JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"`
+ // If set, all the classes from the .proto file are wrapped in a single
+ // outer class with the given name. This applies to both Proto1
+ // (equivalent to the old "--one_java_file" option) and Proto2 (where
+ // a .proto always translates to a single class, but you may want to
+ // explicitly choose the class name).
+ JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"`
+ // If set true, then the Java code generator will generate a separate .java
+ // file for each top-level message, enum, and service defined in the .proto
+ // file. Thus, these types will *not* be nested inside the outer class
+ // named by java_outer_classname. However, the outer class will still be
+ // generated to contain the file's getDescriptor() method as well as any
+ // top-level extensions defined in the file.
+ JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"`
+ // This option does nothing.
+ JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"`
+ // If set true, then the Java2 code generator will generate code that
+ // throws an exception whenever an attempt is made to assign a non-UTF-8
+ // byte sequence to a string field.
+ // Message reflection will do the same.
+ // However, an extension field still accepts non-UTF-8 byte sequences.
+ // This option has no effect on when used with the lite runtime.
+ JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"`
+ OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"`
+ // Sets the Go package where structs generated from this .proto will be
+ // placed. If omitted, the Go package will be derived from the following:
+ // - The basename of the package import path, if provided.
+ // - Otherwise, the package statement in the .proto file, if present.
+ // - Otherwise, the basename of the .proto file, without extension.
+ GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"`
+ // Should generic services be generated in each language? "Generic" services
+ // are not specific to any particular RPC system. They are generated by the
+ // main code generators in each language (without additional plugins).
+ // Generic services were the only kind of service generation supported by
+ // early versions of google.protobuf.
+ //
+ // Generic services are now considered deprecated in favor of using plugins
+ // that generate code specific to your particular RPC system. Therefore,
+ // these default to false. Old code which depends on generic services should
+ // explicitly set them to true.
+ CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"`
+ JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"`
+ PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"`
+ PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"`
+ // Is this file deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for everything in the file, or it will be completely ignored; in the very
+ // least, this is a formalization for deprecating files.
+ Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // Enables the use of arenas for the proto messages in this file. This applies
+ // only to generated classes for C++.
+ CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"`
+ // Sets the objective c class prefix which is prepended to all objective c
+ // generated classes from this .proto. There is no default.
+ ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"`
+ // Namespace for generated classes; defaults to the package.
+ CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"`
+ // By default Swift generators will take the proto package and CamelCase it
+ // replacing '.' with underscore and use that to prefix the types/symbols
+ // defined. When this options is provided, they will use this value instead
+ // to prefix the types/symbols defined.
+ SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"`
+ // Sets the php class prefix which is prepended to all php generated classes
+ // from this .proto. Default is empty.
+ PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"`
+ // Use this option to change the namespace of php generated classes. Default
+ // is empty. When this option is empty, the package name will be used for
+ // determining the namespace.
+ PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FileOptions) Reset() { *m = FileOptions{} }
+func (m *FileOptions) String() string { return proto.CompactTextString(m) }
+func (*FileOptions) ProtoMessage() {}
+func (*FileOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{10} }
+
+var extRange_FileOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_FileOptions
+}
+
+const Default_FileOptions_JavaMultipleFiles bool = false
+const Default_FileOptions_JavaStringCheckUtf8 bool = false
+const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED
+const Default_FileOptions_CcGenericServices bool = false
+const Default_FileOptions_JavaGenericServices bool = false
+const Default_FileOptions_PyGenericServices bool = false
+const Default_FileOptions_PhpGenericServices bool = false
+const Default_FileOptions_Deprecated bool = false
+const Default_FileOptions_CcEnableArenas bool = false
+
+func (m *FileOptions) GetJavaPackage() string {
+ if m != nil && m.JavaPackage != nil {
+ return *m.JavaPackage
+ }
+ return ""
+}
+
+func (m *FileOptions) GetJavaOuterClassname() string {
+ if m != nil && m.JavaOuterClassname != nil {
+ return *m.JavaOuterClassname
+ }
+ return ""
+}
+
+func (m *FileOptions) GetJavaMultipleFiles() bool {
+ if m != nil && m.JavaMultipleFiles != nil {
+ return *m.JavaMultipleFiles
+ }
+ return Default_FileOptions_JavaMultipleFiles
+}
+
+func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool {
+ if m != nil && m.JavaGenerateEqualsAndHash != nil {
+ return *m.JavaGenerateEqualsAndHash
+ }
+ return false
+}
+
+func (m *FileOptions) GetJavaStringCheckUtf8() bool {
+ if m != nil && m.JavaStringCheckUtf8 != nil {
+ return *m.JavaStringCheckUtf8
+ }
+ return Default_FileOptions_JavaStringCheckUtf8
+}
+
+func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode {
+ if m != nil && m.OptimizeFor != nil {
+ return *m.OptimizeFor
+ }
+ return Default_FileOptions_OptimizeFor
+}
+
+func (m *FileOptions) GetGoPackage() string {
+ if m != nil && m.GoPackage != nil {
+ return *m.GoPackage
+ }
+ return ""
+}
+
+func (m *FileOptions) GetCcGenericServices() bool {
+ if m != nil && m.CcGenericServices != nil {
+ return *m.CcGenericServices
+ }
+ return Default_FileOptions_CcGenericServices
+}
+
+func (m *FileOptions) GetJavaGenericServices() bool {
+ if m != nil && m.JavaGenericServices != nil {
+ return *m.JavaGenericServices
+ }
+ return Default_FileOptions_JavaGenericServices
+}
+
+func (m *FileOptions) GetPyGenericServices() bool {
+ if m != nil && m.PyGenericServices != nil {
+ return *m.PyGenericServices
+ }
+ return Default_FileOptions_PyGenericServices
+}
+
+func (m *FileOptions) GetPhpGenericServices() bool {
+ if m != nil && m.PhpGenericServices != nil {
+ return *m.PhpGenericServices
+ }
+ return Default_FileOptions_PhpGenericServices
+}
+
+func (m *FileOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_FileOptions_Deprecated
+}
+
+func (m *FileOptions) GetCcEnableArenas() bool {
+ if m != nil && m.CcEnableArenas != nil {
+ return *m.CcEnableArenas
+ }
+ return Default_FileOptions_CcEnableArenas
+}
+
+func (m *FileOptions) GetObjcClassPrefix() string {
+ if m != nil && m.ObjcClassPrefix != nil {
+ return *m.ObjcClassPrefix
+ }
+ return ""
+}
+
+func (m *FileOptions) GetCsharpNamespace() string {
+ if m != nil && m.CsharpNamespace != nil {
+ return *m.CsharpNamespace
+ }
+ return ""
+}
+
+func (m *FileOptions) GetSwiftPrefix() string {
+ if m != nil && m.SwiftPrefix != nil {
+ return *m.SwiftPrefix
+ }
+ return ""
+}
+
+func (m *FileOptions) GetPhpClassPrefix() string {
+ if m != nil && m.PhpClassPrefix != nil {
+ return *m.PhpClassPrefix
+ }
+ return ""
+}
+
+func (m *FileOptions) GetPhpNamespace() string {
+ if m != nil && m.PhpNamespace != nil {
+ return *m.PhpNamespace
+ }
+ return ""
+}
+
+func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type MessageOptions struct {
+ // Set true to use the old proto1 MessageSet wire format for extensions.
+ // This is provided for backwards-compatibility with the MessageSet wire
+ // format. You should not use this for any other reason: It's less
+ // efficient, has fewer features, and is more complicated.
+ //
+ // The message must be defined exactly as follows:
+ // message Foo {
+ // option message_set_wire_format = true;
+ // extensions 4 to max;
+ // }
+ // Note that the message cannot have any defined fields; MessageSets only
+ // have extensions.
+ //
+ // All extensions of your type must be singular messages; e.g. they cannot
+ // be int32s, enums, or repeated messages.
+ //
+ // Because this is an option, the above two restrictions are not enforced by
+ // the protocol compiler.
+ MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"`
+ // Disables the generation of the standard "descriptor()" accessor, which can
+ // conflict with a field of the same name. This is meant to make migration
+ // from proto1 easier; new code should avoid fields named "descriptor".
+ NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"`
+ // Is this message deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the message, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating messages.
+ Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // Whether the message is an automatically generated map entry type for the
+ // maps field.
+ //
+ // For maps fields:
+ // map map_field = 1;
+ // The parsed descriptor looks like:
+ // message MapFieldEntry {
+ // option map_entry = true;
+ // optional KeyType key = 1;
+ // optional ValueType value = 2;
+ // }
+ // repeated MapFieldEntry map_field = 1;
+ //
+ // Implementations may choose not to generate the map_entry=true message, but
+ // use a native map in the target language to hold the keys and values.
+ // The reflection APIs in such implementions still need to work as
+ // if the field is a repeated message field.
+ //
+ // NOTE: Do not set the option in .proto files. Always use the maps syntax
+ // instead. The option should only be implicitly set by the proto compiler
+ // parser.
+ MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MessageOptions) Reset() { *m = MessageOptions{} }
+func (m *MessageOptions) String() string { return proto.CompactTextString(m) }
+func (*MessageOptions) ProtoMessage() {}
+func (*MessageOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{11} }
+
+var extRange_MessageOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_MessageOptions
+}
+
+const Default_MessageOptions_MessageSetWireFormat bool = false
+const Default_MessageOptions_NoStandardDescriptorAccessor bool = false
+const Default_MessageOptions_Deprecated bool = false
+
+func (m *MessageOptions) GetMessageSetWireFormat() bool {
+ if m != nil && m.MessageSetWireFormat != nil {
+ return *m.MessageSetWireFormat
+ }
+ return Default_MessageOptions_MessageSetWireFormat
+}
+
+func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool {
+ if m != nil && m.NoStandardDescriptorAccessor != nil {
+ return *m.NoStandardDescriptorAccessor
+ }
+ return Default_MessageOptions_NoStandardDescriptorAccessor
+}
+
+func (m *MessageOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_MessageOptions_Deprecated
+}
+
+func (m *MessageOptions) GetMapEntry() bool {
+ if m != nil && m.MapEntry != nil {
+ return *m.MapEntry
+ }
+ return false
+}
+
+func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type FieldOptions struct {
+ // The ctype option instructs the C++ code generator to use a different
+ // representation of the field than it normally would. See the specific
+ // options below. This option is not yet implemented in the open source
+ // release -- sorry, we'll try to include it in a future version!
+ Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"`
+ // The packed option can be enabled for repeated primitive fields to enable
+ // a more efficient representation on the wire. Rather than repeatedly
+ // writing the tag and type for each element, the entire array is encoded as
+ // a single length-delimited blob. In proto3, only explicit setting it to
+ // false will avoid using packed encoding.
+ Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"`
+ // The jstype option determines the JavaScript type used for values of the
+ // field. The option is permitted only for 64 bit integral and fixed types
+ // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
+ // is represented as JavaScript string, which avoids loss of precision that
+ // can happen when a large value is converted to a floating point JavaScript.
+ // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
+ // use the JavaScript "number" type. The behavior of the default option
+ // JS_NORMAL is implementation dependent.
+ //
+ // This option is an enum to permit additional types to be added, e.g.
+ // goog.math.Integer.
+ Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"`
+ // Should this field be parsed lazily? Lazy applies only to message-type
+ // fields. It means that when the outer message is initially parsed, the
+ // inner message's contents will not be parsed but instead stored in encoded
+ // form. The inner message will actually be parsed when it is first accessed.
+ //
+ // This is only a hint. Implementations are free to choose whether to use
+ // eager or lazy parsing regardless of the value of this option. However,
+ // setting this option true suggests that the protocol author believes that
+ // using lazy parsing on this field is worth the additional bookkeeping
+ // overhead typically needed to implement it.
+ //
+ // This option does not affect the public interface of any generated code;
+ // all method signatures remain the same. Furthermore, thread-safety of the
+ // interface is not affected by this option; const methods remain safe to
+ // call from multiple threads concurrently, while non-const methods continue
+ // to require exclusive access.
+ //
+ //
+ // Note that implementations may choose not to check required fields within
+ // a lazy sub-message. That is, calling IsInitialized() on the outer message
+ // may return true even if the inner message has missing required fields.
+ // This is necessary because otherwise the inner message would have to be
+ // parsed in order to perform the check, defeating the purpose of lazy
+ // parsing. An implementation which chooses not to check required fields
+ // must be consistent about it. That is, for any particular sub-message, the
+ // implementation must either *always* check its required fields, or *never*
+ // check its required fields, regardless of whether or not the message has
+ // been parsed.
+ Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"`
+ // Is this field deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for accessors, or it will be completely ignored; in the very least, this
+ // is a formalization for deprecating fields.
+ Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // For Google-internal migration only. Do not use.
+ Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *FieldOptions) Reset() { *m = FieldOptions{} }
+func (m *FieldOptions) String() string { return proto.CompactTextString(m) }
+func (*FieldOptions) ProtoMessage() {}
+func (*FieldOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{12} }
+
+var extRange_FieldOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_FieldOptions
+}
+
+const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING
+const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL
+const Default_FieldOptions_Lazy bool = false
+const Default_FieldOptions_Deprecated bool = false
+const Default_FieldOptions_Weak bool = false
+
+func (m *FieldOptions) GetCtype() FieldOptions_CType {
+ if m != nil && m.Ctype != nil {
+ return *m.Ctype
+ }
+ return Default_FieldOptions_Ctype
+}
+
+func (m *FieldOptions) GetPacked() bool {
+ if m != nil && m.Packed != nil {
+ return *m.Packed
+ }
+ return false
+}
+
+func (m *FieldOptions) GetJstype() FieldOptions_JSType {
+ if m != nil && m.Jstype != nil {
+ return *m.Jstype
+ }
+ return Default_FieldOptions_Jstype
+}
+
+func (m *FieldOptions) GetLazy() bool {
+ if m != nil && m.Lazy != nil {
+ return *m.Lazy
+ }
+ return Default_FieldOptions_Lazy
+}
+
+func (m *FieldOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_FieldOptions_Deprecated
+}
+
+func (m *FieldOptions) GetWeak() bool {
+ if m != nil && m.Weak != nil {
+ return *m.Weak
+ }
+ return Default_FieldOptions_Weak
+}
+
+func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type OneofOptions struct {
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OneofOptions) Reset() { *m = OneofOptions{} }
+func (m *OneofOptions) String() string { return proto.CompactTextString(m) }
+func (*OneofOptions) ProtoMessage() {}
+func (*OneofOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{13} }
+
+var extRange_OneofOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_OneofOptions
+}
+
+func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type EnumOptions struct {
+ // Set this option to true to allow mapping different tag names to the same
+ // value.
+ AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"`
+ // Is this enum deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the enum, or it will be completely ignored; in the very least, this
+ // is a formalization for deprecating enums.
+ Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *EnumOptions) Reset() { *m = EnumOptions{} }
+func (m *EnumOptions) String() string { return proto.CompactTextString(m) }
+func (*EnumOptions) ProtoMessage() {}
+func (*EnumOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{14} }
+
+var extRange_EnumOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_EnumOptions
+}
+
+const Default_EnumOptions_Deprecated bool = false
+
+func (m *EnumOptions) GetAllowAlias() bool {
+ if m != nil && m.AllowAlias != nil {
+ return *m.AllowAlias
+ }
+ return false
+}
+
+func (m *EnumOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_EnumOptions_Deprecated
+}
+
+func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type EnumValueOptions struct {
+ // Is this enum value deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the enum value, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating enum values.
+ Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} }
+func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) }
+func (*EnumValueOptions) ProtoMessage() {}
+func (*EnumValueOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{15} }
+
+var extRange_EnumValueOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_EnumValueOptions
+}
+
+const Default_EnumValueOptions_Deprecated bool = false
+
+func (m *EnumValueOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_EnumValueOptions_Deprecated
+}
+
+func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type ServiceOptions struct {
+ // Is this service deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the service, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating services.
+ Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *ServiceOptions) Reset() { *m = ServiceOptions{} }
+func (m *ServiceOptions) String() string { return proto.CompactTextString(m) }
+func (*ServiceOptions) ProtoMessage() {}
+func (*ServiceOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{16} }
+
+var extRange_ServiceOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_ServiceOptions
+}
+
+const Default_ServiceOptions_Deprecated bool = false
+
+func (m *ServiceOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_ServiceOptions_Deprecated
+}
+
+func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+type MethodOptions struct {
+ // Is this method deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the method, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating methods.
+ Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
+ IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"`
+ // The parser stores options it doesn't recognize here. See above.
+ UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *MethodOptions) Reset() { *m = MethodOptions{} }
+func (m *MethodOptions) String() string { return proto.CompactTextString(m) }
+func (*MethodOptions) ProtoMessage() {}
+func (*MethodOptions) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{17} }
+
+var extRange_MethodOptions = []proto.ExtensionRange{
+ {1000, 536870911},
+}
+
+func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_MethodOptions
+}
+
+const Default_MethodOptions_Deprecated bool = false
+const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN
+
+func (m *MethodOptions) GetDeprecated() bool {
+ if m != nil && m.Deprecated != nil {
+ return *m.Deprecated
+ }
+ return Default_MethodOptions_Deprecated
+}
+
+func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel {
+ if m != nil && m.IdempotencyLevel != nil {
+ return *m.IdempotencyLevel
+ }
+ return Default_MethodOptions_IdempotencyLevel
+}
+
+func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption {
+ if m != nil {
+ return m.UninterpretedOption
+ }
+ return nil
+}
+
+// A message representing a option the parser does not recognize. This only
+// appears in options protos created by the compiler::Parser class.
+// DescriptorPool resolves these when building Descriptor objects. Therefore,
+// options protos in descriptor objects (e.g. returned by Descriptor::options(),
+// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
+// in them.
+type UninterpretedOption struct {
+ Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"`
+ // The value of the uninterpreted option, in whatever type the tokenizer
+ // identified it as during parsing. Exactly one of these should be set.
+ IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"`
+ PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"`
+ NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"`
+ DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"`
+ StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"`
+ AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} }
+func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) }
+func (*UninterpretedOption) ProtoMessage() {}
+func (*UninterpretedOption) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{18} }
+
+func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart {
+ if m != nil {
+ return m.Name
+ }
+ return nil
+}
+
+func (m *UninterpretedOption) GetIdentifierValue() string {
+ if m != nil && m.IdentifierValue != nil {
+ return *m.IdentifierValue
+ }
+ return ""
+}
+
+func (m *UninterpretedOption) GetPositiveIntValue() uint64 {
+ if m != nil && m.PositiveIntValue != nil {
+ return *m.PositiveIntValue
+ }
+ return 0
+}
+
+func (m *UninterpretedOption) GetNegativeIntValue() int64 {
+ if m != nil && m.NegativeIntValue != nil {
+ return *m.NegativeIntValue
+ }
+ return 0
+}
+
+func (m *UninterpretedOption) GetDoubleValue() float64 {
+ if m != nil && m.DoubleValue != nil {
+ return *m.DoubleValue
+ }
+ return 0
+}
+
+func (m *UninterpretedOption) GetStringValue() []byte {
+ if m != nil {
+ return m.StringValue
+ }
+ return nil
+}
+
+func (m *UninterpretedOption) GetAggregateValue() string {
+ if m != nil && m.AggregateValue != nil {
+ return *m.AggregateValue
+ }
+ return ""
+}
+
+// The name of the uninterpreted option. Each string represents a segment in
+// a dot-separated name. is_extension is true iff a segment represents an
+// extension (denoted with parentheses in options specs in .proto files).
+// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
+// "foo.(bar.baz).qux".
+type UninterpretedOption_NamePart struct {
+ NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"`
+ IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} }
+func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) }
+func (*UninterpretedOption_NamePart) ProtoMessage() {}
+func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{18, 0}
+}
+
+func (m *UninterpretedOption_NamePart) GetNamePart() string {
+ if m != nil && m.NamePart != nil {
+ return *m.NamePart
+ }
+ return ""
+}
+
+func (m *UninterpretedOption_NamePart) GetIsExtension() bool {
+ if m != nil && m.IsExtension != nil {
+ return *m.IsExtension
+ }
+ return false
+}
+
+// Encapsulates information about the original source file from which a
+// FileDescriptorProto was generated.
+type SourceCodeInfo struct {
+ // A Location identifies a piece of source code in a .proto file which
+ // corresponds to a particular definition. This information is intended
+ // to be useful to IDEs, code indexers, documentation generators, and similar
+ // tools.
+ //
+ // For example, say we have a file like:
+ // message Foo {
+ // optional string foo = 1;
+ // }
+ // Let's look at just the field definition:
+ // optional string foo = 1;
+ // ^ ^^ ^^ ^ ^^^
+ // a bc de f ghi
+ // We have the following locations:
+ // span path represents
+ // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
+ // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
+ // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
+ // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
+ // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
+ //
+ // Notes:
+ // - A location may refer to a repeated field itself (i.e. not to any
+ // particular index within it). This is used whenever a set of elements are
+ // logically enclosed in a single code segment. For example, an entire
+ // extend block (possibly containing multiple extension definitions) will
+ // have an outer location whose path refers to the "extensions" repeated
+ // field without an index.
+ // - Multiple locations may have the same path. This happens when a single
+ // logical declaration is spread out across multiple places. The most
+ // obvious example is the "extend" block again -- there may be multiple
+ // extend blocks in the same scope, each of which will have the same path.
+ // - A location's span is not always a subset of its parent's span. For
+ // example, the "extendee" of an extension declaration appears at the
+ // beginning of the "extend" block and is shared by all extensions within
+ // the block.
+ // - Just because a location's span is a subset of some other location's span
+ // does not mean that it is a descendent. For example, a "group" defines
+ // both a type and a field in a single declaration. Thus, the locations
+ // corresponding to the type and field and their components will overlap.
+ // - Code which tries to interpret locations should probably be designed to
+ // ignore those that it doesn't understand, as more types of locations could
+ // be recorded in the future.
+ Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} }
+func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) }
+func (*SourceCodeInfo) ProtoMessage() {}
+func (*SourceCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19} }
+
+func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location {
+ if m != nil {
+ return m.Location
+ }
+ return nil
+}
+
+type SourceCodeInfo_Location struct {
+ // Identifies which part of the FileDescriptorProto was defined at this
+ // location.
+ //
+ // Each element is a field number or an index. They form a path from
+ // the root FileDescriptorProto to the place where the definition. For
+ // example, this path:
+ // [ 4, 3, 2, 7, 1 ]
+ // refers to:
+ // file.message_type(3) // 4, 3
+ // .field(7) // 2, 7
+ // .name() // 1
+ // This is because FileDescriptorProto.message_type has field number 4:
+ // repeated DescriptorProto message_type = 4;
+ // and DescriptorProto.field has field number 2:
+ // repeated FieldDescriptorProto field = 2;
+ // and FieldDescriptorProto.name has field number 1:
+ // optional string name = 1;
+ //
+ // Thus, the above path gives the location of a field name. If we removed
+ // the last element:
+ // [ 4, 3, 2, 7 ]
+ // this path refers to the whole field declaration (from the beginning
+ // of the label to the terminating semicolon).
+ Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
+ // Always has exactly three or four elements: start line, start column,
+ // end line (optional, otherwise assumed same as start line), end column.
+ // These are packed into a single field for efficiency. Note that line
+ // and column numbers are zero-based -- typically you will want to add
+ // 1 to each before displaying to a user.
+ Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"`
+ // If this SourceCodeInfo represents a complete declaration, these are any
+ // comments appearing before and after the declaration which appear to be
+ // attached to the declaration.
+ //
+ // A series of line comments appearing on consecutive lines, with no other
+ // tokens appearing on those lines, will be treated as a single comment.
+ //
+ // leading_detached_comments will keep paragraphs of comments that appear
+ // before (but not connected to) the current element. Each paragraph,
+ // separated by empty lines, will be one comment element in the repeated
+ // field.
+ //
+ // Only the comment content is provided; comment markers (e.g. //) are
+ // stripped out. For block comments, leading whitespace and an asterisk
+ // will be stripped from the beginning of each line other than the first.
+ // Newlines are included in the output.
+ //
+ // Examples:
+ //
+ // optional int32 foo = 1; // Comment attached to foo.
+ // // Comment attached to bar.
+ // optional int32 bar = 2;
+ //
+ // optional string baz = 3;
+ // // Comment attached to baz.
+ // // Another line attached to baz.
+ //
+ // // Comment attached to qux.
+ // //
+ // // Another line attached to qux.
+ // optional double qux = 4;
+ //
+ // // Detached comment for corge. This is not leading or trailing comments
+ // // to qux or corge because there are blank lines separating it from
+ // // both.
+ //
+ // // Detached comment for corge paragraph 2.
+ //
+ // optional string corge = 5;
+ // /* Block comment attached
+ // * to corge. Leading asterisks
+ // * will be removed. */
+ // /* Block comment attached to
+ // * grault. */
+ // optional int32 grault = 6;
+ //
+ // // ignored detached comments.
+ LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"`
+ TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"`
+ LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} }
+func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) }
+func (*SourceCodeInfo_Location) ProtoMessage() {}
+func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{19, 0} }
+
+func (m *SourceCodeInfo_Location) GetPath() []int32 {
+ if m != nil {
+ return m.Path
+ }
+ return nil
+}
+
+func (m *SourceCodeInfo_Location) GetSpan() []int32 {
+ if m != nil {
+ return m.Span
+ }
+ return nil
+}
+
+func (m *SourceCodeInfo_Location) GetLeadingComments() string {
+ if m != nil && m.LeadingComments != nil {
+ return *m.LeadingComments
+ }
+ return ""
+}
+
+func (m *SourceCodeInfo_Location) GetTrailingComments() string {
+ if m != nil && m.TrailingComments != nil {
+ return *m.TrailingComments
+ }
+ return ""
+}
+
+func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string {
+ if m != nil {
+ return m.LeadingDetachedComments
+ }
+ return nil
+}
+
+// Describes the relationship between generated code and its original source
+// file. A GeneratedCodeInfo message is associated with only one generated
+// source file, but may contain references to different source .proto files.
+type GeneratedCodeInfo struct {
+ // An Annotation connects some span of text in generated code to an element
+ // of its generating .proto file.
+ Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} }
+func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) }
+func (*GeneratedCodeInfo) ProtoMessage() {}
+func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{20} }
+
+func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation {
+ if m != nil {
+ return m.Annotation
+ }
+ return nil
+}
+
+type GeneratedCodeInfo_Annotation struct {
+ // Identifies the element in the original source .proto file. This field
+ // is formatted the same as SourceCodeInfo.Location.path.
+ Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
+ // Identifies the filesystem path to the original source .proto.
+ SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"`
+ // Identifies the starting offset in bytes in the generated code
+ // that relates to the identified object.
+ Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"`
+ // Identifies the ending offset in bytes in the generated code that
+ // relates to the identified offset. The end offset should be one past
+ // the last relevant byte (so the length of the text = end - begin).
+ End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} }
+func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) }
+func (*GeneratedCodeInfo_Annotation) ProtoMessage() {}
+func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) {
+ return fileDescriptor0, []int{20, 0}
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 {
+ if m != nil {
+ return m.Path
+ }
+ return nil
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string {
+ if m != nil && m.SourceFile != nil {
+ return *m.SourceFile
+ }
+ return ""
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 {
+ if m != nil && m.Begin != nil {
+ return *m.Begin
+ }
+ return 0
+}
+
+func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 {
+ if m != nil && m.End != nil {
+ return *m.End
+ }
+ return 0
+}
+
+func init() {
+ proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet")
+ proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto")
+ proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto")
+ proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange")
+ proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange")
+ proto.RegisterType((*ExtensionRangeOptions)(nil), "google.protobuf.ExtensionRangeOptions")
+ proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto")
+ proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto")
+ proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto")
+ proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto")
+ proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto")
+ proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto")
+ proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions")
+ proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions")
+ proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions")
+ proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions")
+ proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions")
+ proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions")
+ proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions")
+ proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions")
+ proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption")
+ proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart")
+ proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo")
+ proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location")
+ proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo")
+ proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation")
+ proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value)
+ proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value)
+ proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value)
+ proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value)
+ proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value)
+ proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value)
+}
+
+func init() { proto.RegisterFile("google/protobuf/descriptor.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 2519 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xdd, 0x6e, 0x1b, 0xc7,
+ 0x15, 0x0e, 0x7f, 0x45, 0x1e, 0x52, 0xd4, 0x68, 0xa4, 0xd8, 0x6b, 0xe5, 0xc7, 0x32, 0xf3, 0x63,
+ 0xd9, 0x69, 0xa8, 0x40, 0xb1, 0x1d, 0x47, 0x29, 0xd2, 0x52, 0xe4, 0x5a, 0xa1, 0x4a, 0x91, 0xec,
+ 0x92, 0x6a, 0x7e, 0x6e, 0x16, 0xa3, 0xdd, 0x21, 0xb9, 0xf6, 0x72, 0x77, 0xb3, 0xbb, 0xb4, 0xad,
+ 0xa0, 0x17, 0x06, 0x7a, 0x55, 0xa0, 0x0f, 0x50, 0x14, 0x45, 0x2f, 0x72, 0x13, 0xa0, 0x0f, 0x50,
+ 0x20, 0x77, 0x7d, 0x82, 0x02, 0x79, 0x83, 0xa2, 0x28, 0xd0, 0x3e, 0x46, 0x31, 0x33, 0xbb, 0xcb,
+ 0x5d, 0xfe, 0xc4, 0x6a, 0x80, 0x38, 0x57, 0xe4, 0x7c, 0xe7, 0x3b, 0x67, 0xce, 0x9c, 0x39, 0x33,
+ 0x73, 0x66, 0x16, 0x76, 0x47, 0xb6, 0x3d, 0x32, 0xe9, 0xbe, 0xe3, 0xda, 0xbe, 0x7d, 0x3e, 0x1d,
+ 0xee, 0xeb, 0xd4, 0xd3, 0x5c, 0xc3, 0xf1, 0x6d, 0xb7, 0xc6, 0x31, 0xbc, 0x21, 0x18, 0xb5, 0x90,
+ 0x51, 0x3d, 0x85, 0xcd, 0x07, 0x86, 0x49, 0x9b, 0x11, 0xb1, 0x4f, 0x7d, 0x7c, 0x1f, 0xb2, 0x43,
+ 0xc3, 0xa4, 0x52, 0x6a, 0x37, 0xb3, 0x57, 0x3a, 0x78, 0xb3, 0x36, 0xa7, 0x54, 0x4b, 0x6a, 0xf4,
+ 0x18, 0xac, 0x70, 0x8d, 0xea, 0xbf, 0xb3, 0xb0, 0xb5, 0x44, 0x8a, 0x31, 0x64, 0x2d, 0x32, 0x61,
+ 0x16, 0x53, 0x7b, 0x45, 0x85, 0xff, 0xc7, 0x12, 0xac, 0x39, 0x44, 0x7b, 0x44, 0x46, 0x54, 0x4a,
+ 0x73, 0x38, 0x6c, 0xe2, 0xd7, 0x01, 0x74, 0xea, 0x50, 0x4b, 0xa7, 0x96, 0x76, 0x21, 0x65, 0x76,
+ 0x33, 0x7b, 0x45, 0x25, 0x86, 0xe0, 0x77, 0x60, 0xd3, 0x99, 0x9e, 0x9b, 0x86, 0xa6, 0xc6, 0x68,
+ 0xb0, 0x9b, 0xd9, 0xcb, 0x29, 0x48, 0x08, 0x9a, 0x33, 0xf2, 0x4d, 0xd8, 0x78, 0x42, 0xc9, 0xa3,
+ 0x38, 0xb5, 0xc4, 0xa9, 0x15, 0x06, 0xc7, 0x88, 0x0d, 0x28, 0x4f, 0xa8, 0xe7, 0x91, 0x11, 0x55,
+ 0xfd, 0x0b, 0x87, 0x4a, 0x59, 0x3e, 0xfa, 0xdd, 0x85, 0xd1, 0xcf, 0x8f, 0xbc, 0x14, 0x68, 0x0d,
+ 0x2e, 0x1c, 0x8a, 0xeb, 0x50, 0xa4, 0xd6, 0x74, 0x22, 0x2c, 0xe4, 0x56, 0xc4, 0x4f, 0xb6, 0xa6,
+ 0x93, 0x79, 0x2b, 0x05, 0xa6, 0x16, 0x98, 0x58, 0xf3, 0xa8, 0xfb, 0xd8, 0xd0, 0xa8, 0x94, 0xe7,
+ 0x06, 0x6e, 0x2e, 0x18, 0xe8, 0x0b, 0xf9, 0xbc, 0x8d, 0x50, 0x0f, 0x37, 0xa0, 0x48, 0x9f, 0xfa,
+ 0xd4, 0xf2, 0x0c, 0xdb, 0x92, 0xd6, 0xb8, 0x91, 0xb7, 0x96, 0xcc, 0x22, 0x35, 0xf5, 0x79, 0x13,
+ 0x33, 0x3d, 0x7c, 0x0f, 0xd6, 0x6c, 0xc7, 0x37, 0x6c, 0xcb, 0x93, 0x0a, 0xbb, 0xa9, 0xbd, 0xd2,
+ 0xc1, 0xab, 0x4b, 0x13, 0xa1, 0x2b, 0x38, 0x4a, 0x48, 0xc6, 0x2d, 0x40, 0x9e, 0x3d, 0x75, 0x35,
+ 0xaa, 0x6a, 0xb6, 0x4e, 0x55, 0xc3, 0x1a, 0xda, 0x52, 0x91, 0x1b, 0xb8, 0xbe, 0x38, 0x10, 0x4e,
+ 0x6c, 0xd8, 0x3a, 0x6d, 0x59, 0x43, 0x5b, 0xa9, 0x78, 0x89, 0x36, 0xbe, 0x02, 0x79, 0xef, 0xc2,
+ 0xf2, 0xc9, 0x53, 0xa9, 0xcc, 0x33, 0x24, 0x68, 0x55, 0xbf, 0xcd, 0xc3, 0xc6, 0x65, 0x52, 0xec,
+ 0x23, 0xc8, 0x0d, 0xd9, 0x28, 0xa5, 0xf4, 0xff, 0x13, 0x03, 0xa1, 0x93, 0x0c, 0x62, 0xfe, 0x07,
+ 0x06, 0xb1, 0x0e, 0x25, 0x8b, 0x7a, 0x3e, 0xd5, 0x45, 0x46, 0x64, 0x2e, 0x99, 0x53, 0x20, 0x94,
+ 0x16, 0x53, 0x2a, 0xfb, 0x83, 0x52, 0xea, 0x33, 0xd8, 0x88, 0x5c, 0x52, 0x5d, 0x62, 0x8d, 0xc2,
+ 0xdc, 0xdc, 0x7f, 0x9e, 0x27, 0x35, 0x39, 0xd4, 0x53, 0x98, 0x9a, 0x52, 0xa1, 0x89, 0x36, 0x6e,
+ 0x02, 0xd8, 0x16, 0xb5, 0x87, 0xaa, 0x4e, 0x35, 0x53, 0x2a, 0xac, 0x88, 0x52, 0x97, 0x51, 0x16,
+ 0xa2, 0x64, 0x0b, 0x54, 0x33, 0xf1, 0x87, 0xb3, 0x54, 0x5b, 0x5b, 0x91, 0x29, 0xa7, 0x62, 0x91,
+ 0x2d, 0x64, 0xdb, 0x19, 0x54, 0x5c, 0xca, 0xf2, 0x9e, 0xea, 0xc1, 0xc8, 0x8a, 0xdc, 0x89, 0xda,
+ 0x73, 0x47, 0xa6, 0x04, 0x6a, 0x62, 0x60, 0xeb, 0x6e, 0xbc, 0x89, 0xdf, 0x80, 0x08, 0x50, 0x79,
+ 0x5a, 0x01, 0xdf, 0x85, 0xca, 0x21, 0xd8, 0x21, 0x13, 0xba, 0xf3, 0x15, 0x54, 0x92, 0xe1, 0xc1,
+ 0xdb, 0x90, 0xf3, 0x7c, 0xe2, 0xfa, 0x3c, 0x0b, 0x73, 0x8a, 0x68, 0x60, 0x04, 0x19, 0x6a, 0xe9,
+ 0x7c, 0x97, 0xcb, 0x29, 0xec, 0x2f, 0xfe, 0xe5, 0x6c, 0xc0, 0x19, 0x3e, 0xe0, 0xb7, 0x17, 0x67,
+ 0x34, 0x61, 0x79, 0x7e, 0xdc, 0x3b, 0x1f, 0xc0, 0x7a, 0x62, 0x00, 0x97, 0xed, 0xba, 0xfa, 0x5b,
+ 0x78, 0x79, 0xa9, 0x69, 0xfc, 0x19, 0x6c, 0x4f, 0x2d, 0xc3, 0xf2, 0xa9, 0xeb, 0xb8, 0x94, 0x65,
+ 0xac, 0xe8, 0x4a, 0xfa, 0xcf, 0xda, 0x8a, 0x9c, 0x3b, 0x8b, 0xb3, 0x85, 0x15, 0x65, 0x6b, 0xba,
+ 0x08, 0xde, 0x2e, 0x16, 0xfe, 0xbb, 0x86, 0x9e, 0x3d, 0x7b, 0xf6, 0x2c, 0x5d, 0xfd, 0x63, 0x1e,
+ 0xb6, 0x97, 0xad, 0x99, 0xa5, 0xcb, 0xf7, 0x0a, 0xe4, 0xad, 0xe9, 0xe4, 0x9c, 0xba, 0x3c, 0x48,
+ 0x39, 0x25, 0x68, 0xe1, 0x3a, 0xe4, 0x4c, 0x72, 0x4e, 0x4d, 0x29, 0xbb, 0x9b, 0xda, 0xab, 0x1c,
+ 0xbc, 0x73, 0xa9, 0x55, 0x59, 0x6b, 0x33, 0x15, 0x45, 0x68, 0xe2, 0x8f, 0x21, 0x1b, 0x6c, 0xd1,
+ 0xcc, 0xc2, 0xed, 0xcb, 0x59, 0x60, 0x6b, 0x49, 0xe1, 0x7a, 0xf8, 0x15, 0x28, 0xb2, 0x5f, 0x91,
+ 0x1b, 0x79, 0xee, 0x73, 0x81, 0x01, 0x2c, 0x2f, 0xf0, 0x0e, 0x14, 0xf8, 0x32, 0xd1, 0x69, 0x78,
+ 0xb4, 0x45, 0x6d, 0x96, 0x58, 0x3a, 0x1d, 0x92, 0xa9, 0xe9, 0xab, 0x8f, 0x89, 0x39, 0xa5, 0x3c,
+ 0xe1, 0x8b, 0x4a, 0x39, 0x00, 0x7f, 0xc3, 0x30, 0x7c, 0x1d, 0x4a, 0x62, 0x55, 0x19, 0x96, 0x4e,
+ 0x9f, 0xf2, 0xdd, 0x33, 0xa7, 0x88, 0x85, 0xd6, 0x62, 0x08, 0xeb, 0xfe, 0xa1, 0x67, 0x5b, 0x61,
+ 0x6a, 0xf2, 0x2e, 0x18, 0xc0, 0xbb, 0xff, 0x60, 0x7e, 0xe3, 0x7e, 0x6d, 0xf9, 0xf0, 0xe6, 0x73,
+ 0xaa, 0xfa, 0xb7, 0x34, 0x64, 0xf9, 0x7e, 0xb1, 0x01, 0xa5, 0xc1, 0xe7, 0x3d, 0x59, 0x6d, 0x76,
+ 0xcf, 0x8e, 0xda, 0x32, 0x4a, 0xe1, 0x0a, 0x00, 0x07, 0x1e, 0xb4, 0xbb, 0xf5, 0x01, 0x4a, 0x47,
+ 0xed, 0x56, 0x67, 0x70, 0xef, 0x0e, 0xca, 0x44, 0x0a, 0x67, 0x02, 0xc8, 0xc6, 0x09, 0xef, 0x1f,
+ 0xa0, 0x1c, 0x46, 0x50, 0x16, 0x06, 0x5a, 0x9f, 0xc9, 0xcd, 0x7b, 0x77, 0x50, 0x3e, 0x89, 0xbc,
+ 0x7f, 0x80, 0xd6, 0xf0, 0x3a, 0x14, 0x39, 0x72, 0xd4, 0xed, 0xb6, 0x51, 0x21, 0xb2, 0xd9, 0x1f,
+ 0x28, 0xad, 0xce, 0x31, 0x2a, 0x46, 0x36, 0x8f, 0x95, 0xee, 0x59, 0x0f, 0x41, 0x64, 0xe1, 0x54,
+ 0xee, 0xf7, 0xeb, 0xc7, 0x32, 0x2a, 0x45, 0x8c, 0xa3, 0xcf, 0x07, 0x72, 0x1f, 0x95, 0x13, 0x6e,
+ 0xbd, 0x7f, 0x80, 0xd6, 0xa3, 0x2e, 0xe4, 0xce, 0xd9, 0x29, 0xaa, 0xe0, 0x4d, 0x58, 0x17, 0x5d,
+ 0x84, 0x4e, 0x6c, 0xcc, 0x41, 0xf7, 0xee, 0x20, 0x34, 0x73, 0x44, 0x58, 0xd9, 0x4c, 0x00, 0xf7,
+ 0xee, 0x20, 0x5c, 0x6d, 0x40, 0x8e, 0x67, 0x17, 0xc6, 0x50, 0x69, 0xd7, 0x8f, 0xe4, 0xb6, 0xda,
+ 0xed, 0x0d, 0x5a, 0xdd, 0x4e, 0xbd, 0x8d, 0x52, 0x33, 0x4c, 0x91, 0x7f, 0x7d, 0xd6, 0x52, 0xe4,
+ 0x26, 0x4a, 0xc7, 0xb1, 0x9e, 0x5c, 0x1f, 0xc8, 0x4d, 0x94, 0xa9, 0x6a, 0xb0, 0xbd, 0x6c, 0x9f,
+ 0x5c, 0xba, 0x32, 0x62, 0x53, 0x9c, 0x5e, 0x31, 0xc5, 0xdc, 0xd6, 0xc2, 0x14, 0x7f, 0x9d, 0x82,
+ 0xad, 0x25, 0x67, 0xc5, 0xd2, 0x4e, 0x7e, 0x01, 0x39, 0x91, 0xa2, 0xe2, 0xf4, 0xbc, 0xb5, 0xf4,
+ 0xd0, 0xe1, 0x09, 0xbb, 0x70, 0x82, 0x72, 0xbd, 0x78, 0x05, 0x91, 0x59, 0x51, 0x41, 0x30, 0x13,
+ 0x0b, 0x4e, 0xfe, 0x2e, 0x05, 0xd2, 0x2a, 0xdb, 0xcf, 0xd9, 0x28, 0xd2, 0x89, 0x8d, 0xe2, 0xa3,
+ 0x79, 0x07, 0x6e, 0xac, 0x1e, 0xc3, 0x82, 0x17, 0xdf, 0xa4, 0xe0, 0xca, 0xf2, 0x42, 0x6b, 0xa9,
+ 0x0f, 0x1f, 0x43, 0x7e, 0x42, 0xfd, 0xb1, 0x1d, 0x16, 0x1b, 0x6f, 0x2f, 0x39, 0xc2, 0x98, 0x78,
+ 0x3e, 0x56, 0x81, 0x56, 0xfc, 0x0c, 0xcc, 0xac, 0xaa, 0x96, 0x84, 0x37, 0x0b, 0x9e, 0xfe, 0x3e,
+ 0x0d, 0x2f, 0x2f, 0x35, 0xbe, 0xd4, 0xd1, 0xd7, 0x00, 0x0c, 0xcb, 0x99, 0xfa, 0xa2, 0xa0, 0x10,
+ 0xfb, 0x53, 0x91, 0x23, 0x7c, 0xed, 0xb3, 0xbd, 0x67, 0xea, 0x47, 0xf2, 0x0c, 0x97, 0x83, 0x80,
+ 0x38, 0xe1, 0xfe, 0xcc, 0xd1, 0x2c, 0x77, 0xf4, 0xf5, 0x15, 0x23, 0x5d, 0x38, 0xab, 0xdf, 0x03,
+ 0xa4, 0x99, 0x06, 0xb5, 0x7c, 0xd5, 0xf3, 0x5d, 0x4a, 0x26, 0x86, 0x35, 0xe2, 0x1b, 0x70, 0xe1,
+ 0x30, 0x37, 0x24, 0xa6, 0x47, 0x95, 0x0d, 0x21, 0xee, 0x87, 0x52, 0xa6, 0xc1, 0xcf, 0x38, 0x37,
+ 0xa6, 0x91, 0x4f, 0x68, 0x08, 0x71, 0xa4, 0x51, 0xfd, 0xb6, 0x00, 0xa5, 0x58, 0x59, 0x8a, 0x6f,
+ 0x40, 0xf9, 0x21, 0x79, 0x4c, 0xd4, 0xf0, 0xaa, 0x21, 0x22, 0x51, 0x62, 0x58, 0x2f, 0xb8, 0x6e,
+ 0xbc, 0x07, 0xdb, 0x9c, 0x62, 0x4f, 0x7d, 0xea, 0xaa, 0x9a, 0x49, 0x3c, 0x8f, 0x07, 0xad, 0xc0,
+ 0xa9, 0x98, 0xc9, 0xba, 0x4c, 0xd4, 0x08, 0x25, 0xf8, 0x2e, 0x6c, 0x71, 0x8d, 0xc9, 0xd4, 0xf4,
+ 0x0d, 0xc7, 0xa4, 0x2a, 0xbb, 0xfc, 0x78, 0x7c, 0x23, 0x8e, 0x3c, 0xdb, 0x64, 0x8c, 0xd3, 0x80,
+ 0xc0, 0x3c, 0xf2, 0x70, 0x13, 0x5e, 0xe3, 0x6a, 0x23, 0x6a, 0x51, 0x97, 0xf8, 0x54, 0xa5, 0x5f,
+ 0x4e, 0x89, 0xe9, 0xa9, 0xc4, 0xd2, 0xd5, 0x31, 0xf1, 0xc6, 0xd2, 0x36, 0x33, 0x70, 0x94, 0x96,
+ 0x52, 0xca, 0x35, 0x46, 0x3c, 0x0e, 0x78, 0x32, 0xa7, 0xd5, 0x2d, 0xfd, 0x13, 0xe2, 0x8d, 0xf1,
+ 0x21, 0x5c, 0xe1, 0x56, 0x3c, 0xdf, 0x35, 0xac, 0x91, 0xaa, 0x8d, 0xa9, 0xf6, 0x48, 0x9d, 0xfa,
+ 0xc3, 0xfb, 0xd2, 0x2b, 0xf1, 0xfe, 0xb9, 0x87, 0x7d, 0xce, 0x69, 0x30, 0xca, 0x99, 0x3f, 0xbc,
+ 0x8f, 0xfb, 0x50, 0x66, 0x93, 0x31, 0x31, 0xbe, 0xa2, 0xea, 0xd0, 0x76, 0xf9, 0xc9, 0x52, 0x59,
+ 0xb2, 0xb2, 0x63, 0x11, 0xac, 0x75, 0x03, 0x85, 0x53, 0x5b, 0xa7, 0x87, 0xb9, 0x7e, 0x4f, 0x96,
+ 0x9b, 0x4a, 0x29, 0xb4, 0xf2, 0xc0, 0x76, 0x59, 0x42, 0x8d, 0xec, 0x28, 0xc0, 0x25, 0x91, 0x50,
+ 0x23, 0x3b, 0x0c, 0xef, 0x5d, 0xd8, 0xd2, 0x34, 0x31, 0x66, 0x43, 0x53, 0x83, 0x2b, 0x8a, 0x27,
+ 0xa1, 0x44, 0xb0, 0x34, 0xed, 0x58, 0x10, 0x82, 0x1c, 0xf7, 0xf0, 0x87, 0xf0, 0xf2, 0x2c, 0x58,
+ 0x71, 0xc5, 0xcd, 0x85, 0x51, 0xce, 0xab, 0xde, 0x85, 0x2d, 0xe7, 0x62, 0x51, 0x11, 0x27, 0x7a,
+ 0x74, 0x2e, 0xe6, 0xd5, 0x3e, 0x80, 0x6d, 0x67, 0xec, 0x2c, 0xea, 0xdd, 0x8e, 0xeb, 0x61, 0x67,
+ 0xec, 0xcc, 0x2b, 0xbe, 0xc5, 0xef, 0xab, 0x2e, 0xd5, 0x88, 0x4f, 0x75, 0xe9, 0x6a, 0x9c, 0x1e,
+ 0x13, 0xe0, 0x7d, 0x40, 0x9a, 0xa6, 0x52, 0x8b, 0x9c, 0x9b, 0x54, 0x25, 0x2e, 0xb5, 0x88, 0x27,
+ 0x5d, 0x8f, 0x93, 0x2b, 0x9a, 0x26, 0x73, 0x69, 0x9d, 0x0b, 0xf1, 0x6d, 0xd8, 0xb4, 0xcf, 0x1f,
+ 0x6a, 0x22, 0x25, 0x55, 0xc7, 0xa5, 0x43, 0xe3, 0xa9, 0xf4, 0x26, 0x8f, 0xef, 0x06, 0x13, 0xf0,
+ 0x84, 0xec, 0x71, 0x18, 0xdf, 0x02, 0xa4, 0x79, 0x63, 0xe2, 0x3a, 0xbc, 0x26, 0xf0, 0x1c, 0xa2,
+ 0x51, 0xe9, 0x2d, 0x41, 0x15, 0x78, 0x27, 0x84, 0xd9, 0x92, 0xf0, 0x9e, 0x18, 0x43, 0x3f, 0xb4,
+ 0x78, 0x53, 0x2c, 0x09, 0x8e, 0x05, 0xd6, 0xf6, 0x00, 0xb1, 0x50, 0x24, 0x3a, 0xde, 0xe3, 0xb4,
+ 0x8a, 0x33, 0x76, 0xe2, 0xfd, 0xbe, 0x01, 0xeb, 0x8c, 0x39, 0xeb, 0xf4, 0x96, 0xa8, 0x67, 0x9c,
+ 0x71, 0xac, 0xc7, 0x1f, 0xad, 0xb4, 0xac, 0x1e, 0x42, 0x39, 0x9e, 0x9f, 0xb8, 0x08, 0x22, 0x43,
+ 0x51, 0x8a, 0x9d, 0xf5, 0x8d, 0x6e, 0x93, 0x9d, 0xd2, 0x5f, 0xc8, 0x28, 0xcd, 0xaa, 0x85, 0x76,
+ 0x6b, 0x20, 0xab, 0xca, 0x59, 0x67, 0xd0, 0x3a, 0x95, 0x51, 0x26, 0x56, 0x96, 0x9e, 0x64, 0x0b,
+ 0x6f, 0xa3, 0x9b, 0xd5, 0xef, 0xd2, 0x50, 0x49, 0xde, 0x33, 0xf0, 0xcf, 0xe1, 0x6a, 0xf8, 0x28,
+ 0xe0, 0x51, 0x5f, 0x7d, 0x62, 0xb8, 0x7c, 0xe1, 0x4c, 0x88, 0xa8, 0xb3, 0xa3, 0xa9, 0xdb, 0x0e,
+ 0x58, 0x7d, 0xea, 0x7f, 0x6a, 0xb8, 0x6c, 0x59, 0x4c, 0x88, 0x8f, 0xdb, 0x70, 0xdd, 0xb2, 0x55,
+ 0xcf, 0x27, 0x96, 0x4e, 0x5c, 0x5d, 0x9d, 0x3d, 0xc7, 0xa8, 0x44, 0xd3, 0xa8, 0xe7, 0xd9, 0xe2,
+ 0xc0, 0x8a, 0xac, 0xbc, 0x6a, 0xd9, 0xfd, 0x80, 0x3c, 0xdb, 0xc9, 0xeb, 0x01, 0x75, 0x2e, 0xcd,
+ 0x32, 0xab, 0xd2, 0xec, 0x15, 0x28, 0x4e, 0x88, 0xa3, 0x52, 0xcb, 0x77, 0x2f, 0x78, 0x75, 0x59,
+ 0x50, 0x0a, 0x13, 0xe2, 0xc8, 0xac, 0xfd, 0x42, 0x8a, 0xfc, 0x93, 0x6c, 0xa1, 0x80, 0x8a, 0x27,
+ 0xd9, 0x42, 0x11, 0x41, 0xf5, 0x5f, 0x19, 0x28, 0xc7, 0xab, 0x4d, 0x56, 0xbc, 0x6b, 0xfc, 0x64,
+ 0x49, 0xf1, 0xbd, 0xe7, 0x8d, 0xef, 0xad, 0x4d, 0x6b, 0x0d, 0x76, 0xe4, 0x1c, 0xe6, 0x45, 0x0d,
+ 0xa8, 0x08, 0x4d, 0x76, 0xdc, 0xb3, 0xdd, 0x86, 0x8a, 0x7b, 0x4d, 0x41, 0x09, 0x5a, 0xf8, 0x18,
+ 0xf2, 0x0f, 0x3d, 0x6e, 0x3b, 0xcf, 0x6d, 0xbf, 0xf9, 0xfd, 0xb6, 0x4f, 0xfa, 0xdc, 0x78, 0xf1,
+ 0xa4, 0xaf, 0x76, 0xba, 0xca, 0x69, 0xbd, 0xad, 0x04, 0xea, 0xf8, 0x1a, 0x64, 0x4d, 0xf2, 0xd5,
+ 0x45, 0xf2, 0x70, 0xe2, 0xd0, 0x65, 0x27, 0xe1, 0x1a, 0x64, 0x9f, 0x50, 0xf2, 0x28, 0x79, 0x24,
+ 0x70, 0xe8, 0x47, 0x5c, 0x0c, 0xfb, 0x90, 0xe3, 0xf1, 0xc2, 0x00, 0x41, 0xc4, 0xd0, 0x4b, 0xb8,
+ 0x00, 0xd9, 0x46, 0x57, 0x61, 0x0b, 0x02, 0x41, 0x59, 0xa0, 0x6a, 0xaf, 0x25, 0x37, 0x64, 0x94,
+ 0xae, 0xde, 0x85, 0xbc, 0x08, 0x02, 0x5b, 0x2c, 0x51, 0x18, 0xd0, 0x4b, 0x41, 0x33, 0xb0, 0x91,
+ 0x0a, 0xa5, 0x67, 0xa7, 0x47, 0xb2, 0x82, 0xd2, 0xc9, 0xa9, 0xce, 0xa2, 0x5c, 0xd5, 0x83, 0x72,
+ 0xbc, 0xdc, 0x7c, 0x31, 0x57, 0xc9, 0xbf, 0xa7, 0xa0, 0x14, 0x2b, 0x1f, 0x59, 0xe1, 0x42, 0x4c,
+ 0xd3, 0x7e, 0xa2, 0x12, 0xd3, 0x20, 0x5e, 0x90, 0x1a, 0xc0, 0xa1, 0x3a, 0x43, 0x2e, 0x3b, 0x75,
+ 0x2f, 0x68, 0x89, 0xe4, 0x50, 0xbe, 0xfa, 0x97, 0x14, 0xa0, 0xf9, 0x02, 0x74, 0xce, 0xcd, 0xd4,
+ 0x4f, 0xe9, 0x66, 0xf5, 0xcf, 0x29, 0xa8, 0x24, 0xab, 0xce, 0x39, 0xf7, 0x6e, 0xfc, 0xa4, 0xee,
+ 0xfd, 0x33, 0x0d, 0xeb, 0x89, 0x5a, 0xf3, 0xb2, 0xde, 0x7d, 0x09, 0x9b, 0x86, 0x4e, 0x27, 0x8e,
+ 0xed, 0x53, 0x4b, 0xbb, 0x50, 0x4d, 0xfa, 0x98, 0x9a, 0x52, 0x95, 0x6f, 0x1a, 0xfb, 0xdf, 0x5f,
+ 0xcd, 0xd6, 0x5a, 0x33, 0xbd, 0x36, 0x53, 0x3b, 0xdc, 0x6a, 0x35, 0xe5, 0xd3, 0x5e, 0x77, 0x20,
+ 0x77, 0x1a, 0x9f, 0xab, 0x67, 0x9d, 0x5f, 0x75, 0xba, 0x9f, 0x76, 0x14, 0x64, 0xcc, 0xd1, 0x7e,
+ 0xc4, 0x65, 0xdf, 0x03, 0x34, 0xef, 0x14, 0xbe, 0x0a, 0xcb, 0xdc, 0x42, 0x2f, 0xe1, 0x2d, 0xd8,
+ 0xe8, 0x74, 0xd5, 0x7e, 0xab, 0x29, 0xab, 0xf2, 0x83, 0x07, 0x72, 0x63, 0xd0, 0x17, 0xd7, 0xfb,
+ 0x88, 0x3d, 0x48, 0x2c, 0xf0, 0xea, 0x9f, 0x32, 0xb0, 0xb5, 0xc4, 0x13, 0x5c, 0x0f, 0x6e, 0x16,
+ 0xe2, 0xb2, 0xf3, 0xee, 0x65, 0xbc, 0xaf, 0xb1, 0x82, 0xa0, 0x47, 0x5c, 0x3f, 0xb8, 0x88, 0xdc,
+ 0x02, 0x16, 0x25, 0xcb, 0x37, 0x86, 0x06, 0x75, 0x83, 0xd7, 0x10, 0x71, 0xdd, 0xd8, 0x98, 0xe1,
+ 0xe2, 0x41, 0xe4, 0x67, 0x80, 0x1d, 0xdb, 0x33, 0x7c, 0xe3, 0x31, 0x55, 0x0d, 0x2b, 0x7c, 0x3a,
+ 0x61, 0xd7, 0x8f, 0xac, 0x82, 0x42, 0x49, 0xcb, 0xf2, 0x23, 0xb6, 0x45, 0x47, 0x64, 0x8e, 0xcd,
+ 0x36, 0xf3, 0x8c, 0x82, 0x42, 0x49, 0xc4, 0xbe, 0x01, 0x65, 0xdd, 0x9e, 0xb2, 0x9a, 0x4c, 0xf0,
+ 0xd8, 0xd9, 0x91, 0x52, 0x4a, 0x02, 0x8b, 0x28, 0x41, 0xb5, 0x3d, 0x7b, 0xb3, 0x29, 0x2b, 0x25,
+ 0x81, 0x09, 0xca, 0x4d, 0xd8, 0x20, 0xa3, 0x91, 0xcb, 0x8c, 0x87, 0x86, 0xc4, 0xfd, 0xa1, 0x12,
+ 0xc1, 0x9c, 0xb8, 0x73, 0x02, 0x85, 0x30, 0x0e, 0xec, 0xa8, 0x66, 0x91, 0x50, 0x1d, 0xf1, 0x6e,
+ 0x97, 0xde, 0x2b, 0x2a, 0x05, 0x2b, 0x14, 0xde, 0x80, 0xb2, 0xe1, 0xa9, 0xb3, 0x27, 0xe8, 0xf4,
+ 0x6e, 0x7a, 0xaf, 0xa0, 0x94, 0x0c, 0x2f, 0x7a, 0xbe, 0xab, 0x7e, 0x93, 0x86, 0x4a, 0xf2, 0x09,
+ 0x1d, 0x37, 0xa1, 0x60, 0xda, 0x1a, 0xe1, 0xa9, 0x25, 0xbe, 0xdf, 0xec, 0x3d, 0xe7, 0xd5, 0xbd,
+ 0xd6, 0x0e, 0xf8, 0x4a, 0xa4, 0xb9, 0xf3, 0x8f, 0x14, 0x14, 0x42, 0x18, 0x5f, 0x81, 0xac, 0x43,
+ 0xfc, 0x31, 0x37, 0x97, 0x3b, 0x4a, 0xa3, 0x94, 0xc2, 0xdb, 0x0c, 0xf7, 0x1c, 0x62, 0xf1, 0x14,
+ 0x08, 0x70, 0xd6, 0x66, 0xf3, 0x6a, 0x52, 0xa2, 0xf3, 0xcb, 0x89, 0x3d, 0x99, 0x50, 0xcb, 0xf7,
+ 0xc2, 0x79, 0x0d, 0xf0, 0x46, 0x00, 0xe3, 0x77, 0x60, 0xd3, 0x77, 0x89, 0x61, 0x26, 0xb8, 0x59,
+ 0xce, 0x45, 0xa1, 0x20, 0x22, 0x1f, 0xc2, 0xb5, 0xd0, 0xae, 0x4e, 0x7d, 0xa2, 0x8d, 0xa9, 0x3e,
+ 0x53, 0xca, 0xf3, 0xf7, 0xd9, 0xab, 0x01, 0xa1, 0x19, 0xc8, 0x43, 0xdd, 0xea, 0x77, 0x29, 0xd8,
+ 0x0c, 0xaf, 0x53, 0x7a, 0x14, 0xac, 0x53, 0x00, 0x62, 0x59, 0xb6, 0x1f, 0x0f, 0xd7, 0x62, 0x2a,
+ 0x2f, 0xe8, 0xd5, 0xea, 0x91, 0x92, 0x12, 0x33, 0xb0, 0x33, 0x01, 0x98, 0x49, 0x56, 0x86, 0xed,
+ 0x3a, 0x94, 0x82, 0xef, 0x23, 0xfc, 0x23, 0x9b, 0xb8, 0x80, 0x83, 0x80, 0xd8, 0xbd, 0x0b, 0x6f,
+ 0x43, 0xee, 0x9c, 0x8e, 0x0c, 0x2b, 0x78, 0xf5, 0x14, 0x8d, 0xf0, 0x25, 0x37, 0x1b, 0xbd, 0xe4,
+ 0x1e, 0xfd, 0x21, 0x05, 0x5b, 0x9a, 0x3d, 0x99, 0xf7, 0xf7, 0x08, 0xcd, 0xbd, 0x02, 0x78, 0x9f,
+ 0xa4, 0xbe, 0xf8, 0x78, 0x64, 0xf8, 0xe3, 0xe9, 0x79, 0x4d, 0xb3, 0x27, 0xfb, 0x23, 0xdb, 0x24,
+ 0xd6, 0x68, 0xf6, 0x95, 0x90, 0xff, 0xd1, 0xde, 0x1d, 0x51, 0xeb, 0xdd, 0x91, 0x1d, 0xfb, 0x66,
+ 0xf8, 0xd1, 0xec, 0xef, 0xd7, 0xe9, 0xcc, 0x71, 0xef, 0xe8, 0xaf, 0xe9, 0x9d, 0x63, 0xd1, 0x57,
+ 0x2f, 0x8c, 0x8d, 0x42, 0x87, 0x26, 0xd5, 0xd8, 0x78, 0xff, 0x17, 0x00, 0x00, 0xff, 0xff, 0x0c,
+ 0xab, 0xb6, 0x37, 0x7e, 0x1c, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto
new file mode 100644
index 0000000..4d4fb37
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto
@@ -0,0 +1,849 @@
+// 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)
+// Based on original Protocol Buffers design by
+// Sanjay Ghemawat, Jeff Dean, and others.
+//
+// The messages in this file describe the definitions found in .proto files.
+// A valid .proto file can be translated directly to a FileDescriptorProto
+// without any other information (e.g. without reading its imports).
+
+
+syntax = "proto2";
+
+package google.protobuf;
+option go_package = "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "DescriptorProtos";
+option csharp_namespace = "Google.Protobuf.Reflection";
+option objc_class_prefix = "GPB";
+
+// descriptor.proto must be optimized for speed because reflection-based
+// algorithms don't work during bootstrapping.
+option optimize_for = SPEED;
+
+// The protocol compiler can output a FileDescriptorSet containing the .proto
+// files it parses.
+message FileDescriptorSet {
+ repeated FileDescriptorProto file = 1;
+}
+
+// Describes a complete .proto file.
+message FileDescriptorProto {
+ optional string name = 1; // file name, relative to root of source tree
+ optional string package = 2; // e.g. "foo", "foo.bar", etc.
+
+ // Names of files imported by this file.
+ repeated string dependency = 3;
+ // Indexes of the public imported files in the dependency list above.
+ repeated int32 public_dependency = 10;
+ // Indexes of the weak imported files in the dependency list.
+ // For Google-internal migration only. Do not use.
+ repeated int32 weak_dependency = 11;
+
+ // All top-level definitions in this file.
+ repeated DescriptorProto message_type = 4;
+ repeated EnumDescriptorProto enum_type = 5;
+ repeated ServiceDescriptorProto service = 6;
+ repeated FieldDescriptorProto extension = 7;
+
+ optional FileOptions options = 8;
+
+ // This field contains optional information about the original source code.
+ // You may safely remove this entire field without harming runtime
+ // functionality of the descriptors -- the information is needed only by
+ // development tools.
+ optional SourceCodeInfo source_code_info = 9;
+
+ // The syntax of the proto file.
+ // The supported values are "proto2" and "proto3".
+ optional string syntax = 12;
+}
+
+// Describes a message type.
+message DescriptorProto {
+ optional string name = 1;
+
+ repeated FieldDescriptorProto field = 2;
+ repeated FieldDescriptorProto extension = 6;
+
+ repeated DescriptorProto nested_type = 3;
+ repeated EnumDescriptorProto enum_type = 4;
+
+ message ExtensionRange {
+ optional int32 start = 1;
+ optional int32 end = 2;
+
+ optional ExtensionRangeOptions options = 3;
+ }
+ repeated ExtensionRange extension_range = 5;
+
+ repeated OneofDescriptorProto oneof_decl = 8;
+
+ optional MessageOptions options = 7;
+
+ // Range of reserved tag numbers. Reserved tag numbers may not be used by
+ // fields or extension ranges in the same message. Reserved ranges may
+ // not overlap.
+ message ReservedRange {
+ optional int32 start = 1; // Inclusive.
+ optional int32 end = 2; // Exclusive.
+ }
+ repeated ReservedRange reserved_range = 9;
+ // Reserved field names, which may not be used by fields in the same message.
+ // A given name may only be reserved once.
+ repeated string reserved_name = 10;
+}
+
+message ExtensionRangeOptions {
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+// Describes a field within a message.
+message FieldDescriptorProto {
+ enum Type {
+ // 0 is reserved for errors.
+ // Order is weird for historical reasons.
+ TYPE_DOUBLE = 1;
+ TYPE_FLOAT = 2;
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
+ // negative values are likely.
+ TYPE_INT64 = 3;
+ TYPE_UINT64 = 4;
+ // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
+ // negative values are likely.
+ TYPE_INT32 = 5;
+ TYPE_FIXED64 = 6;
+ TYPE_FIXED32 = 7;
+ TYPE_BOOL = 8;
+ TYPE_STRING = 9;
+ // Tag-delimited aggregate.
+ // Group type is deprecated and not supported in proto3. However, Proto3
+ // implementations should still be able to parse the group wire format and
+ // treat group fields as unknown fields.
+ TYPE_GROUP = 10;
+ TYPE_MESSAGE = 11; // Length-delimited aggregate.
+
+ // New in version 2.
+ TYPE_BYTES = 12;
+ TYPE_UINT32 = 13;
+ TYPE_ENUM = 14;
+ TYPE_SFIXED32 = 15;
+ TYPE_SFIXED64 = 16;
+ TYPE_SINT32 = 17; // Uses ZigZag encoding.
+ TYPE_SINT64 = 18; // Uses ZigZag encoding.
+ };
+
+ enum Label {
+ // 0 is reserved for errors
+ LABEL_OPTIONAL = 1;
+ LABEL_REQUIRED = 2;
+ LABEL_REPEATED = 3;
+ };
+
+ optional string name = 1;
+ optional int32 number = 3;
+ optional Label label = 4;
+
+ // If type_name is set, this need not be set. If both this and type_name
+ // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
+ optional Type type = 5;
+
+ // For message and enum types, this is the name of the type. If the name
+ // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
+ // rules are used to find the type (i.e. first the nested types within this
+ // message are searched, then within the parent, on up to the root
+ // namespace).
+ optional string type_name = 6;
+
+ // For extensions, this is the name of the type being extended. It is
+ // resolved in the same manner as type_name.
+ optional string extendee = 2;
+
+ // For numeric types, contains the original text representation of the value.
+ // For booleans, "true" or "false".
+ // For strings, contains the default text contents (not escaped in any way).
+ // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
+ // TODO(kenton): Base-64 encode?
+ optional string default_value = 7;
+
+ // If set, gives the index of a oneof in the containing type's oneof_decl
+ // list. This field is a member of that oneof.
+ optional int32 oneof_index = 9;
+
+ // JSON name of this field. The value is set by protocol compiler. If the
+ // user has set a "json_name" option on this field, that option's value
+ // will be used. Otherwise, it's deduced from the field's name by converting
+ // it to camelCase.
+ optional string json_name = 10;
+
+ optional FieldOptions options = 8;
+}
+
+// Describes a oneof.
+message OneofDescriptorProto {
+ optional string name = 1;
+ optional OneofOptions options = 2;
+}
+
+// Describes an enum type.
+message EnumDescriptorProto {
+ optional string name = 1;
+
+ repeated EnumValueDescriptorProto value = 2;
+
+ optional EnumOptions options = 3;
+}
+
+// Describes a value within an enum.
+message EnumValueDescriptorProto {
+ optional string name = 1;
+ optional int32 number = 2;
+
+ optional EnumValueOptions options = 3;
+}
+
+// Describes a service.
+message ServiceDescriptorProto {
+ optional string name = 1;
+ repeated MethodDescriptorProto method = 2;
+
+ optional ServiceOptions options = 3;
+}
+
+// Describes a method of a service.
+message MethodDescriptorProto {
+ optional string name = 1;
+
+ // Input and output type names. These are resolved in the same way as
+ // FieldDescriptorProto.type_name, but must refer to a message type.
+ optional string input_type = 2;
+ optional string output_type = 3;
+
+ optional MethodOptions options = 4;
+
+ // Identifies if client streams multiple client messages
+ optional bool client_streaming = 5 [default=false];
+ // Identifies if server streams multiple server messages
+ optional bool server_streaming = 6 [default=false];
+}
+
+
+// ===================================================================
+// Options
+
+// Each of the definitions above may have "options" attached. These are
+// just annotations which may cause code to be generated slightly differently
+// or may contain hints for code that manipulates protocol messages.
+//
+// Clients may define custom options as extensions of the *Options messages.
+// These extensions may not yet be known at parsing time, so the parser cannot
+// store the values in them. Instead it stores them in a field in the *Options
+// message called uninterpreted_option. This field must have the same name
+// across all *Options messages. We then use this field to populate the
+// extensions when we build a descriptor, at which point all protos have been
+// parsed and so all extensions are known.
+//
+// Extension numbers for custom options may be chosen as follows:
+// * For options which will only be used within a single application or
+// organization, or for experimental options, use field numbers 50000
+// through 99999. It is up to you to ensure that you do not use the
+// same number for multiple options.
+// * For options which will be published and used publicly by multiple
+// independent entities, e-mail protobuf-global-extension-registry@google.com
+// to reserve extension numbers. Simply provide your project name (e.g.
+// Objective-C plugin) and your project website (if available) -- there's no
+// need to explain how you intend to use them. Usually you only need one
+// extension number. You can declare multiple options with only one extension
+// number by putting them in a sub-message. See the Custom Options section of
+// the docs for examples:
+// https://developers.google.com/protocol-buffers/docs/proto#options
+// If this turns out to be popular, a web service will be set up
+// to automatically assign option numbers.
+
+
+message FileOptions {
+
+ // Sets the Java package where classes generated from this .proto will be
+ // placed. By default, the proto package is used, but this is often
+ // inappropriate because proto packages do not normally start with backwards
+ // domain names.
+ optional string java_package = 1;
+
+
+ // If set, all the classes from the .proto file are wrapped in a single
+ // outer class with the given name. This applies to both Proto1
+ // (equivalent to the old "--one_java_file" option) and Proto2 (where
+ // a .proto always translates to a single class, but you may want to
+ // explicitly choose the class name).
+ optional string java_outer_classname = 8;
+
+ // If set true, then the Java code generator will generate a separate .java
+ // file for each top-level message, enum, and service defined in the .proto
+ // file. Thus, these types will *not* be nested inside the outer class
+ // named by java_outer_classname. However, the outer class will still be
+ // generated to contain the file's getDescriptor() method as well as any
+ // top-level extensions defined in the file.
+ optional bool java_multiple_files = 10 [default=false];
+
+ // This option does nothing.
+ optional bool java_generate_equals_and_hash = 20 [deprecated=true];
+
+ // If set true, then the Java2 code generator will generate code that
+ // throws an exception whenever an attempt is made to assign a non-UTF-8
+ // byte sequence to a string field.
+ // Message reflection will do the same.
+ // However, an extension field still accepts non-UTF-8 byte sequences.
+ // This option has no effect on when used with the lite runtime.
+ optional bool java_string_check_utf8 = 27 [default=false];
+
+
+ // Generated classes can be optimized for speed or code size.
+ enum OptimizeMode {
+ SPEED = 1; // Generate complete code for parsing, serialization,
+ // etc.
+ CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
+ LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
+ }
+ optional OptimizeMode optimize_for = 9 [default=SPEED];
+
+ // Sets the Go package where structs generated from this .proto will be
+ // placed. If omitted, the Go package will be derived from the following:
+ // - The basename of the package import path, if provided.
+ // - Otherwise, the package statement in the .proto file, if present.
+ // - Otherwise, the basename of the .proto file, without extension.
+ optional string go_package = 11;
+
+
+
+ // Should generic services be generated in each language? "Generic" services
+ // are not specific to any particular RPC system. They are generated by the
+ // main code generators in each language (without additional plugins).
+ // Generic services were the only kind of service generation supported by
+ // early versions of google.protobuf.
+ //
+ // Generic services are now considered deprecated in favor of using plugins
+ // that generate code specific to your particular RPC system. Therefore,
+ // these default to false. Old code which depends on generic services should
+ // explicitly set them to true.
+ optional bool cc_generic_services = 16 [default=false];
+ optional bool java_generic_services = 17 [default=false];
+ optional bool py_generic_services = 18 [default=false];
+ optional bool php_generic_services = 42 [default=false];
+
+ // Is this file deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for everything in the file, or it will be completely ignored; in the very
+ // least, this is a formalization for deprecating files.
+ optional bool deprecated = 23 [default=false];
+
+ // Enables the use of arenas for the proto messages in this file. This applies
+ // only to generated classes for C++.
+ optional bool cc_enable_arenas = 31 [default=false];
+
+
+ // Sets the objective c class prefix which is prepended to all objective c
+ // generated classes from this .proto. There is no default.
+ optional string objc_class_prefix = 36;
+
+ // Namespace for generated classes; defaults to the package.
+ optional string csharp_namespace = 37;
+
+ // By default Swift generators will take the proto package and CamelCase it
+ // replacing '.' with underscore and use that to prefix the types/symbols
+ // defined. When this options is provided, they will use this value instead
+ // to prefix the types/symbols defined.
+ optional string swift_prefix = 39;
+
+ // Sets the php class prefix which is prepended to all php generated classes
+ // from this .proto. Default is empty.
+ optional string php_class_prefix = 40;
+
+ // Use this option to change the namespace of php generated classes. Default
+ // is empty. When this option is empty, the package name will be used for
+ // determining the namespace.
+ optional string php_namespace = 41;
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+
+ reserved 38;
+}
+
+message MessageOptions {
+ // Set true to use the old proto1 MessageSet wire format for extensions.
+ // This is provided for backwards-compatibility with the MessageSet wire
+ // format. You should not use this for any other reason: It's less
+ // efficient, has fewer features, and is more complicated.
+ //
+ // The message must be defined exactly as follows:
+ // message Foo {
+ // option message_set_wire_format = true;
+ // extensions 4 to max;
+ // }
+ // Note that the message cannot have any defined fields; MessageSets only
+ // have extensions.
+ //
+ // All extensions of your type must be singular messages; e.g. they cannot
+ // be int32s, enums, or repeated messages.
+ //
+ // Because this is an option, the above two restrictions are not enforced by
+ // the protocol compiler.
+ optional bool message_set_wire_format = 1 [default=false];
+
+ // Disables the generation of the standard "descriptor()" accessor, which can
+ // conflict with a field of the same name. This is meant to make migration
+ // from proto1 easier; new code should avoid fields named "descriptor".
+ optional bool no_standard_descriptor_accessor = 2 [default=false];
+
+ // Is this message deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the message, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating messages.
+ optional bool deprecated = 3 [default=false];
+
+ // Whether the message is an automatically generated map entry type for the
+ // maps field.
+ //
+ // For maps fields:
+ // map map_field = 1;
+ // The parsed descriptor looks like:
+ // message MapFieldEntry {
+ // option map_entry = true;
+ // optional KeyType key = 1;
+ // optional ValueType value = 2;
+ // }
+ // repeated MapFieldEntry map_field = 1;
+ //
+ // Implementations may choose not to generate the map_entry=true message, but
+ // use a native map in the target language to hold the keys and values.
+ // The reflection APIs in such implementions still need to work as
+ // if the field is a repeated message field.
+ //
+ // NOTE: Do not set the option in .proto files. Always use the maps syntax
+ // instead. The option should only be implicitly set by the proto compiler
+ // parser.
+ optional bool map_entry = 7;
+
+ reserved 8; // javalite_serializable
+ reserved 9; // javanano_as_lite
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message FieldOptions {
+ // The ctype option instructs the C++ code generator to use a different
+ // representation of the field than it normally would. See the specific
+ // options below. This option is not yet implemented in the open source
+ // release -- sorry, we'll try to include it in a future version!
+ optional CType ctype = 1 [default = STRING];
+ enum CType {
+ // Default mode.
+ STRING = 0;
+
+ CORD = 1;
+
+ STRING_PIECE = 2;
+ }
+ // The packed option can be enabled for repeated primitive fields to enable
+ // a more efficient representation on the wire. Rather than repeatedly
+ // writing the tag and type for each element, the entire array is encoded as
+ // a single length-delimited blob. In proto3, only explicit setting it to
+ // false will avoid using packed encoding.
+ optional bool packed = 2;
+
+ // The jstype option determines the JavaScript type used for values of the
+ // field. The option is permitted only for 64 bit integral and fixed types
+ // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
+ // is represented as JavaScript string, which avoids loss of precision that
+ // can happen when a large value is converted to a floating point JavaScript.
+ // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
+ // use the JavaScript "number" type. The behavior of the default option
+ // JS_NORMAL is implementation dependent.
+ //
+ // This option is an enum to permit additional types to be added, e.g.
+ // goog.math.Integer.
+ optional JSType jstype = 6 [default = JS_NORMAL];
+ enum JSType {
+ // Use the default type.
+ JS_NORMAL = 0;
+
+ // Use JavaScript strings.
+ JS_STRING = 1;
+
+ // Use JavaScript numbers.
+ JS_NUMBER = 2;
+ }
+
+ // Should this field be parsed lazily? Lazy applies only to message-type
+ // fields. It means that when the outer message is initially parsed, the
+ // inner message's contents will not be parsed but instead stored in encoded
+ // form. The inner message will actually be parsed when it is first accessed.
+ //
+ // This is only a hint. Implementations are free to choose whether to use
+ // eager or lazy parsing regardless of the value of this option. However,
+ // setting this option true suggests that the protocol author believes that
+ // using lazy parsing on this field is worth the additional bookkeeping
+ // overhead typically needed to implement it.
+ //
+ // This option does not affect the public interface of any generated code;
+ // all method signatures remain the same. Furthermore, thread-safety of the
+ // interface is not affected by this option; const methods remain safe to
+ // call from multiple threads concurrently, while non-const methods continue
+ // to require exclusive access.
+ //
+ //
+ // Note that implementations may choose not to check required fields within
+ // a lazy sub-message. That is, calling IsInitialized() on the outer message
+ // may return true even if the inner message has missing required fields.
+ // This is necessary because otherwise the inner message would have to be
+ // parsed in order to perform the check, defeating the purpose of lazy
+ // parsing. An implementation which chooses not to check required fields
+ // must be consistent about it. That is, for any particular sub-message, the
+ // implementation must either *always* check its required fields, or *never*
+ // check its required fields, regardless of whether or not the message has
+ // been parsed.
+ optional bool lazy = 5 [default=false];
+
+ // Is this field deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for accessors, or it will be completely ignored; in the very least, this
+ // is a formalization for deprecating fields.
+ optional bool deprecated = 3 [default=false];
+
+ // For Google-internal migration only. Do not use.
+ optional bool weak = 10 [default=false];
+
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+
+ reserved 4; // removed jtype
+}
+
+message OneofOptions {
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message EnumOptions {
+
+ // Set this option to true to allow mapping different tag names to the same
+ // value.
+ optional bool allow_alias = 2;
+
+ // Is this enum deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the enum, or it will be completely ignored; in the very least, this
+ // is a formalization for deprecating enums.
+ optional bool deprecated = 3 [default=false];
+
+ reserved 5; // javanano_as_lite
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message EnumValueOptions {
+ // Is this enum value deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the enum value, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating enum values.
+ optional bool deprecated = 1 [default=false];
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message ServiceOptions {
+
+ // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
+ // framework. We apologize for hoarding these numbers to ourselves, but
+ // we were already using them long before we decided to release Protocol
+ // Buffers.
+
+ // Is this service deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the service, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating services.
+ optional bool deprecated = 33 [default=false];
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+message MethodOptions {
+
+ // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
+ // framework. We apologize for hoarding these numbers to ourselves, but
+ // we were already using them long before we decided to release Protocol
+ // Buffers.
+
+ // Is this method deprecated?
+ // Depending on the target platform, this can emit Deprecated annotations
+ // for the method, or it will be completely ignored; in the very least,
+ // this is a formalization for deprecating methods.
+ optional bool deprecated = 33 [default=false];
+
+ // Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
+ // or neither? HTTP based RPC implementation may choose GET verb for safe
+ // methods, and PUT verb for idempotent methods instead of the default POST.
+ enum IdempotencyLevel {
+ IDEMPOTENCY_UNKNOWN = 0;
+ NO_SIDE_EFFECTS = 1; // implies idempotent
+ IDEMPOTENT = 2; // idempotent, but may have side effects
+ }
+ optional IdempotencyLevel idempotency_level =
+ 34 [default=IDEMPOTENCY_UNKNOWN];
+
+ // The parser stores options it doesn't recognize here. See above.
+ repeated UninterpretedOption uninterpreted_option = 999;
+
+ // Clients can define custom options in extensions of this message. See above.
+ extensions 1000 to max;
+}
+
+
+// A message representing a option the parser does not recognize. This only
+// appears in options protos created by the compiler::Parser class.
+// DescriptorPool resolves these when building Descriptor objects. Therefore,
+// options protos in descriptor objects (e.g. returned by Descriptor::options(),
+// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
+// in them.
+message UninterpretedOption {
+ // The name of the uninterpreted option. Each string represents a segment in
+ // a dot-separated name. is_extension is true iff a segment represents an
+ // extension (denoted with parentheses in options specs in .proto files).
+ // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
+ // "foo.(bar.baz).qux".
+ message NamePart {
+ required string name_part = 1;
+ required bool is_extension = 2;
+ }
+ repeated NamePart name = 2;
+
+ // The value of the uninterpreted option, in whatever type the tokenizer
+ // identified it as during parsing. Exactly one of these should be set.
+ optional string identifier_value = 3;
+ optional uint64 positive_int_value = 4;
+ optional int64 negative_int_value = 5;
+ optional double double_value = 6;
+ optional bytes string_value = 7;
+ optional string aggregate_value = 8;
+}
+
+// ===================================================================
+// Optional source code info
+
+// Encapsulates information about the original source file from which a
+// FileDescriptorProto was generated.
+message SourceCodeInfo {
+ // A Location identifies a piece of source code in a .proto file which
+ // corresponds to a particular definition. This information is intended
+ // to be useful to IDEs, code indexers, documentation generators, and similar
+ // tools.
+ //
+ // For example, say we have a file like:
+ // message Foo {
+ // optional string foo = 1;
+ // }
+ // Let's look at just the field definition:
+ // optional string foo = 1;
+ // ^ ^^ ^^ ^ ^^^
+ // a bc de f ghi
+ // We have the following locations:
+ // span path represents
+ // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
+ // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
+ // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
+ // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
+ // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
+ //
+ // Notes:
+ // - A location may refer to a repeated field itself (i.e. not to any
+ // particular index within it). This is used whenever a set of elements are
+ // logically enclosed in a single code segment. For example, an entire
+ // extend block (possibly containing multiple extension definitions) will
+ // have an outer location whose path refers to the "extensions" repeated
+ // field without an index.
+ // - Multiple locations may have the same path. This happens when a single
+ // logical declaration is spread out across multiple places. The most
+ // obvious example is the "extend" block again -- there may be multiple
+ // extend blocks in the same scope, each of which will have the same path.
+ // - A location's span is not always a subset of its parent's span. For
+ // example, the "extendee" of an extension declaration appears at the
+ // beginning of the "extend" block and is shared by all extensions within
+ // the block.
+ // - Just because a location's span is a subset of some other location's span
+ // does not mean that it is a descendent. For example, a "group" defines
+ // both a type and a field in a single declaration. Thus, the locations
+ // corresponding to the type and field and their components will overlap.
+ // - Code which tries to interpret locations should probably be designed to
+ // ignore those that it doesn't understand, as more types of locations could
+ // be recorded in the future.
+ repeated Location location = 1;
+ message Location {
+ // Identifies which part of the FileDescriptorProto was defined at this
+ // location.
+ //
+ // Each element is a field number or an index. They form a path from
+ // the root FileDescriptorProto to the place where the definition. For
+ // example, this path:
+ // [ 4, 3, 2, 7, 1 ]
+ // refers to:
+ // file.message_type(3) // 4, 3
+ // .field(7) // 2, 7
+ // .name() // 1
+ // This is because FileDescriptorProto.message_type has field number 4:
+ // repeated DescriptorProto message_type = 4;
+ // and DescriptorProto.field has field number 2:
+ // repeated FieldDescriptorProto field = 2;
+ // and FieldDescriptorProto.name has field number 1:
+ // optional string name = 1;
+ //
+ // Thus, the above path gives the location of a field name. If we removed
+ // the last element:
+ // [ 4, 3, 2, 7 ]
+ // this path refers to the whole field declaration (from the beginning
+ // of the label to the terminating semicolon).
+ repeated int32 path = 1 [packed=true];
+
+ // Always has exactly three or four elements: start line, start column,
+ // end line (optional, otherwise assumed same as start line), end column.
+ // These are packed into a single field for efficiency. Note that line
+ // and column numbers are zero-based -- typically you will want to add
+ // 1 to each before displaying to a user.
+ repeated int32 span = 2 [packed=true];
+
+ // If this SourceCodeInfo represents a complete declaration, these are any
+ // comments appearing before and after the declaration which appear to be
+ // attached to the declaration.
+ //
+ // A series of line comments appearing on consecutive lines, with no other
+ // tokens appearing on those lines, will be treated as a single comment.
+ //
+ // leading_detached_comments will keep paragraphs of comments that appear
+ // before (but not connected to) the current element. Each paragraph,
+ // separated by empty lines, will be one comment element in the repeated
+ // field.
+ //
+ // Only the comment content is provided; comment markers (e.g. //) are
+ // stripped out. For block comments, leading whitespace and an asterisk
+ // will be stripped from the beginning of each line other than the first.
+ // Newlines are included in the output.
+ //
+ // Examples:
+ //
+ // optional int32 foo = 1; // Comment attached to foo.
+ // // Comment attached to bar.
+ // optional int32 bar = 2;
+ //
+ // optional string baz = 3;
+ // // Comment attached to baz.
+ // // Another line attached to baz.
+ //
+ // // Comment attached to qux.
+ // //
+ // // Another line attached to qux.
+ // optional double qux = 4;
+ //
+ // // Detached comment for corge. This is not leading or trailing comments
+ // // to qux or corge because there are blank lines separating it from
+ // // both.
+ //
+ // // Detached comment for corge paragraph 2.
+ //
+ // optional string corge = 5;
+ // /* Block comment attached
+ // * to corge. Leading asterisks
+ // * will be removed. */
+ // /* Block comment attached to
+ // * grault. */
+ // optional int32 grault = 6;
+ //
+ // // ignored detached comments.
+ optional string leading_comments = 3;
+ optional string trailing_comments = 4;
+ repeated string leading_detached_comments = 6;
+ }
+}
+
+// Describes the relationship between generated code and its original source
+// file. A GeneratedCodeInfo message is associated with only one generated
+// source file, but may contain references to different source .proto files.
+message GeneratedCodeInfo {
+ // An Annotation connects some span of text in generated code to an element
+ // of its generating .proto file.
+ repeated Annotation annotation = 1;
+ message Annotation {
+ // Identifies the element in the original source .proto file. This field
+ // is formatted the same as SourceCodeInfo.Location.path.
+ repeated int32 path = 1 [packed=true];
+
+ // Identifies the filesystem path to the original source .proto.
+ optional string source_file = 2;
+
+ // Identifies the starting offset in bytes in the generated code
+ // that relates to the identified object.
+ optional int32 begin = 3;
+
+ // Identifies the ending offset in bytes in the generated code that
+ // relates to the identified offset. The end offset should be one past
+ // the last relevant byte (so the length of the text = end - begin).
+ optional int32 end = 4;
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/doc.go b/vendor/github.com/golang/protobuf/protoc-gen-go/doc.go
new file mode 100644
index 0000000..0d6055d
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/doc.go
@@ -0,0 +1,51 @@
+// 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/Makefile b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/Makefile
new file mode 100644
index 0000000..b5715c3
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/Makefile
@@ -0,0 +1,40 @@
+# 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.
+
+include $(GOROOT)/src/Make.inc
+
+TARG=github.com/golang/protobuf/compiler/generator
+GOFILES=\
+ generator.go\
+
+DEPS=../descriptor ../plugin ../../proto
+
+include $(GOROOT)/src/Make.pkg
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
new file mode 100644
index 0000000..60d5246
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/generator.go
@@ -0,0 +1,2866 @@
+// 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"
+ "fmt"
+ "go/parser"
+ "go/printer"
+ "go/token"
+ "log"
+ "os"
+ "path"
+ "strconv"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/golang/protobuf/proto"
+
+ "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 = 2
+
+// 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)
+}
+
+// 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 *descriptor.FileDescriptorProto // File this object comes from.
+}
+
+// PackageName is name in the package clause in the generated file.
+func (c *common) PackageName() string { return uniquePackageOf(c.file) }
+
+func (c *common) File() *descriptor.FileDescriptorProto { return c.file }
+
+func fileIsProto3(file *descriptor.FileDescriptorProto) bool {
+ return file.GetSyntax() == "proto3"
+}
+
+func (c *common) proto3() bool { return fileIsProto3(c.file) }
+
+// 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, 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
+
+ index int // The index of this file in the list of files to generate code for
+
+ proto3 bool // whether to generate proto3 code for this file
+}
+
+// PackageName is the package name we'll use in the generated code to refer to this file.
+func (d *FileDescriptor) PackageName() string { return uniquePackageOf(d.FileDescriptorProto) }
+
+// 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 { return fmt.Sprintf("fileDescriptor%d", d.index) }
+
+// 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, pkg string, ok bool) {
+ pkg = d.GetOptions().GetGoPackage()
+ if pkg == "" {
+ return
+ }
+ ok = true
+ // The presence of a slash implies there's an import path.
+ slash := strings.LastIndex(pkg, "/")
+ if slash < 0 {
+ return
+ }
+ impPath, pkg = pkg, pkg[slash+1:]
+ // A semicolon-delimited suffix overrides the package name.
+ sc := strings.IndexByte(impPath, ';')
+ if sc < 0 {
+ return
+ }
+ impPath, pkg = impPath[:sc], impPath[sc+1:]
+ return
+}
+
+// goPackageName returns the Go package name to use in the
+// generated Go file. The result explicit reports whether the name
+// came from an option go_package statement. If explicit is false,
+// the name was derived from the protocol buffer's package statement
+// or the input file name.
+func (d *FileDescriptor) goPackageName() (name string, explicit bool) {
+ // Does the file have a "go_package" option?
+ if _, pkg, ok := d.goPackageOption(); ok {
+ return pkg, true
+ }
+
+ // Does the file have a package clause?
+ if pkg := d.GetPackage(); pkg != "" {
+ return pkg, false
+ }
+ // Use the file base name.
+ return baseName(d.GetName()), false
+}
+
+// goFileName returns the output name for the generated Go file.
+func (d *FileDescriptor) goFileName() string {
+ name := *d.Name
+ if ext := path.Ext(name); ext == ".proto" || ext == ".protodevel" {
+ name = name[:len(name)-len(ext)]
+ }
+ name += ".pb.go"
+
+ // 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(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, pkg string)
+}
+
+type messageSymbol struct {
+ sym string
+ hasExtensions, isMessageSet bool
+ hasOneof bool
+ getters []getterSymbol
+}
+
+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, pkg string) {
+ remoteSym := pkg + "." + ms.sym
+
+ g.P("type ", ms.sym, " ", remoteSym)
+ g.P("func (m *", ms.sym, ") Reset() { (*", remoteSym, ")(m).Reset() }")
+ g.P("func (m *", ms.sym, ") String() string { return (*", remoteSym, ")(m).String() }")
+ g.P("func (*", ms.sym, ") ProtoMessage() {}")
+ if ms.hasExtensions {
+ g.P("func (*", ms.sym, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange ",
+ "{ return (*", remoteSym, ")(nil).ExtensionRangeArray() }")
+ if ms.isMessageSet {
+ g.P("func (m *", ms.sym, ") Marshal() ([]byte, error) ",
+ "{ return (*", remoteSym, ")(m).Marshal() }")
+ g.P("func (m *", ms.sym, ") Unmarshal(buf []byte) error ",
+ "{ return (*", remoteSym, ")(m).Unmarshal(buf) }")
+ }
+ }
+ if ms.hasOneof {
+ // Oneofs and public imports do not mix well.
+ // We can make them work okay for the binary format,
+ // but they're going to break weirdly for text/JSON.
+ enc := "_" + ms.sym + "_OneofMarshaler"
+ dec := "_" + ms.sym + "_OneofUnmarshaler"
+ size := "_" + ms.sym + "_OneofSizer"
+ encSig := "(msg " + g.Pkg["proto"] + ".Message, b *" + g.Pkg["proto"] + ".Buffer) error"
+ decSig := "(msg " + g.Pkg["proto"] + ".Message, tag, wire int, b *" + g.Pkg["proto"] + ".Buffer) (bool, error)"
+ sizeSig := "(msg " + g.Pkg["proto"] + ".Message) int"
+ g.P("func (m *", ms.sym, ") XXX_OneofFuncs() (func", encSig, ", func", decSig, ", func", sizeSig, ", []interface{}) {")
+ g.P("return ", enc, ", ", dec, ", ", size, ", nil")
+ g.P("}")
+
+ g.P("func ", enc, encSig, " {")
+ g.P("m := msg.(*", ms.sym, ")")
+ g.P("m0 := (*", remoteSym, ")(m)")
+ g.P("enc, _, _, _ := m0.XXX_OneofFuncs()")
+ g.P("return enc(m0, b)")
+ g.P("}")
+
+ g.P("func ", dec, decSig, " {")
+ g.P("m := msg.(*", ms.sym, ")")
+ g.P("m0 := (*", remoteSym, ")(m)")
+ g.P("_, dec, _, _ := m0.XXX_OneofFuncs()")
+ g.P("return dec(m0, tag, wire, b)")
+ g.P("}")
+
+ g.P("func ", size, sizeSig, " {")
+ g.P("m := msg.(*", ms.sym, ")")
+ g.P("m0 := (*", remoteSym, ")(m)")
+ g.P("_, _, size, _ := m0.XXX_OneofFuncs()")
+ g.P("return size(m0)")
+ g.P("}")
+ }
+ for _, get := range ms.getters {
+
+ if get.typeName != "" {
+ g.RecordTypeUse(get.typeName)
+ }
+ typ := get.typ
+ val := "(*" + remoteSym + ")(m)." + get.name + "()"
+ if get.genType {
+ // typ will be "*pkg.T" (message/group) or "pkg.T" (enum)
+ // or "map[t]*pkg.T" (map to message/enum).
+ // The first two of those might have a "[]" prefix if it is repeated.
+ // Drop any package qualifier since we have hoisted the type into this package.
+ rep := strings.HasPrefix(typ, "[]")
+ if rep {
+ typ = typ[2:]
+ }
+ isMap := strings.HasPrefix(typ, "map[")
+ star := typ[0] == '*'
+ if !isMap { // map types handled lower down
+ typ = typ[strings.Index(typ, ".")+1:]
+ }
+ if star {
+ typ = "*" + typ
+ }
+ if rep {
+ // Go does not permit conversion between slice types where both
+ // element types are named. That means we need to generate a bit
+ // of code in this situation.
+ // typ is the element type.
+ // val is the expression to get the slice from the imported type.
+
+ ctyp := typ // conversion type expression; "Foo" or "(*Foo)"
+ if star {
+ ctyp = "(" + typ + ")"
+ }
+
+ g.P("func (m *", ms.sym, ") ", get.name, "() []", typ, " {")
+ g.In()
+ g.P("o := ", val)
+ g.P("if o == nil {")
+ g.In()
+ g.P("return nil")
+ g.Out()
+ g.P("}")
+ g.P("s := make([]", typ, ", len(o))")
+ g.P("for i, x := range o {")
+ g.In()
+ g.P("s[i] = ", ctyp, "(x)")
+ g.Out()
+ g.P("}")
+ g.P("return s")
+ g.Out()
+ g.P("}")
+ continue
+ }
+ if isMap {
+ // Split map[keyTyp]valTyp.
+ bra, ket := strings.Index(typ, "["), strings.Index(typ, "]")
+ keyTyp, valTyp := typ[bra+1:ket], typ[ket+1:]
+ // Drop any package qualifier.
+ // Only the value type may be foreign.
+ star := valTyp[0] == '*'
+ valTyp = valTyp[strings.Index(valTyp, ".")+1:]
+ if star {
+ valTyp = "*" + valTyp
+ }
+
+ typ := "map[" + keyTyp + "]" + valTyp
+ g.P("func (m *", ms.sym, ") ", get.name, "() ", typ, " {")
+ g.P("o := ", val)
+ g.P("if o == nil { return nil }")
+ g.P("s := make(", typ, ", len(o))")
+ g.P("for k, v := range o {")
+ g.P("s[k] = (", valTyp, ")(v)")
+ g.P("}")
+ g.P("return s")
+ g.P("}")
+ continue
+ }
+ // Convert imported type into the forwarding type.
+ val = "(" + typ + ")(" + val + ")"
+ }
+
+ g.P("func (m *", ms.sym, ") ", get.name, "() ", typ, " { return ", val, " }")
+ }
+
+}
+
+type enumSymbol struct {
+ name string
+ proto3 bool // Whether this came from a proto3 file.
+}
+
+func (es enumSymbol) GenerateAlias(g *Generator, pkg string) {
+ s := es.name
+ g.P("type ", s, " ", pkg, ".", s)
+ g.P("var ", s, "_name = ", pkg, ".", s, "_name")
+ g.P("var ", s, "_value = ", pkg, ".", s, "_value")
+ g.P("func (x ", s, ") String() string { return (", pkg, ".", s, ")(x).String() }")
+ if !es.proto3 {
+ g.P("func (x ", s, ") Enum() *", s, "{ return (*", s, ")((", pkg, ".", s, ")(x).Enum()) }")
+ g.P("func (x *", s, ") UnmarshalJSON(data []byte) error { return (*", pkg, ".", s, ")(x).UnmarshalJSON(data) }")
+ }
+}
+
+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, pkg string) {
+ v := 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 {
+ PackageName() string // The name we use in our output (a_b_c), possibly renamed for uniqueness.
+ TypeName() []string
+ File() *descriptor.FileDescriptorProto
+}
+
+// Each package name we generate must be unique. The package we're generating
+// gets its own name but every other package must have a unique name that does
+// not conflict in the code we generate. These names are chosen globally (although
+// they don't have to be, it simplifies things to do them globally).
+func uniquePackageOf(fd *descriptor.FileDescriptorProto) string {
+ s, ok := uniquePackageName[fd]
+ if !ok {
+ log.Fatal("internal error: no package name defined for " + fd.GetName())
+ }
+ return s
+}
+
+// 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
+
+ packageName string // What we're calling ourselves.
+ 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.
+ usedPackages map[string]bool // Names of packages used in current file.
+ typeNameToObject map[string]Object // Key is a fully-qualified name in input syntax.
+ init []string // Lines to emit in the init function.
+ indent string
+ writeOutput bool
+}
+
+// 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 "plugins":
+ pluginList = v
+ 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 {
+ pkg := obj.PackageName()
+ if pkg == g.packageName {
+ return ""
+ }
+ return pkg + "."
+}
+
+// For each input file, the unique package name to use, underscored.
+var uniquePackageName = make(map[*descriptor.FileDescriptorProto]string)
+
+// Package names already registered. Key is the name from the .proto file;
+// value is the name that appears in the generated code.
+var pkgNamesInUse = make(map[string]bool)
+
+// Create and remember a guaranteed unique package name for this file descriptor.
+// Pkg is the candidate name. If f is nil, it's a builtin package like "proto" and
+// has no file descriptor.
+func RegisterUniquePackageName(pkg string, f *FileDescriptor) string {
+ // Convert dots to underscores before finding a unique alias.
+ pkg = strings.Map(badToUnderscore, pkg)
+
+ for i, orig := 1, pkg; pkgNamesInUse[pkg]; i++ {
+ // It's a duplicate; must rename.
+ pkg = orig + strconv.Itoa(i)
+ }
+ // Install it.
+ pkgNamesInUse[pkg] = true
+ if f != nil {
+ uniquePackageName[f.FileDescriptorProto] = pkg
+ }
+ return pkg
+}
+
+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,
+}
+
+// defaultGoPackage returns the package name to use,
+// derived from the import path of the package we're building code for.
+func (g *Generator) defaultGoPackage() string {
+ p := g.PackageImportPath
+ if i := strings.LastIndex(p, "/"); i >= 0 {
+ p = p[i+1:]
+ }
+ if p == "" {
+ return ""
+ }
+
+ p = strings.Map(badToUnderscore, p)
+ // Identifier must not be keyword: insert _.
+ if isGoKeyword[p] {
+ p = "_" + p
+ }
+ // Identifier must not begin with digit: insert _.
+ if r, _ := utf8.DecodeRuneInString(p); unicode.IsDigit(r) {
+ p = "_" + p
+ }
+ return 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() {
+ // Register the name for this package. It will be the first name
+ // registered so is guaranteed to be unmodified.
+ pkg, explicit := g.genFiles[0].goPackageName()
+
+ // Check all files for an explicit go_package option.
+ for _, f := range g.genFiles {
+ thisPkg, thisExplicit := f.goPackageName()
+ if thisExplicit {
+ if !explicit {
+ // Let this file's go_package option serve for all input files.
+ pkg, explicit = thisPkg, true
+ } else if thisPkg != pkg {
+ g.Fail("inconsistent package names:", thisPkg, pkg)
+ }
+ }
+ }
+
+ // If we don't have an explicit go_package option but we have an
+ // import path, use that.
+ if !explicit {
+ p := g.defaultGoPackage()
+ if p != "" {
+ pkg, explicit = p, true
+ }
+ }
+
+ // If there was no go_package and no import path to use,
+ // double-check that all the inputs have the same implicit
+ // Go package name.
+ if !explicit {
+ for _, f := range g.genFiles {
+ thisPkg, _ := f.goPackageName()
+ if thisPkg != pkg {
+ g.Fail("inconsistent package names:", thisPkg, pkg)
+ }
+ }
+ }
+
+ g.packageName = RegisterUniquePackageName(pkg, g.genFiles[0])
+
+ // Register the support package names. They might collide with the
+ // name of a package we import.
+ g.Pkg = map[string]string{
+ "fmt": RegisterUniquePackageName("fmt", nil),
+ "math": RegisterUniquePackageName("math", nil),
+ "proto": RegisterUniquePackageName("proto", nil),
+ }
+
+AllFiles:
+ for _, f := range g.allFiles {
+ for _, genf := range g.genFiles {
+ if f == genf {
+ // In this package already.
+ uniquePackageName[f.FileDescriptorProto] = g.packageName
+ continue AllFiles
+ }
+ }
+ // The file is a dependency, so we want to ignore its go_package option
+ // because that is only relevant for its specific generated output.
+ pkg := f.GetPackage()
+ if pkg == "" {
+ pkg = baseName(*f.Name)
+ }
+ RegisterUniquePackageName(pkg, f)
+ }
+}
+
+// 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))
+ for _, f := range g.Request.ProtoFile {
+ // We must wrap the descriptors before we wrap the enums
+ descs := wrapDescriptors(f)
+ g.buildNestedDescriptors(descs)
+ enums := wrapEnumDescriptors(f, descs)
+ g.buildNestedEnums(descs, enums)
+ exts := wrapExtensions(f)
+ fd := &FileDescriptor{
+ FileDescriptorProto: f,
+ desc: descs,
+ enum: enums,
+ ext: exts,
+ exported: make(map[Object][]symbol),
+ proto3: fileIsProto3(f),
+ }
+ extractComments(fd)
+ g.allFiles = append(g.allFiles, fd)
+ g.allFilesByName[f.GetName()] = fd
+ }
+ for _, fd := range g.allFiles {
+ fd.imp = wrapImported(fd.FileDescriptorProto, 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)
+ }
+ fd.index = len(g.genFiles)
+ 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 *descriptor.FileDescriptorProto, 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 *descriptor.FileDescriptorProto) []*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 *descriptor.FileDescriptorProto, 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 *descriptor.FileDescriptorProto, 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 *descriptor.FileDescriptorProto, 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 *descriptor.FileDescriptorProto) []*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 *descriptor.FileDescriptorProto, 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)
+ }
+
+ // If the file of this object isn't a direct dependency of the current file,
+ // or in the current file, then this object has been publicly imported into
+ // a dependency of the current file.
+ // We should return the ImportedDescriptor object for it instead.
+ direct := *o.File().Name == *g.file.Name
+ if !direct {
+ for _, dep := range g.file.Dependency {
+ if *g.fileByName(dep).Name == *o.File().Name {
+ direct = true
+ break
+ }
+ }
+ }
+ if !direct {
+ found := false
+ Loop:
+ for _, dep := range g.file.Dependency {
+ df := g.fileByName(*g.fileByName(dep).Name)
+ for _, td := range df.imp {
+ if td.o == o {
+ // Found it!
+ o = td
+ found = true
+ break Loop
+ }
+ }
+ }
+ if !found {
+ log.Printf("protoc-gen-go: WARNING: failed finding publicly imported dependency for %v, used in %v", typeName, *g.file.Name)
+ }
+ }
+
+ return o
+}
+
+// P prints the arguments to the generated output. It handles strings and int32s, plus
+// handling indirections because they may be *string, etc.
+func (g *Generator) P(str ...interface{}) {
+ if !g.writeOutput {
+ return
+ }
+ g.WriteString(g.indent)
+ for _, v := range str {
+ switch s := v.(type) {
+ case string:
+ g.WriteString(s)
+ case *string:
+ g.WriteString(*s)
+ case bool:
+ fmt.Fprintf(g, "%t", s)
+ case *bool:
+ fmt.Fprintf(g, "%t", *s)
+ case int:
+ fmt.Fprintf(g, "%d", s)
+ case *int32:
+ fmt.Fprintf(g, "%d", *s)
+ case *int64:
+ fmt.Fprintf(g, "%d", *s)
+ case float64:
+ fmt.Fprintf(g, "%g", s)
+ case *float64:
+ fmt.Fprintf(g, "%g", *s)
+ default:
+ g.Fail(fmt.Sprintf("unknown type in printer: %T", 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.writeOutput = genFileMap[file]
+ g.generate(file)
+ if !g.writeOutput {
+ continue
+ }
+ g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
+ Name: proto.String(file.goFileName()),
+ Content: proto.String(g.String()),
+ })
+ }
+}
+
+// Run all the plugins associated with the file.
+func (g *Generator) runPlugins(file *FileDescriptor) {
+ for _, p := range plugins {
+ p.Generate(file)
+ }
+}
+
+// FileOf return the FileDescriptor for this FileDescriptorProto.
+func (g *Generator) FileOf(fd *descriptor.FileDescriptorProto) *FileDescriptor {
+ for _, file := range g.allFiles {
+ if file.FileDescriptorProto == fd {
+ return file
+ }
+ }
+ g.Fail("could not find file in table:", fd.GetName())
+ return nil
+}
+
+// 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 = g.FileOf(file.FileDescriptorProto)
+ g.usedPackages = make(map[string]bool)
+
+ if g.file.index == 0 {
+ // For one file in the package, assert version compatibility.
+ 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()
+
+ // Run the plugins before the imports so we know which imports are necessary.
+ g.runPlugins(file)
+
+ g.generateFileDescriptor(file)
+
+ // Generate header and imports last, though they appear first in the output.
+ rem := g.Buffer
+ g.Buffer = new(bytes.Buffer)
+ g.generateHeader()
+ g.generateImports()
+ if !g.writeOutput {
+ return
+ }
+ g.Write(rem.Bytes())
+
+ // Reformat generated code.
+ fset := token.NewFileSet()
+ raw := g.Bytes()
+ ast, err := parser.ParseFile(fset, "", g, 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(raw))
+ 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())
+ }
+ g.Reset()
+ err = (&printer.Config{Mode: printer.TabIndent | printer.UseSpaces, Tabwidth: 8}).Fprint(g, fset, ast)
+ if err != nil {
+ g.Fail("generated Go source code could not be reformatted:", err.Error())
+ }
+}
+
+// Generate the header, including package definition
+func (g *Generator) generateHeader() {
+ g.P("// Code generated by protoc-gen-go. DO NOT EDIT.")
+ g.P("// source: ", g.file.Name)
+ g.P()
+
+ name := g.file.PackageName()
+
+ if g.file.index == 0 {
+ // Generate package docs for the first file in the package.
+ g.P("/*")
+ g.P("Package ", name, " is a generated protocol buffer package.")
+ g.P()
+ if loc, ok := g.file.comments[strconv.Itoa(packagePath)]; ok {
+ // not using g.PrintComments because this is a /* */ comment block.
+ text := strings.TrimSuffix(loc.GetLeadingComments(), "\n")
+ for _, line := range strings.Split(text, "\n") {
+ line = strings.TrimPrefix(line, " ")
+ // ensure we don't escape from the block comment
+ line = strings.Replace(line, "*/", "* /", -1)
+ g.P(line)
+ }
+ g.P()
+ }
+ var topMsgs []string
+ g.P("It is generated from these files:")
+ for _, f := range g.genFiles {
+ g.P("\t", f.Name)
+ for _, msg := range f.desc {
+ if msg.parent != nil {
+ continue
+ }
+ topMsgs = append(topMsgs, CamelCaseSlice(msg.TypeName()))
+ }
+ }
+ g.P()
+ g.P("It has these top-level messages:")
+ for _, msg := range topMsgs {
+ g.P("\t", msg)
+ }
+ g.P("*/")
+ }
+
+ g.P("package ", name)
+ g.P()
+}
+
+// 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 loc, ok := g.file.comments[path]; ok {
+ text := strings.TrimSuffix(loc.GetLeadingComments(), "\n")
+ for _, line := range strings.Split(text, "\n") {
+ g.P("// ", strings.TrimPrefix(line, " "))
+ }
+ return true
+ }
+ return false
+}
+
+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() {
+ // 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.Pkg["proto"] + " " + strconv.Quote(g.ImportPrefix+"github.com/golang/protobuf/proto"))
+ g.P("import " + g.Pkg["fmt"] + ` "fmt"`)
+ g.P("import " + g.Pkg["math"] + ` "math"`)
+ for i, s := range g.file.Dependency {
+ fd := g.fileByName(s)
+ // Do not import our own package.
+ if fd.PackageName() == g.packageName {
+ continue
+ }
+ filename := fd.goFileName()
+ // By default, import path is the dirname of the Go filename.
+ importPath := path.Dir(filename)
+ if substitution, ok := g.ImportMap[s]; ok {
+ importPath = substitution
+ }
+ importPath = g.ImportPrefix + importPath
+ // Skip weak imports.
+ if g.weak(int32(i)) {
+ g.P("// skipping weak import ", fd.PackageName(), " ", strconv.Quote(importPath))
+ 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.
+ pname := fd.PackageName()
+ if _, ok := g.usedPackages[pname]; !ok {
+ pname = "_"
+ }
+ g.P("import ", pname, " ", strconv.Quote(importPath))
+ }
+ 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) {
+ // Don't generate public import symbols for files that we are generating
+ // code for, since those symbols will already be in this package.
+ // We can't simply avoid creating the ImportedDescriptor objects,
+ // because g.genFiles isn't populated at that stage.
+ tn := id.TypeName()
+ sn := tn[len(tn)-1]
+ df := g.FileOf(id.o.File())
+ filename := *df.Name
+ for _, fd := range g.genFiles {
+ if *fd.Name == filename {
+ g.P("// Ignoring public import of ", sn, " from ", filename)
+ g.P()
+ return
+ }
+ }
+ g.P("// ", sn, " from public import ", filename)
+ g.usedPackages[df.PackageName()] = true
+
+ for _, sym := range df.exported[id.o] {
+ sym.GenerateAlias(g, df.PackageName())
+ }
+
+ 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()
+
+ g.PrintComments(enum.path)
+ g.P("type ", ccTypeName, " int32")
+ g.file.addExport(enum, enumSymbol{ccTypeName, enum.proto3()})
+ g.P("const (")
+ g.In()
+ for i, e := range enum.Value {
+ g.PrintComments(fmt.Sprintf("%s,%d,%d", enum.path, enumValuePath, i))
+
+ name := ccPrefix + *e.Name
+ g.P(name, " ", ccTypeName, " = ", e.Number)
+ g.file.addExport(enum, constOrVarSymbol{name, "const", ccTypeName})
+ }
+ g.Out()
+ g.P(")")
+ g.P("var ", ccTypeName, "_name = map[int32]string{")
+ g.In()
+ 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.Out()
+ g.P("}")
+ g.P("var ", ccTypeName, "_value = map[string]int32{")
+ g.In()
+ for _, e := range enum.Value {
+ g.P(strconv.Quote(*e.Name), ": ", e.Number, ",")
+ }
+ g.Out()
+ g.P("}")
+
+ if !enum.proto3() {
+ g.P("func (x ", ccTypeName, ") Enum() *", ccTypeName, " {")
+ g.In()
+ g.P("p := new(", ccTypeName, ")")
+ g.P("*p = x")
+ g.P("return p")
+ g.Out()
+ g.P("}")
+ }
+
+ g.P("func (x ", ccTypeName, ") String() string {")
+ g.In()
+ g.P("return ", g.Pkg["proto"], ".EnumName(", ccTypeName, "_name, int32(x))")
+ g.Out()
+ g.P("}")
+
+ if !enum.proto3() {
+ g.P("func (x *", ccTypeName, ") UnmarshalJSON(data []byte) error {")
+ g.In()
+ g.P("value, err := ", g.Pkg["proto"], ".UnmarshalJSONEnum(", ccTypeName, `_value, data, "`, ccTypeName, `")`)
+ g.P("if err != nil {")
+ g.In()
+ g.P("return err")
+ g.Out()
+ g.P("}")
+ g.P("*x = ", ccTypeName, "(value)")
+ g.P("return nil")
+ g.Out()
+ 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) { return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "} }")
+ if enum.file.GetPackage() == "google.protobuf" && enum.GetName() == "NullValue" {
+ g.P("func (", ccTypeName, `) XXX_WellKnownType() string { return "`, enum.GetName(), `" }`)
+ }
+
+ g.P()
+}
+
+// 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)
+ }
+ defaultValue = ",def=" + defaultValue
+ }
+ enum := ""
+ if *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM {
+ // We avoid using obj.PackageName(), 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(); 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() {
+ // We only need the extra tag for []byte fields;
+ // no need to add noise for the others.
+ if *field.Type == descriptor.FieldDescriptorProto_TYPE_BYTES {
+ 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())
+}
+
+// TypeNameWithPackage is like TypeName, but always includes the package
+// name even if the object is in our own package.
+func (g *Generator) TypeNameWithPackage(obj Object) string {
+ return obj.PackageName() + 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 obj, ok := g.typeNameToObject[t]; ok {
+ // Call ObjectNamed to get the true object to record the use.
+ obj = g.ObjectNamed(t)
+ g.usedPackages[obj.PackageName()] = 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,
+}
+
+// Generate the type and default constant definitions for this Descriptor.
+func (g *Generator) generateMessage(message *Descriptor) {
+ // The full type name
+ typeName := message.TypeName()
+ // The full type name, CamelCased.
+ ccTypeName := CamelCaseSlice(typeName)
+
+ usedNames := make(map[string]bool)
+ for _, n := range methodNames {
+ usedNames[n] = true
+ }
+ fieldNames := make(map[*descriptor.FieldDescriptorProto]string)
+ fieldGetterNames := make(map[*descriptor.FieldDescriptorProto]string)
+ fieldTypes := make(map[*descriptor.FieldDescriptorProto]string)
+ mapFieldTypes := make(map[*descriptor.FieldDescriptorProto]string)
+
+ oneofFieldName := make(map[int32]string) // indexed by oneof_index field of FieldDescriptorProto
+ oneofDisc := make(map[int32]string) // name of discriminator method
+ oneofTypeName := make(map[*descriptor.FieldDescriptorProto]string) // without star
+ oneofInsertPoints := make(map[int32]int) // oneof_index => offset of g.Buffer
+
+ g.PrintComments(message.path)
+ g.P("type ", ccTypeName, " struct {")
+ g.In()
+
+ // 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
+ }
+ }
+
+ 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")
+
+ fieldNames[field] = fieldName
+ fieldGetterNames[field] = fieldGetterName
+
+ oneof := field.OneofIndex != nil
+ if oneof && oneofFieldName[*field.OneofIndex] == "" {
+ odp := message.OneofDecl[int(*field.OneofIndex)]
+ fname := allocNames(CamelCase(odp.GetName()))[0]
+
+ // This is the first field of a oneof we haven't seen before.
+ // Generate the union field.
+ com := g.PrintComments(fmt.Sprintf("%s,%d,%d", message.path, messageOneofPath, *field.OneofIndex))
+ if com {
+ g.P("//")
+ }
+ g.P("// Types that are valid to be assigned to ", fname, ":")
+ // Generate the rest of this comment later,
+ // when we've computed any disambiguation.
+ oneofInsertPoints[*field.OneofIndex] = g.Buffer.Len()
+
+ dname := "is" + ccTypeName + "_" + fname
+ oneofFieldName[*field.OneofIndex] = fname
+ oneofDisc[*field.OneofIndex] = dname
+ tag := `protobuf_oneof:"` + odp.GetName() + `"`
+ g.P(fname, " ", dname, " `", tag, "`")
+ }
+
+ 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)
+ }
+ }
+
+ fieldTypes[field] = typename
+
+ if oneof {
+ tname := ccTypeName + "_" + 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
+ }
+
+ oneofTypeName[field] = tname
+ continue
+ }
+
+ g.PrintComments(fmt.Sprintf("%s,%d,%d", message.path, messageFieldPath, i))
+ g.P(fieldName, "\t", typename, "\t`", tag, "`")
+ g.RecordTypeUse(field.GetTypeName())
+ }
+ if len(message.ExtensionRange) > 0 {
+ g.P(g.Pkg["proto"], ".XXX_InternalExtensions `json:\"-\"`")
+ }
+ if !message.proto3() {
+ g.P("XXX_unrecognized\t[]byte `json:\"-\"`")
+ }
+ g.Out()
+ g.P("}")
+
+ // Update g.Buffer to list valid oneof types.
+ // We do this down here, after we've disambiguated the oneof type names.
+ // We go in reverse order of insertion point to avoid invalidating offsets.
+ for oi := int32(len(message.OneofDecl)); oi >= 0; oi-- {
+ ip := oneofInsertPoints[oi]
+ all := g.Buffer.Bytes()
+ rem := all[ip:]
+ g.Buffer = bytes.NewBuffer(all[:ip:ip]) // set cap so we don't scribble on rem
+ for _, field := range message.Field {
+ if field.OneofIndex == nil || *field.OneofIndex != oi {
+ continue
+ }
+ g.P("//\t*", oneofTypeName[field])
+ }
+ g.Buffer.Write(rem)
+ }
+
+ // Reset, String and ProtoMessage methods.
+ g.P("func (m *", ccTypeName, ") Reset() { *m = ", ccTypeName, "{} }")
+ g.P("func (m *", ccTypeName, ") String() string { return ", g.Pkg["proto"], ".CompactTextString(m) }")
+ g.P("func (*", ccTypeName, ") ProtoMessage() {}")
+ var indexes []string
+ for m := message; m != nil; m = m.parent {
+ indexes = append([]string{strconv.Itoa(m.index)}, indexes...)
+ }
+ g.P("func (*", ccTypeName, ") Descriptor() ([]byte, []int) { return ", g.file.VarName(), ", []int{", strings.Join(indexes, ", "), "} }")
+ // TODO: Revisit the decision to use a XXX_WellKnownType method
+ // if we change proto.MessageName to work with multiple equivalents.
+ if message.file.GetPackage() == "google.protobuf" && wellKnownTypes[message.GetName()] {
+ g.P("func (*", ccTypeName, `) XXX_WellKnownType() string { return "`, message.GetName(), `" }`)
+ }
+
+ // Extension support methods
+ var hasExtensions, isMessageSet bool
+ if len(message.ExtensionRange) > 0 {
+ hasExtensions = true
+ // message_set_wire_format only makes sense when extensions are defined.
+ if opts := message.Options; opts != nil && opts.GetMessageSetWireFormat() {
+ isMessageSet = true
+ g.P()
+ g.P("func (m *", ccTypeName, ") Marshal() ([]byte, error) {")
+ g.In()
+ g.P("return ", g.Pkg["proto"], ".MarshalMessageSet(&m.XXX_InternalExtensions)")
+ g.Out()
+ g.P("}")
+ g.P("func (m *", ccTypeName, ") Unmarshal(buf []byte) error {")
+ g.In()
+ g.P("return ", g.Pkg["proto"], ".UnmarshalMessageSet(buf, &m.XXX_InternalExtensions)")
+ g.Out()
+ g.P("}")
+ g.P("func (m *", ccTypeName, ") MarshalJSON() ([]byte, error) {")
+ g.In()
+ g.P("return ", g.Pkg["proto"], ".MarshalMessageSetJSON(&m.XXX_InternalExtensions)")
+ g.Out()
+ g.P("}")
+ g.P("func (m *", ccTypeName, ") UnmarshalJSON(buf []byte) error {")
+ g.In()
+ g.P("return ", g.Pkg["proto"], ".UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions)")
+ g.Out()
+ g.P("}")
+ g.P("// ensure ", ccTypeName, " satisfies proto.Marshaler and proto.Unmarshaler")
+ g.P("var _ ", g.Pkg["proto"], ".Marshaler = (*", ccTypeName, ")(nil)")
+ g.P("var _ ", g.Pkg["proto"], ".Unmarshaler = (*", ccTypeName, ")(nil)")
+ }
+
+ g.P()
+ g.P("var extRange_", ccTypeName, " = []", g.Pkg["proto"], ".ExtensionRange{")
+ g.In()
+ for _, r := range message.ExtensionRange {
+ end := fmt.Sprint(*r.End - 1) // make range inclusive on both ends
+ g.P("{", r.Start, ", ", end, "},")
+ }
+ g.Out()
+ g.P("}")
+ g.P("func (*", ccTypeName, ") ExtensionRangeArray() []", g.Pkg["proto"], ".ExtensionRange {")
+ g.In()
+ g.P("return extRange_", ccTypeName)
+ g.Out()
+ g.P("}")
+ }
+
+ // Default constants
+ defNames := make(map[*descriptor.FieldDescriptorProto]string)
+ for _, field := range message.Field {
+ def := field.GetDefaultValue()
+ if def == "" {
+ continue
+ }
+ fieldname := "Default_" + ccTypeName + "_" + CamelCase(*field.Name)
+ defNames[field] = fieldname
+ typename, _ := g.GoType(message, field)
+ 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 *field.Type == descriptor.FieldDescriptorProto_TYPE_FLOAT {
+ def = "float32(" + def + ")"
+ }
+ kind = "var "
+ case *field.Type == descriptor.FieldDescriptorProto_TYPE_ENUM:
+ // Must be an enum. Need to construct the prefixed name.
+ 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 constant for %s", fieldname)
+ continue
+ }
+ def = g.DefaultPackageName(obj) + enum.prefix() + def
+ }
+ g.P(kind, fieldname, " ", typename, " = ", def)
+ g.file.addExport(message, constOrVarSymbol{fieldname, kind, ""})
+ }
+ g.P()
+
+ // Oneof per-field types, discriminants and getters.
+ //
+ // Generate unexported named types for the discriminant interfaces.
+ // We shouldn't have to do this, but there was (~19 Aug 2015) a compiler/linker bug
+ // that was triggered by using anonymous interfaces here.
+ // TODO: Revisit this and consider reverting back to anonymous interfaces.
+ for oi := range message.OneofDecl {
+ dname := oneofDisc[int32(oi)]
+ g.P("type ", dname, " interface { ", dname, "() }")
+ }
+ g.P()
+ for _, field := range message.Field {
+ if field.OneofIndex == nil {
+ continue
+ }
+ _, wiretype := g.GoType(message, field)
+ tag := "protobuf:" + g.goTag(message, field, wiretype)
+ g.P("type ", oneofTypeName[field], " struct{ ", fieldNames[field], " ", fieldTypes[field], " `", tag, "` }")
+ g.RecordTypeUse(field.GetTypeName())
+ }
+ g.P()
+ for _, field := range message.Field {
+ if field.OneofIndex == nil {
+ continue
+ }
+ g.P("func (*", oneofTypeName[field], ") ", oneofDisc[*field.OneofIndex], "() {}")
+ }
+ g.P()
+ for oi := range message.OneofDecl {
+ fname := oneofFieldName[int32(oi)]
+ g.P("func (m *", ccTypeName, ") Get", fname, "() ", oneofDisc[int32(oi)], " {")
+ g.P("if m != nil { return m.", fname, " }")
+ g.P("return nil")
+ g.P("}")
+ }
+ g.P()
+
+ // Field getters
+ var getters []getterSymbol
+ for _, field := range message.Field {
+ oneof := field.OneofIndex != nil
+
+ fname := fieldNames[field]
+ typename, _ := g.GoType(message, field)
+ if t, ok := mapFieldTypes[field]; ok {
+ typename = t
+ }
+ mname := fieldGetterNames[field]
+ star := ""
+ if needsStar(*field.Type) && typename[0] == '*' {
+ typename = typename[1:]
+ star = "*"
+ }
+
+ // Only export getter symbols for basic types,
+ // and for messages and enums in the same package.
+ // Groups are not exported.
+ // Foreign types can't be hoisted through a public import because
+ // the importer may not already be importing the defining .proto.
+ // As an example, imagine we have an import tree like this:
+ // A.proto -> B.proto -> C.proto
+ // If A publicly imports B, we need to generate the getters from B in A's output,
+ // but if one such getter returns something from C then we cannot do that
+ // because A is not importing C already.
+ var getter, genType bool
+ switch *field.Type {
+ case descriptor.FieldDescriptorProto_TYPE_GROUP:
+ getter = false
+ case descriptor.FieldDescriptorProto_TYPE_MESSAGE, descriptor.FieldDescriptorProto_TYPE_ENUM:
+ // Only export getter if its return type is in this package.
+ getter = g.ObjectNamed(field.GetTypeName()).PackageName() == message.PackageName()
+ genType = true
+ default:
+ getter = true
+ }
+ if getter {
+ getters = append(getters, getterSymbol{
+ name: mname,
+ typ: typename,
+ typeName: field.GetTypeName(),
+ genType: genType,
+ })
+ }
+
+ g.P("func (m *", ccTypeName, ") "+mname+"() "+typename+" {")
+ g.In()
+ def, hasDef := defNames[field]
+ typeDefaultIsNil := false // whether this field type's default value is a literal nil unless specified
+ switch *field.Type {
+ case descriptor.FieldDescriptorProto_TYPE_BYTES:
+ typeDefaultIsNil = !hasDef
+ case descriptor.FieldDescriptorProto_TYPE_GROUP, descriptor.FieldDescriptorProto_TYPE_MESSAGE:
+ typeDefaultIsNil = true
+ }
+ if isRepeated(field) {
+ typeDefaultIsNil = true
+ }
+ if typeDefaultIsNil && !oneof {
+ // A bytes field with no explicit default needs less generated code,
+ // as does a message or group field, or a repeated field.
+ g.P("if m != nil {")
+ g.In()
+ g.P("return m." + fname)
+ g.Out()
+ g.P("}")
+ g.P("return nil")
+ g.Out()
+ g.P("}")
+ g.P()
+ continue
+ }
+ if !oneof {
+ if message.proto3() {
+ g.P("if m != nil {")
+ } else {
+ g.P("if m != nil && m." + fname + " != nil {")
+ }
+ g.In()
+ g.P("return " + star + "m." + fname)
+ g.Out()
+ g.P("}")
+ } else {
+ uname := oneofFieldName[*field.OneofIndex]
+ tname := oneofTypeName[field]
+ g.P("if x, ok := m.Get", uname, "().(*", tname, "); ok {")
+ g.P("return x.", fname)
+ g.P("}")
+ }
+ if hasDef {
+ if *field.Type != descriptor.FieldDescriptorProto_TYPE_BYTES {
+ g.P("return " + def)
+ } else {
+ // The default is a []byte var.
+ // Make a copy when returning it to be safe.
+ g.P("return append([]byte(nil), ", def, "...)")
+ }
+ } else {
+ switch *field.Type {
+ case descriptor.FieldDescriptorProto_TYPE_BOOL:
+ g.P("return false")
+ case descriptor.FieldDescriptorProto_TYPE_STRING:
+ g.P(`return ""`)
+ case descriptor.FieldDescriptorProto_TYPE_GROUP,
+ descriptor.FieldDescriptorProto_TYPE_MESSAGE,
+ descriptor.FieldDescriptorProto_TYPE_BYTES:
+ // This is only possible for oneof fields.
+ g.P("return nil")
+ case descriptor.FieldDescriptorProto_TYPE_ENUM:
+ // The default default for an enum is the first value in the enum,
+ // not zero.
+ 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())
+ continue
+ }
+ if len(enum.Value) == 0 {
+ g.P("return 0 // empty enum")
+ } else {
+ first := enum.Value[0].GetName()
+ g.P("return ", g.DefaultPackageName(obj)+enum.prefix()+first)
+ }
+ default:
+ g.P("return 0")
+ }
+ }
+ g.Out()
+ g.P("}")
+ g.P()
+ }
+
+ if !message.group {
+ ms := &messageSymbol{
+ sym: ccTypeName,
+ hasExtensions: hasExtensions,
+ isMessageSet: isMessageSet,
+ hasOneof: len(message.OneofDecl) > 0,
+ getters: getters,
+ }
+ g.file.addExport(message, ms)
+ }
+
+ // Oneof functions
+ if len(message.OneofDecl) > 0 {
+ fieldWire := make(map[*descriptor.FieldDescriptorProto]string)
+
+ // method
+ enc := "_" + ccTypeName + "_OneofMarshaler"
+ dec := "_" + ccTypeName + "_OneofUnmarshaler"
+ size := "_" + ccTypeName + "_OneofSizer"
+ encSig := "(msg " + g.Pkg["proto"] + ".Message, b *" + g.Pkg["proto"] + ".Buffer) error"
+ decSig := "(msg " + g.Pkg["proto"] + ".Message, tag, wire int, b *" + g.Pkg["proto"] + ".Buffer) (bool, error)"
+ sizeSig := "(msg " + g.Pkg["proto"] + ".Message) (n int)"
+
+ g.P("// XXX_OneofFuncs is for the internal use of the proto package.")
+ g.P("func (*", ccTypeName, ") XXX_OneofFuncs() (func", encSig, ", func", decSig, ", func", sizeSig, ", []interface{}) {")
+ g.P("return ", enc, ", ", dec, ", ", size, ", []interface{}{")
+ for _, field := range message.Field {
+ if field.OneofIndex == nil {
+ continue
+ }
+ g.P("(*", oneofTypeName[field], ")(nil),")
+ }
+ g.P("}")
+ g.P("}")
+ g.P()
+
+ // marshaler
+ g.P("func ", enc, encSig, " {")
+ g.P("m := msg.(*", ccTypeName, ")")
+ for oi, odp := range message.OneofDecl {
+ g.P("// ", odp.GetName())
+ fname := oneofFieldName[int32(oi)]
+ g.P("switch x := m.", fname, ".(type) {")
+ for _, field := range message.Field {
+ if field.OneofIndex == nil || int(*field.OneofIndex) != oi {
+ continue
+ }
+ g.P("case *", oneofTypeName[field], ":")
+ var wire, pre, post string
+ val := "x." + fieldNames[field] // overridden for TYPE_BOOL
+ canFail := false // only TYPE_MESSAGE and TYPE_GROUP can fail
+ switch *field.Type {
+ case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
+ wire = "WireFixed64"
+ pre = "b.EncodeFixed64(" + g.Pkg["math"] + ".Float64bits("
+ post = "))"
+ case descriptor.FieldDescriptorProto_TYPE_FLOAT:
+ wire = "WireFixed32"
+ pre = "b.EncodeFixed32(uint64(" + g.Pkg["math"] + ".Float32bits("
+ post = ")))"
+ case descriptor.FieldDescriptorProto_TYPE_INT64,
+ descriptor.FieldDescriptorProto_TYPE_UINT64:
+ wire = "WireVarint"
+ pre, post = "b.EncodeVarint(uint64(", "))"
+ case descriptor.FieldDescriptorProto_TYPE_INT32,
+ descriptor.FieldDescriptorProto_TYPE_UINT32,
+ descriptor.FieldDescriptorProto_TYPE_ENUM:
+ wire = "WireVarint"
+ pre, post = "b.EncodeVarint(uint64(", "))"
+ case descriptor.FieldDescriptorProto_TYPE_FIXED64,
+ descriptor.FieldDescriptorProto_TYPE_SFIXED64:
+ wire = "WireFixed64"
+ pre, post = "b.EncodeFixed64(uint64(", "))"
+ case descriptor.FieldDescriptorProto_TYPE_FIXED32,
+ descriptor.FieldDescriptorProto_TYPE_SFIXED32:
+ wire = "WireFixed32"
+ pre, post = "b.EncodeFixed32(uint64(", "))"
+ case descriptor.FieldDescriptorProto_TYPE_BOOL:
+ // bool needs special handling.
+ g.P("t := uint64(0)")
+ g.P("if ", val, " { t = 1 }")
+ val = "t"
+ wire = "WireVarint"
+ pre, post = "b.EncodeVarint(", ")"
+ case descriptor.FieldDescriptorProto_TYPE_STRING:
+ wire = "WireBytes"
+ pre, post = "b.EncodeStringBytes(", ")"
+ case descriptor.FieldDescriptorProto_TYPE_GROUP:
+ wire = "WireStartGroup"
+ pre, post = "b.Marshal(", ")"
+ canFail = true
+ case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
+ wire = "WireBytes"
+ pre, post = "b.EncodeMessage(", ")"
+ canFail = true
+ case descriptor.FieldDescriptorProto_TYPE_BYTES:
+ wire = "WireBytes"
+ pre, post = "b.EncodeRawBytes(", ")"
+ case descriptor.FieldDescriptorProto_TYPE_SINT32:
+ wire = "WireVarint"
+ pre, post = "b.EncodeZigzag32(uint64(", "))"
+ case descriptor.FieldDescriptorProto_TYPE_SINT64:
+ wire = "WireVarint"
+ pre, post = "b.EncodeZigzag64(uint64(", "))"
+ default:
+ g.Fail("unhandled oneof field type ", field.Type.String())
+ }
+ fieldWire[field] = wire
+ g.P("b.EncodeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".", wire, ")")
+ if !canFail {
+ g.P(pre, val, post)
+ } else {
+ g.P("if err := ", pre, val, post, "; err != nil {")
+ g.P("return err")
+ g.P("}")
+ }
+ if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP {
+ g.P("b.EncodeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".WireEndGroup)")
+ }
+ }
+ g.P("case nil:")
+ g.P("default: return ", g.Pkg["fmt"], `.Errorf("`, ccTypeName, ".", fname, ` has unexpected type %T", x)`)
+ g.P("}")
+ }
+ g.P("return nil")
+ g.P("}")
+ g.P()
+
+ // unmarshaler
+ g.P("func ", dec, decSig, " {")
+ g.P("m := msg.(*", ccTypeName, ")")
+ g.P("switch tag {")
+ for _, field := range message.Field {
+ if field.OneofIndex == nil {
+ continue
+ }
+ odp := message.OneofDecl[int(*field.OneofIndex)]
+ g.P("case ", field.Number, ": // ", odp.GetName(), ".", *field.Name)
+ g.P("if wire != ", g.Pkg["proto"], ".", fieldWire[field], " {")
+ g.P("return true, ", g.Pkg["proto"], ".ErrInternalBadWireType")
+ g.P("}")
+ lhs := "x, err" // overridden for TYPE_MESSAGE and TYPE_GROUP
+ var dec, cast, cast2 string
+ switch *field.Type {
+ case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
+ dec, cast = "b.DecodeFixed64()", g.Pkg["math"]+".Float64frombits"
+ case descriptor.FieldDescriptorProto_TYPE_FLOAT:
+ dec, cast, cast2 = "b.DecodeFixed32()", "uint32", g.Pkg["math"]+".Float32frombits"
+ case descriptor.FieldDescriptorProto_TYPE_INT64:
+ dec, cast = "b.DecodeVarint()", "int64"
+ case descriptor.FieldDescriptorProto_TYPE_UINT64:
+ dec = "b.DecodeVarint()"
+ case descriptor.FieldDescriptorProto_TYPE_INT32:
+ dec, cast = "b.DecodeVarint()", "int32"
+ case descriptor.FieldDescriptorProto_TYPE_FIXED64:
+ dec = "b.DecodeFixed64()"
+ case descriptor.FieldDescriptorProto_TYPE_FIXED32:
+ dec, cast = "b.DecodeFixed32()", "uint32"
+ case descriptor.FieldDescriptorProto_TYPE_BOOL:
+ dec = "b.DecodeVarint()"
+ // handled specially below
+ case descriptor.FieldDescriptorProto_TYPE_STRING:
+ dec = "b.DecodeStringBytes()"
+ case descriptor.FieldDescriptorProto_TYPE_GROUP:
+ g.P("msg := new(", fieldTypes[field][1:], ")") // drop star
+ lhs = "err"
+ dec = "b.DecodeGroup(msg)"
+ // handled specially below
+ case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
+ g.P("msg := new(", fieldTypes[field][1:], ")") // drop star
+ lhs = "err"
+ dec = "b.DecodeMessage(msg)"
+ // handled specially below
+ case descriptor.FieldDescriptorProto_TYPE_BYTES:
+ dec = "b.DecodeRawBytes(true)"
+ case descriptor.FieldDescriptorProto_TYPE_UINT32:
+ dec, cast = "b.DecodeVarint()", "uint32"
+ case descriptor.FieldDescriptorProto_TYPE_ENUM:
+ dec, cast = "b.DecodeVarint()", fieldTypes[field]
+ case descriptor.FieldDescriptorProto_TYPE_SFIXED32:
+ dec, cast = "b.DecodeFixed32()", "int32"
+ case descriptor.FieldDescriptorProto_TYPE_SFIXED64:
+ dec, cast = "b.DecodeFixed64()", "int64"
+ case descriptor.FieldDescriptorProto_TYPE_SINT32:
+ dec, cast = "b.DecodeZigzag32()", "int32"
+ case descriptor.FieldDescriptorProto_TYPE_SINT64:
+ dec, cast = "b.DecodeZigzag64()", "int64"
+ default:
+ g.Fail("unhandled oneof field type ", field.Type.String())
+ }
+ g.P(lhs, " := ", dec)
+ val := "x"
+ if cast != "" {
+ val = cast + "(" + val + ")"
+ }
+ if cast2 != "" {
+ val = cast2 + "(" + val + ")"
+ }
+ switch *field.Type {
+ case descriptor.FieldDescriptorProto_TYPE_BOOL:
+ val += " != 0"
+ case descriptor.FieldDescriptorProto_TYPE_GROUP,
+ descriptor.FieldDescriptorProto_TYPE_MESSAGE:
+ val = "msg"
+ }
+ g.P("m.", oneofFieldName[*field.OneofIndex], " = &", oneofTypeName[field], "{", val, "}")
+ g.P("return true, err")
+ }
+ g.P("default: return false, nil")
+ g.P("}")
+ g.P("}")
+ g.P()
+
+ // sizer
+ g.P("func ", size, sizeSig, " {")
+ g.P("m := msg.(*", ccTypeName, ")")
+ for oi, odp := range message.OneofDecl {
+ g.P("// ", odp.GetName())
+ fname := oneofFieldName[int32(oi)]
+ g.P("switch x := m.", fname, ".(type) {")
+ for _, field := range message.Field {
+ if field.OneofIndex == nil || int(*field.OneofIndex) != oi {
+ continue
+ }
+ g.P("case *", oneofTypeName[field], ":")
+ val := "x." + fieldNames[field]
+ var wire, varint, fixed string
+ switch *field.Type {
+ case descriptor.FieldDescriptorProto_TYPE_DOUBLE:
+ wire = "WireFixed64"
+ fixed = "8"
+ case descriptor.FieldDescriptorProto_TYPE_FLOAT:
+ wire = "WireFixed32"
+ fixed = "4"
+ case descriptor.FieldDescriptorProto_TYPE_INT64,
+ descriptor.FieldDescriptorProto_TYPE_UINT64,
+ descriptor.FieldDescriptorProto_TYPE_INT32,
+ descriptor.FieldDescriptorProto_TYPE_UINT32,
+ descriptor.FieldDescriptorProto_TYPE_ENUM:
+ wire = "WireVarint"
+ varint = val
+ case descriptor.FieldDescriptorProto_TYPE_FIXED64,
+ descriptor.FieldDescriptorProto_TYPE_SFIXED64:
+ wire = "WireFixed64"
+ fixed = "8"
+ case descriptor.FieldDescriptorProto_TYPE_FIXED32,
+ descriptor.FieldDescriptorProto_TYPE_SFIXED32:
+ wire = "WireFixed32"
+ fixed = "4"
+ case descriptor.FieldDescriptorProto_TYPE_BOOL:
+ wire = "WireVarint"
+ fixed = "1"
+ case descriptor.FieldDescriptorProto_TYPE_STRING:
+ wire = "WireBytes"
+ fixed = "len(" + val + ")"
+ varint = fixed
+ case descriptor.FieldDescriptorProto_TYPE_GROUP:
+ wire = "WireStartGroup"
+ fixed = g.Pkg["proto"] + ".Size(" + val + ")"
+ case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
+ wire = "WireBytes"
+ g.P("s := ", g.Pkg["proto"], ".Size(", val, ")")
+ fixed = "s"
+ varint = fixed
+ case descriptor.FieldDescriptorProto_TYPE_BYTES:
+ wire = "WireBytes"
+ fixed = "len(" + val + ")"
+ varint = fixed
+ case descriptor.FieldDescriptorProto_TYPE_SINT32:
+ wire = "WireVarint"
+ varint = "(uint32(" + val + ") << 1) ^ uint32((int32(" + val + ") >> 31))"
+ case descriptor.FieldDescriptorProto_TYPE_SINT64:
+ wire = "WireVarint"
+ varint = "uint64(" + val + " << 1) ^ uint64((int64(" + val + ") >> 63))"
+ default:
+ g.Fail("unhandled oneof field type ", field.Type.String())
+ }
+ g.P("n += ", g.Pkg["proto"], ".SizeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".", wire, ")")
+ if varint != "" {
+ g.P("n += ", g.Pkg["proto"], ".SizeVarint(uint64(", varint, "))")
+ }
+ if fixed != "" {
+ g.P("n += ", fixed)
+ }
+ if *field.Type == descriptor.FieldDescriptorProto_TYPE_GROUP {
+ g.P("n += ", g.Pkg["proto"], ".SizeVarint(", field.Number, "<<3|", g.Pkg["proto"], ".WireEndGroup)")
+ }
+ }
+ g.P("case nil:")
+ g.P("default:")
+ g.P("panic(", g.Pkg["fmt"], ".Sprintf(\"proto: unexpected type %T in oneof\", x))")
+ g.P("}")
+ }
+ g.P("return n")
+ g.P("}")
+ g.P()
+ }
+
+ 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"], ccTypeName, fullName)
+}
+
+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.
+ mset := false
+ if extendedType == "*proto2_bridge.MessageSet" && typeName[len(typeName)-1] == "message_set_extension" {
+ typeName = typeName[:len(typeName)-1]
+ mset = true
+ }
+
+ // 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.In()
+ 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.Out()
+ g.P("}")
+ g.P()
+
+ if mset {
+ // Generate a bit more code to register with message_set.go.
+ g.addInitf("%s.RegisterMessageSetType((%s)(nil), %d, %q)", g.Pkg["proto"], fieldType, *field.Number, extName)
+ }
+
+ g.file.addExport(ext, constOrVarSymbol{ccTypeName, "var", ""})
+}
+
+func (g *Generator) generateInitFunction() {
+ for _, enum := range g.file.enum {
+ g.generateEnumRegistration(enum)
+ }
+ for _, d := range g.file.desc {
+ for _, ext := range d.ext {
+ g.generateExtensionRegistration(ext)
+ }
+ }
+ for _, ext := range g.file.ext {
+ g.generateExtensionRegistration(ext)
+ }
+ if len(g.init) == 0 {
+ return
+ }
+ g.P("func init() {")
+ g.In()
+ for _, l := range g.init {
+ g.P(l)
+ }
+ g.Out()
+ 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.In()
+ 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.Out()
+ 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)
+}
+
+func (g *Generator) generateExtensionRegistration(ext *ExtensionDescriptor) {
+ g.addInitf("%s.RegisterExtension(%s)", g.Pkg["proto"], ext.DescName())
+}
+
+// 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
+)
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/generator/name_test.go b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/name_test.go
new file mode 100644
index 0000000..76808f3
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/generator/name_test.go
@@ -0,0 +1,114 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2013 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 generator
+
+import (
+ "testing"
+
+ "github.com/golang/protobuf/protoc-gen-go/descriptor"
+)
+
+func TestCamelCase(t *testing.T) {
+ tests := []struct {
+ in, want string
+ }{
+ {"one", "One"},
+ {"one_two", "OneTwo"},
+ {"_my_field_name_2", "XMyFieldName_2"},
+ {"Something_Capped", "Something_Capped"},
+ {"my_Name", "My_Name"},
+ {"OneTwo", "OneTwo"},
+ {"_", "X"},
+ {"_a_", "XA_"},
+ }
+ for _, tc := range tests {
+ if got := CamelCase(tc.in); got != tc.want {
+ t.Errorf("CamelCase(%q) = %q, want %q", tc.in, got, tc.want)
+ }
+ }
+}
+
+func TestGoPackageOption(t *testing.T) {
+ tests := []struct {
+ in string
+ impPath, pkg string
+ ok bool
+ }{
+ {"", "", "", false},
+ {"foo", "", "foo", true},
+ {"github.com/golang/bar", "github.com/golang/bar", "bar", true},
+ {"github.com/golang/bar;baz", "github.com/golang/bar", "baz", true},
+ }
+ for _, tc := range tests {
+ d := &FileDescriptor{
+ FileDescriptorProto: &descriptor.FileDescriptorProto{
+ Options: &descriptor.FileOptions{
+ GoPackage: &tc.in,
+ },
+ },
+ }
+ impPath, pkg, ok := d.goPackageOption()
+ if impPath != tc.impPath || pkg != tc.pkg || ok != tc.ok {
+ t.Errorf("go_package = %q => (%q, %q, %t), want (%q, %q, %t)", tc.in,
+ impPath, pkg, ok, tc.impPath, tc.pkg, tc.ok)
+ }
+ }
+}
+
+func TestUnescape(t *testing.T) {
+ tests := []struct {
+ in string
+ out string
+ }{
+ // successful cases, including all kinds of escapes
+ {"", ""},
+ {"foo bar baz frob nitz", "foo bar baz frob nitz"},
+ {`\000\001\002\003\004\005\006\007`, string([]byte{0, 1, 2, 3, 4, 5, 6, 7})},
+ {`\a\b\f\n\r\t\v\\\?\'\"`, string([]byte{'\a', '\b', '\f', '\n', '\r', '\t', '\v', '\\', '?', '\'', '"'})},
+ {`\x10\x20\x30\x40\x50\x60\x70\x80`, string([]byte{16, 32, 48, 64, 80, 96, 112, 128})},
+ // variable length octal escapes
+ {`\0\018\222\377\3\04\005\6\07`, string([]byte{0, 1, '8', 0222, 255, 3, 4, 5, 6, 7})},
+ // malformed escape sequences left as is
+ {"foo \\g bar", "foo \\g bar"},
+ {"foo \\xg0 bar", "foo \\xg0 bar"},
+ {"\\", "\\"},
+ {"\\x", "\\x"},
+ {"\\xf", "\\xf"},
+ {"\\777", "\\777"}, // overflows byte
+ }
+ for _, tc := range tests {
+ s := unescape(tc.in)
+ if s != tc.out {
+ t.Errorf("doUnescape(%q) = %q; should have been %q", tc.in, s, tc.out)
+ }
+ }
+}
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
new file mode 100644
index 0000000..2660e47
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/grpc/grpc.go
@@ -0,0 +1,463 @@
+// 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"
+ "path"
+ "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 = "golang.org/x/net/context"
+ grpcPkgPath = "google.golang.org/grpc"
+)
+
+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
+ contextPkg = generator.RegisterUniquePackageName("context", nil)
+ grpcPkg = generator.RegisterUniquePackageName("grpc", nil)
+}
+
+// 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
+ }
+
+ 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) {
+ if len(file.FileDescriptorProto.Service) == 0 {
+ return
+ }
+ g.P("import (")
+ g.P(contextPkg, " ", strconv.Quote(path.Join(g.gen.ImportPrefix, contextPkgPath)))
+ g.P(grpcPkg, " ", strconv.Quote(path.Join(g.gen.ImportPrefix, grpcPkgPath)))
+ g.P(")")
+ g.P()
+}
+
+// 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:] }
+
+// 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)
+
+ g.P()
+ g.P("// Client API for ", servName, " service")
+ g.P()
+
+ // Client interface.
+ 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.
+ 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)
+ }
+
+ g.P("// Server API for ", servName, " service")
+ g.P()
+
+ // Server interface.
+ serverType := servName + "Server"
+ 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 registration.
+ 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()
+}
+
+// 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())
+
+ 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 := ", grpcPkg, `.Invoke(ctx, "`, sname, `", in, out, c.cc, 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 := ", grpcPkg, ".NewClientStream(ctx, ", descExpr, `, c.cc, "`, 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()
+ }
+}
+
+// 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
new file mode 100644
index 0000000..532a550
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/link_grpc.go
@@ -0,0 +1,34 @@
+// 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
new file mode 100644
index 0000000..8e2486d
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/main.go
@@ -0,0 +1,98 @@
+// 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/Makefile b/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/Makefile
new file mode 100644
index 0000000..bc0463d
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/Makefile
@@ -0,0 +1,45 @@
+# 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.
+
+# Not stored here, but plugin.proto is in https://github.com/google/protobuf/
+# at src/google/protobuf/compiler/plugin.proto
+# Also we need to fix an import.
+regenerate:
+ @echo WARNING! THIS RULE IS PROBABLY NOT RIGHT FOR YOUR INSTALLATION
+ cp $(HOME)/src/protobuf/include/google/protobuf/compiler/plugin.proto .
+ protoc --go_out=Mgoogle/protobuf/descriptor.proto=github.com/golang/protobuf/protoc-gen-go/descriptor:../../../../.. \
+ -I$(HOME)/src/protobuf/include $(HOME)/src/protobuf/include/google/protobuf/compiler/plugin.proto
+
+restore:
+ cp plugin.pb.golden plugin.pb.go
+
+preserve:
+ cp plugin.pb.go plugin.pb.golden
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
new file mode 100644
index 0000000..c608a24
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.go
@@ -0,0 +1,293 @@
+// 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_unrecognized []byte `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) 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_unrecognized []byte `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) 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_unrecognized []byte `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) 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_unrecognized []byte `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) 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
new file mode 100644
index 0000000..8953d0f
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.pb.golden
@@ -0,0 +1,83 @@
+// 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
new file mode 100644
index 0000000..5b55745
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/plugin/plugin.proto
@@ -0,0 +1,167 @@
+// 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/golang/protobuf/protoc-gen-go/testdata/Makefile b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/Makefile
new file mode 100644
index 0000000..a0bf9fe
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/Makefile
@@ -0,0 +1,73 @@
+# 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.
+
+all:
+ @echo run make test
+
+include ../../Make.protobuf
+
+test: golden testbuild
+
+#test: golden testbuild extension_test
+# ./extension_test
+# @echo PASS
+
+my_test/test.pb.go: my_test/test.proto
+ protoc --go_out=Mmulti/multi1.proto=github.com/golang/protobuf/protoc-gen-go/testdata/multi:. $<
+
+golden:
+ make -B my_test/test.pb.go
+ sed -i -e '/return.*fileDescriptor/d' my_test/test.pb.go
+ sed -i -e '/^var fileDescriptor/,/^}/d' my_test/test.pb.go
+ sed -i -e '/proto.RegisterFile.*fileDescriptor/d' my_test/test.pb.go
+ gofmt -w my_test/test.pb.go
+ diff -w my_test/test.pb.go my_test/test.pb.go.golden
+
+nuke: clean
+
+testbuild: regenerate
+ go test
+
+regenerate:
+ # Invoke protoc once to generate three independent .pb.go files in the same package.
+ protoc --go_out=. multi/multi1.proto multi/multi2.proto multi/multi3.proto
+
+#extension_test: extension_test.$O
+# $(LD) -L. -o $@ $<
+
+#multi.a: multi3.pb.$O multi2.pb.$O multi1.pb.$O
+# rm -f multi.a
+# $(QUOTED_GOBIN)/gopack grc $@ $<
+
+#test.pb.go: imp.pb.go
+#multi1.pb.go: multi2.pb.go multi3.pb.go
+#main.$O: imp.pb.$O test.pb.$O multi.a
+#extension_test.$O: extension_base.pb.$O extension_extra.pb.$O extension_user.pb.$O
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base.proto
new file mode 100644
index 0000000..94acfc1
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_base.proto
@@ -0,0 +1,46 @@
+// 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.
+
+syntax = "proto2";
+
+package extension_base;
+
+message BaseMessage {
+ optional int32 height = 1;
+ extensions 4 to 9;
+ extensions 16 to max;
+}
+
+// Another message that may be extended, using message_set_wire_format.
+message OldStyleMessage {
+ option message_set_wire_format = true;
+ extensions 100 to max;
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra.proto
new file mode 100644
index 0000000..fca7f60
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_extra.proto
@@ -0,0 +1,38 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2011 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.
+
+syntax = "proto2";
+
+package extension_extra;
+
+message ExtraMessage {
+ optional int32 width = 1;
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_test.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_test.go
new file mode 100644
index 0000000..86e9c11
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_test.go
@@ -0,0 +1,210 @@
+// 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.
+
+// Test that we can use protocol buffers that use extensions.
+
+package testdata
+
+/*
+
+import (
+ "bytes"
+ "regexp"
+ "testing"
+
+ "github.com/golang/protobuf/proto"
+ base "extension_base.pb"
+ user "extension_user.pb"
+)
+
+func TestSingleFieldExtension(t *testing.T) {
+ bm := &base.BaseMessage{
+ Height: proto.Int32(178),
+ }
+
+ // Use extension within scope of another type.
+ vol := proto.Uint32(11)
+ err := proto.SetExtension(bm, user.E_LoudMessage_Volume, vol)
+ if err != nil {
+ t.Fatal("Failed setting extension:", err)
+ }
+ buf, err := proto.Marshal(bm)
+ if err != nil {
+ t.Fatal("Failed encoding message with extension:", err)
+ }
+ bm_new := new(base.BaseMessage)
+ if err := proto.Unmarshal(buf, bm_new); err != nil {
+ t.Fatal("Failed decoding message with extension:", err)
+ }
+ if !proto.HasExtension(bm_new, user.E_LoudMessage_Volume) {
+ t.Fatal("Decoded message didn't contain extension.")
+ }
+ vol_out, err := proto.GetExtension(bm_new, user.E_LoudMessage_Volume)
+ if err != nil {
+ t.Fatal("Failed getting extension:", err)
+ }
+ if v := vol_out.(*uint32); *v != *vol {
+ t.Errorf("vol_out = %v, expected %v", *v, *vol)
+ }
+ proto.ClearExtension(bm_new, user.E_LoudMessage_Volume)
+ if proto.HasExtension(bm_new, user.E_LoudMessage_Volume) {
+ t.Fatal("Failed clearing extension.")
+ }
+}
+
+func TestMessageExtension(t *testing.T) {
+ bm := &base.BaseMessage{
+ Height: proto.Int32(179),
+ }
+
+ // Use extension that is itself a message.
+ um := &user.UserMessage{
+ Name: proto.String("Dave"),
+ Rank: proto.String("Major"),
+ }
+ err := proto.SetExtension(bm, user.E_LoginMessage_UserMessage, um)
+ if err != nil {
+ t.Fatal("Failed setting extension:", err)
+ }
+ buf, err := proto.Marshal(bm)
+ if err != nil {
+ t.Fatal("Failed encoding message with extension:", err)
+ }
+ bm_new := new(base.BaseMessage)
+ if err := proto.Unmarshal(buf, bm_new); err != nil {
+ t.Fatal("Failed decoding message with extension:", err)
+ }
+ if !proto.HasExtension(bm_new, user.E_LoginMessage_UserMessage) {
+ t.Fatal("Decoded message didn't contain extension.")
+ }
+ um_out, err := proto.GetExtension(bm_new, user.E_LoginMessage_UserMessage)
+ if err != nil {
+ t.Fatal("Failed getting extension:", err)
+ }
+ if n := um_out.(*user.UserMessage).Name; *n != *um.Name {
+ t.Errorf("um_out.Name = %q, expected %q", *n, *um.Name)
+ }
+ if r := um_out.(*user.UserMessage).Rank; *r != *um.Rank {
+ t.Errorf("um_out.Rank = %q, expected %q", *r, *um.Rank)
+ }
+ proto.ClearExtension(bm_new, user.E_LoginMessage_UserMessage)
+ if proto.HasExtension(bm_new, user.E_LoginMessage_UserMessage) {
+ t.Fatal("Failed clearing extension.")
+ }
+}
+
+func TestTopLevelExtension(t *testing.T) {
+ bm := &base.BaseMessage{
+ Height: proto.Int32(179),
+ }
+
+ width := proto.Int32(17)
+ err := proto.SetExtension(bm, user.E_Width, width)
+ if err != nil {
+ t.Fatal("Failed setting extension:", err)
+ }
+ buf, err := proto.Marshal(bm)
+ if err != nil {
+ t.Fatal("Failed encoding message with extension:", err)
+ }
+ bm_new := new(base.BaseMessage)
+ if err := proto.Unmarshal(buf, bm_new); err != nil {
+ t.Fatal("Failed decoding message with extension:", err)
+ }
+ if !proto.HasExtension(bm_new, user.E_Width) {
+ t.Fatal("Decoded message didn't contain extension.")
+ }
+ width_out, err := proto.GetExtension(bm_new, user.E_Width)
+ if err != nil {
+ t.Fatal("Failed getting extension:", err)
+ }
+ if w := width_out.(*int32); *w != *width {
+ t.Errorf("width_out = %v, expected %v", *w, *width)
+ }
+ proto.ClearExtension(bm_new, user.E_Width)
+ if proto.HasExtension(bm_new, user.E_Width) {
+ t.Fatal("Failed clearing extension.")
+ }
+}
+
+func TestMessageSetWireFormat(t *testing.T) {
+ osm := new(base.OldStyleMessage)
+ osp := &user.OldStyleParcel{
+ Name: proto.String("Dave"),
+ Height: proto.Int32(178),
+ }
+
+ err := proto.SetExtension(osm, user.E_OldStyleParcel_MessageSetExtension, osp)
+ if err != nil {
+ t.Fatal("Failed setting extension:", err)
+ }
+
+ buf, err := proto.Marshal(osm)
+ if err != nil {
+ t.Fatal("Failed encoding message:", err)
+ }
+
+ // Data generated from Python implementation.
+ expected := []byte{
+ 11, 16, 209, 15, 26, 9, 10, 4, 68, 97, 118, 101, 16, 178, 1, 12,
+ }
+
+ if !bytes.Equal(expected, buf) {
+ t.Errorf("Encoding mismatch.\nwant %+v\n got %+v", expected, buf)
+ }
+
+ // Check that it is restored correctly.
+ osm = new(base.OldStyleMessage)
+ if err := proto.Unmarshal(buf, osm); err != nil {
+ t.Fatal("Failed decoding message:", err)
+ }
+ osp_out, err := proto.GetExtension(osm, user.E_OldStyleParcel_MessageSetExtension)
+ if err != nil {
+ t.Fatal("Failed getting extension:", err)
+ }
+ osp = osp_out.(*user.OldStyleParcel)
+ if *osp.Name != "Dave" || *osp.Height != 178 {
+ t.Errorf("Retrieved extension from decoded message is not correct: %+v", osp)
+ }
+}
+
+func main() {
+ // simpler than rigging up gotest
+ testing.Main(regexp.MatchString, []testing.InternalTest{
+ {"TestSingleFieldExtension", TestSingleFieldExtension},
+ {"TestMessageExtension", TestMessageExtension},
+ {"TestTopLevelExtension", TestTopLevelExtension},
+ },
+ []testing.InternalBenchmark{},
+ []testing.InternalExample{})
+}
+
+*/
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user.proto
new file mode 100644
index 0000000..ff65873
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/extension_user.proto
@@ -0,0 +1,100 @@
+// 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.
+
+syntax = "proto2";
+
+import "extension_base.proto";
+import "extension_extra.proto";
+
+package extension_user;
+
+message UserMessage {
+ optional string name = 1;
+ optional string rank = 2;
+}
+
+// Extend with a message
+extend extension_base.BaseMessage {
+ optional UserMessage user_message = 5;
+}
+
+// Extend with a foreign message
+extend extension_base.BaseMessage {
+ optional extension_extra.ExtraMessage extra_message = 9;
+}
+
+// Extend with some primitive types
+extend extension_base.BaseMessage {
+ optional int32 width = 6;
+ optional int64 area = 7;
+}
+
+// Extend inside the scope of another type
+message LoudMessage {
+ extend extension_base.BaseMessage {
+ optional uint32 volume = 8;
+ }
+ extensions 100 to max;
+}
+
+// Extend inside the scope of another type, using a message.
+message LoginMessage {
+ extend extension_base.BaseMessage {
+ optional UserMessage user_message = 16;
+ }
+}
+
+// Extend with a repeated field
+extend extension_base.BaseMessage {
+ repeated Detail detail = 17;
+}
+
+message Detail {
+ optional string color = 1;
+}
+
+// An extension of an extension
+message Announcement {
+ optional string words = 1;
+ extend LoudMessage {
+ optional Announcement loud_ext = 100;
+ }
+}
+
+// Something that can be put in a message set.
+message OldStyleParcel {
+ extend extension_base.OldStyleMessage {
+ optional OldStyleParcel message_set_extension = 2001;
+ }
+
+ required string name = 1;
+ optional int32 height = 2;
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/grpc.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/grpc.proto
new file mode 100644
index 0000000..b8bc41a
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/grpc.proto
@@ -0,0 +1,59 @@
+// 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.
+
+syntax = "proto3";
+
+package grpc.testing;
+
+message SimpleRequest {
+}
+
+message SimpleResponse {
+}
+
+message StreamMsg {
+}
+
+message StreamMsg2 {
+}
+
+service Test {
+ rpc UnaryCall(SimpleRequest) returns (SimpleResponse);
+
+ // This RPC streams from the server only.
+ rpc Downstream(SimpleRequest) returns (stream StreamMsg);
+
+ // This RPC streams from the client.
+ rpc Upstream(stream StreamMsg) returns (SimpleResponse);
+
+ // This one streams in both directions.
+ rpc Bidi(stream StreamMsg) returns (stream StreamMsg2);
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp.pb.go.golden b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp.pb.go.golden
new file mode 100644
index 0000000..784a4f8
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp.pb.go.golden
@@ -0,0 +1,113 @@
+// Code generated by protoc-gen-go.
+// source: imp.proto
+// DO NOT EDIT!
+
+package imp
+
+import proto "github.com/golang/protobuf/proto"
+import "math"
+import "os"
+import imp1 "imp2.pb"
+
+// Reference proto & math imports to suppress error if they are not otherwise used.
+var _ = proto.GetString
+var _ = math.Inf
+
+// Types from public import imp2.proto
+type PubliclyImportedMessage imp1.PubliclyImportedMessage
+
+func (this *PubliclyImportedMessage) Reset() { (*imp1.PubliclyImportedMessage)(this).Reset() }
+func (this *PubliclyImportedMessage) String() string {
+ return (*imp1.PubliclyImportedMessage)(this).String()
+}
+
+// PubliclyImportedMessage from public import imp.proto
+
+type ImportedMessage_Owner int32
+
+const (
+ ImportedMessage_DAVE ImportedMessage_Owner = 1
+ ImportedMessage_MIKE ImportedMessage_Owner = 2
+)
+
+var ImportedMessage_Owner_name = map[int32]string{
+ 1: "DAVE",
+ 2: "MIKE",
+}
+var ImportedMessage_Owner_value = map[string]int32{
+ "DAVE": 1,
+ "MIKE": 2,
+}
+
+// NewImportedMessage_Owner is deprecated. Use x.Enum() instead.
+func NewImportedMessage_Owner(x ImportedMessage_Owner) *ImportedMessage_Owner {
+ e := ImportedMessage_Owner(x)
+ return &e
+}
+func (x ImportedMessage_Owner) Enum() *ImportedMessage_Owner {
+ p := new(ImportedMessage_Owner)
+ *p = x
+ return p
+}
+func (x ImportedMessage_Owner) String() string {
+ return proto.EnumName(ImportedMessage_Owner_name, int32(x))
+}
+
+type ImportedMessage struct {
+ Field *int64 `protobuf:"varint,1,req,name=field" json:"field,omitempty"`
+ XXX_extensions map[int32][]byte `json:",omitempty"`
+ XXX_unrecognized []byte `json:",omitempty"`
+}
+
+func (this *ImportedMessage) Reset() { *this = ImportedMessage{} }
+func (this *ImportedMessage) String() string { return proto.CompactTextString(this) }
+
+var extRange_ImportedMessage = []proto.ExtensionRange{
+ proto.ExtensionRange{90, 100},
+}
+
+func (*ImportedMessage) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_ImportedMessage
+}
+func (this *ImportedMessage) ExtensionMap() map[int32][]byte {
+ if this.XXX_extensions == nil {
+ this.XXX_extensions = make(map[int32][]byte)
+ }
+ return this.XXX_extensions
+}
+
+type ImportedExtendable struct {
+ XXX_extensions map[int32][]byte `json:",omitempty"`
+ XXX_unrecognized []byte `json:",omitempty"`
+}
+
+func (this *ImportedExtendable) Reset() { *this = ImportedExtendable{} }
+func (this *ImportedExtendable) String() string { return proto.CompactTextString(this) }
+
+func (this *ImportedExtendable) Marshal() ([]byte, error) {
+ return proto.MarshalMessageSet(this.ExtensionMap())
+}
+func (this *ImportedExtendable) Unmarshal(buf []byte) error {
+ return proto.UnmarshalMessageSet(buf, this.ExtensionMap())
+}
+// ensure ImportedExtendable satisfies proto.Marshaler and proto.Unmarshaler
+var _ proto.Marshaler = (*ImportedExtendable)(nil)
+var _ proto.Unmarshaler = (*ImportedExtendable)(nil)
+
+var extRange_ImportedExtendable = []proto.ExtensionRange{
+ proto.ExtensionRange{100, 536870911},
+}
+
+func (*ImportedExtendable) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_ImportedExtendable
+}
+func (this *ImportedExtendable) ExtensionMap() map[int32][]byte {
+ if this.XXX_extensions == nil {
+ this.XXX_extensions = make(map[int32][]byte)
+ }
+ return this.XXX_extensions
+}
+
+func init() {
+ proto.RegisterEnum("imp.ImportedMessage_Owner", ImportedMessage_Owner_name, ImportedMessage_Owner_value)
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp.proto
new file mode 100644
index 0000000..156e078
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp.proto
@@ -0,0 +1,70 @@
+// 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.
+
+syntax = "proto2";
+
+package imp;
+
+import "imp2.proto";
+import "imp3.proto";
+
+message ImportedMessage {
+ required int64 field = 1;
+
+ // The forwarded getters for these fields are fiddly to get right.
+ optional ImportedMessage2 local_msg = 2;
+ optional ForeignImportedMessage foreign_msg = 3; // in imp3.proto
+ optional Owner enum_field = 4;
+ oneof union {
+ int32 state = 9;
+ }
+
+ repeated string name = 5;
+ repeated Owner boss = 6;
+ repeated ImportedMessage2 memo = 7;
+
+ map msg_map = 8;
+
+ enum Owner {
+ DAVE = 1;
+ MIKE = 2;
+ }
+
+ extensions 90 to 100;
+}
+
+message ImportedMessage2 {
+}
+
+message ImportedExtendable {
+ option message_set_wire_format = true;
+ extensions 100 to max;
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp2.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp2.proto
new file mode 100644
index 0000000..3bb0632
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp2.proto
@@ -0,0 +1,43 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2011 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.
+
+syntax = "proto2";
+
+package imp;
+
+message PubliclyImportedMessage {
+ optional int64 field = 1;
+}
+
+enum PubliclyImportedEnum {
+ GLASSES = 1;
+ HAIR = 2;
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp3.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp3.proto
new file mode 100644
index 0000000..58fc759
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/imp3.proto
@@ -0,0 +1,38 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2012 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.
+
+syntax = "proto2";
+
+package imp;
+
+message ForeignImportedMessage {
+ optional string tuber = 1;
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/main_test.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/main_test.go
new file mode 100644
index 0000000..f9b5ccf
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/main_test.go
@@ -0,0 +1,46 @@
+// 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 simple binary to link together the protocol buffers in this test.
+
+package testdata
+
+import (
+ "testing"
+
+ mytestpb "./my_test"
+ multipb "github.com/golang/protobuf/protoc-gen-go/testdata/multi"
+)
+
+func TestLink(t *testing.T) {
+ _ = &multipb.Multi1{}
+ _ = &mytestpb.Request{}
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.proto
new file mode 100644
index 0000000..0da6e0a
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi1.proto
@@ -0,0 +1,44 @@
+// 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.
+
+syntax = "proto2";
+
+import "multi/multi2.proto";
+import "multi/multi3.proto";
+
+package multitest;
+
+message Multi1 {
+ required Multi2 multi2 = 1;
+ optional Multi2.Color color = 2;
+ optional Multi3.HatType hat_type = 3;
+}
+
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.proto
new file mode 100644
index 0000000..e6bfc71
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi2.proto
@@ -0,0 +1,46 @@
+// 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.
+
+syntax = "proto2";
+
+package multitest;
+
+message Multi2 {
+ required int32 required_value = 1;
+
+ enum Color {
+ BLUE = 1;
+ GREEN = 2;
+ RED = 3;
+ };
+ optional Color color = 2;
+}
+
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.proto
new file mode 100644
index 0000000..146c255
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/multi/multi3.proto
@@ -0,0 +1,43 @@
+// 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.
+
+syntax = "proto2";
+
+package multitest;
+
+message Multi3 {
+ enum HatType {
+ FEDORA = 1;
+ FEZ = 2;
+ };
+ optional HatType hat_type = 1;
+}
+
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go
new file mode 100644
index 0000000..1954e3f
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go
@@ -0,0 +1,870 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: my_test/test.proto
+
+/*
+Package my_test is a generated protocol buffer package.
+
+This package holds interesting messages.
+
+It is generated from these files:
+ my_test/test.proto
+
+It has these top-level messages:
+ Request
+ Reply
+ OtherBase
+ ReplyExtensions
+ OtherReplyExtensions
+ OldReply
+ Communique
+*/
+package my_test
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/golang/protobuf/protoc-gen-go/testdata/multi"
+
+// 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
+
+type HatType int32
+
+const (
+ // deliberately skipping 0
+ HatType_FEDORA HatType = 1
+ HatType_FEZ HatType = 2
+)
+
+var HatType_name = map[int32]string{
+ 1: "FEDORA",
+ 2: "FEZ",
+}
+var HatType_value = map[string]int32{
+ "FEDORA": 1,
+ "FEZ": 2,
+}
+
+func (x HatType) Enum() *HatType {
+ p := new(HatType)
+ *p = x
+ return p
+}
+func (x HatType) String() string {
+ return proto.EnumName(HatType_name, int32(x))
+}
+func (x *HatType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(HatType_value, data, "HatType")
+ if err != nil {
+ return err
+ }
+ *x = HatType(value)
+ return nil
+}
+
+// This enum represents days of the week.
+type Days int32
+
+const (
+ Days_MONDAY Days = 1
+ Days_TUESDAY Days = 2
+ Days_LUNDI Days = 1
+)
+
+var Days_name = map[int32]string{
+ 1: "MONDAY",
+ 2: "TUESDAY",
+ // Duplicate value: 1: "LUNDI",
+}
+var Days_value = map[string]int32{
+ "MONDAY": 1,
+ "TUESDAY": 2,
+ "LUNDI": 1,
+}
+
+func (x Days) Enum() *Days {
+ p := new(Days)
+ *p = x
+ return p
+}
+func (x Days) String() string {
+ return proto.EnumName(Days_name, int32(x))
+}
+func (x *Days) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(Days_value, data, "Days")
+ if err != nil {
+ return err
+ }
+ *x = Days(value)
+ return nil
+}
+
+type Request_Color int32
+
+const (
+ Request_RED Request_Color = 0
+ Request_GREEN Request_Color = 1
+ Request_BLUE Request_Color = 2
+)
+
+var Request_Color_name = map[int32]string{
+ 0: "RED",
+ 1: "GREEN",
+ 2: "BLUE",
+}
+var Request_Color_value = map[string]int32{
+ "RED": 0,
+ "GREEN": 1,
+ "BLUE": 2,
+}
+
+func (x Request_Color) Enum() *Request_Color {
+ p := new(Request_Color)
+ *p = x
+ return p
+}
+func (x Request_Color) String() string {
+ return proto.EnumName(Request_Color_name, int32(x))
+}
+func (x *Request_Color) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(Request_Color_value, data, "Request_Color")
+ if err != nil {
+ return err
+ }
+ *x = Request_Color(value)
+ return nil
+}
+
+type Reply_Entry_Game int32
+
+const (
+ Reply_Entry_FOOTBALL Reply_Entry_Game = 1
+ Reply_Entry_TENNIS Reply_Entry_Game = 2
+)
+
+var Reply_Entry_Game_name = map[int32]string{
+ 1: "FOOTBALL",
+ 2: "TENNIS",
+}
+var Reply_Entry_Game_value = map[string]int32{
+ "FOOTBALL": 1,
+ "TENNIS": 2,
+}
+
+func (x Reply_Entry_Game) Enum() *Reply_Entry_Game {
+ p := new(Reply_Entry_Game)
+ *p = x
+ return p
+}
+func (x Reply_Entry_Game) String() string {
+ return proto.EnumName(Reply_Entry_Game_name, int32(x))
+}
+func (x *Reply_Entry_Game) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(Reply_Entry_Game_value, data, "Reply_Entry_Game")
+ if err != nil {
+ return err
+ }
+ *x = Reply_Entry_Game(value)
+ return nil
+}
+
+// This is a message that might be sent somewhere.
+type Request struct {
+ Key []int64 `protobuf:"varint,1,rep,name=key" json:"key,omitempty"`
+ // optional imp.ImportedMessage imported_message = 2;
+ Hue *Request_Color `protobuf:"varint,3,opt,name=hue,enum=my.test.Request_Color" json:"hue,omitempty"`
+ Hat *HatType `protobuf:"varint,4,opt,name=hat,enum=my.test.HatType,def=1" json:"hat,omitempty"`
+ // optional imp.ImportedMessage.Owner owner = 6;
+ Deadline *float32 `protobuf:"fixed32,7,opt,name=deadline,def=inf" json:"deadline,omitempty"`
+ Somegroup *Request_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"`
+ // This is a map field. It will generate map[int32]string.
+ NameMapping map[int32]string `protobuf:"bytes,14,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ // This is a map field whose value type is a message.
+ MsgMapping map[int64]*Reply `protobuf:"bytes,15,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Reset_ *int32 `protobuf:"varint,12,opt,name=reset" json:"reset,omitempty"`
+ // This field should not conflict with any getters.
+ GetKey_ *string `protobuf:"bytes,16,opt,name=get_key,json=getKey" json:"get_key,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Request) Reset() { *m = Request{} }
+func (m *Request) String() string { return proto.CompactTextString(m) }
+func (*Request) ProtoMessage() {}
+
+const Default_Request_Hat HatType = HatType_FEDORA
+
+var Default_Request_Deadline float32 = float32(math.Inf(1))
+
+func (m *Request) GetKey() []int64 {
+ if m != nil {
+ return m.Key
+ }
+ return nil
+}
+
+func (m *Request) GetHue() Request_Color {
+ if m != nil && m.Hue != nil {
+ return *m.Hue
+ }
+ return Request_RED
+}
+
+func (m *Request) GetHat() HatType {
+ if m != nil && m.Hat != nil {
+ return *m.Hat
+ }
+ return Default_Request_Hat
+}
+
+func (m *Request) GetDeadline() float32 {
+ if m != nil && m.Deadline != nil {
+ return *m.Deadline
+ }
+ return Default_Request_Deadline
+}
+
+func (m *Request) GetSomegroup() *Request_SomeGroup {
+ if m != nil {
+ return m.Somegroup
+ }
+ return nil
+}
+
+func (m *Request) GetNameMapping() map[int32]string {
+ if m != nil {
+ return m.NameMapping
+ }
+ return nil
+}
+
+func (m *Request) GetMsgMapping() map[int64]*Reply {
+ if m != nil {
+ return m.MsgMapping
+ }
+ return nil
+}
+
+func (m *Request) GetReset_() int32 {
+ if m != nil && m.Reset_ != nil {
+ return *m.Reset_
+ }
+ return 0
+}
+
+func (m *Request) GetGetKey_() string {
+ if m != nil && m.GetKey_ != nil {
+ return *m.GetKey_
+ }
+ return ""
+}
+
+type Request_SomeGroup struct {
+ GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Request_SomeGroup) Reset() { *m = Request_SomeGroup{} }
+func (m *Request_SomeGroup) String() string { return proto.CompactTextString(m) }
+func (*Request_SomeGroup) ProtoMessage() {}
+
+func (m *Request_SomeGroup) GetGroupField() int32 {
+ if m != nil && m.GroupField != nil {
+ return *m.GroupField
+ }
+ return 0
+}
+
+type Reply struct {
+ Found []*Reply_Entry `protobuf:"bytes,1,rep,name=found" json:"found,omitempty"`
+ CompactKeys []int32 `protobuf:"varint,2,rep,packed,name=compact_keys,json=compactKeys" json:"compact_keys,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Reply) Reset() { *m = Reply{} }
+func (m *Reply) String() string { return proto.CompactTextString(m) }
+func (*Reply) ProtoMessage() {}
+
+var extRange_Reply = []proto.ExtensionRange{
+ {100, 536870911},
+}
+
+func (*Reply) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_Reply
+}
+
+func (m *Reply) GetFound() []*Reply_Entry {
+ if m != nil {
+ return m.Found
+ }
+ return nil
+}
+
+func (m *Reply) GetCompactKeys() []int32 {
+ if m != nil {
+ return m.CompactKeys
+ }
+ return nil
+}
+
+type Reply_Entry struct {
+ KeyThatNeeds_1234Camel_CasIng *int64 `protobuf:"varint,1,req,name=key_that_needs_1234camel_CasIng,json=keyThatNeeds1234camelCasIng" json:"key_that_needs_1234camel_CasIng,omitempty"`
+ Value *int64 `protobuf:"varint,2,opt,name=value,def=7" json:"value,omitempty"`
+ XMyFieldName_2 *int64 `protobuf:"varint,3,opt,name=_my_field_name_2,json=MyFieldName2" json:"_my_field_name_2,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Reply_Entry) Reset() { *m = Reply_Entry{} }
+func (m *Reply_Entry) String() string { return proto.CompactTextString(m) }
+func (*Reply_Entry) ProtoMessage() {}
+
+const Default_Reply_Entry_Value int64 = 7
+
+func (m *Reply_Entry) GetKeyThatNeeds_1234Camel_CasIng() int64 {
+ if m != nil && m.KeyThatNeeds_1234Camel_CasIng != nil {
+ return *m.KeyThatNeeds_1234Camel_CasIng
+ }
+ return 0
+}
+
+func (m *Reply_Entry) GetValue() int64 {
+ if m != nil && m.Value != nil {
+ return *m.Value
+ }
+ return Default_Reply_Entry_Value
+}
+
+func (m *Reply_Entry) GetXMyFieldName_2() int64 {
+ if m != nil && m.XMyFieldName_2 != nil {
+ return *m.XMyFieldName_2
+ }
+ return 0
+}
+
+type OtherBase struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OtherBase) Reset() { *m = OtherBase{} }
+func (m *OtherBase) String() string { return proto.CompactTextString(m) }
+func (*OtherBase) ProtoMessage() {}
+
+var extRange_OtherBase = []proto.ExtensionRange{
+ {100, 536870911},
+}
+
+func (*OtherBase) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_OtherBase
+}
+
+func (m *OtherBase) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+type ReplyExtensions struct {
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *ReplyExtensions) Reset() { *m = ReplyExtensions{} }
+func (m *ReplyExtensions) String() string { return proto.CompactTextString(m) }
+func (*ReplyExtensions) ProtoMessage() {}
+
+var E_ReplyExtensions_Time = &proto.ExtensionDesc{
+ ExtendedType: (*Reply)(nil),
+ ExtensionType: (*float64)(nil),
+ Field: 101,
+ Name: "my.test.ReplyExtensions.time",
+ Tag: "fixed64,101,opt,name=time",
+ Filename: "my_test/test.proto",
+}
+
+var E_ReplyExtensions_Carrot = &proto.ExtensionDesc{
+ ExtendedType: (*Reply)(nil),
+ ExtensionType: (*ReplyExtensions)(nil),
+ Field: 105,
+ Name: "my.test.ReplyExtensions.carrot",
+ Tag: "bytes,105,opt,name=carrot",
+ Filename: "my_test/test.proto",
+}
+
+var E_ReplyExtensions_Donut = &proto.ExtensionDesc{
+ ExtendedType: (*OtherBase)(nil),
+ ExtensionType: (*ReplyExtensions)(nil),
+ Field: 101,
+ Name: "my.test.ReplyExtensions.donut",
+ Tag: "bytes,101,opt,name=donut",
+ Filename: "my_test/test.proto",
+}
+
+type OtherReplyExtensions struct {
+ Key *int32 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OtherReplyExtensions) Reset() { *m = OtherReplyExtensions{} }
+func (m *OtherReplyExtensions) String() string { return proto.CompactTextString(m) }
+func (*OtherReplyExtensions) ProtoMessage() {}
+
+func (m *OtherReplyExtensions) GetKey() int32 {
+ if m != nil && m.Key != nil {
+ return *m.Key
+ }
+ return 0
+}
+
+type OldReply struct {
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OldReply) Reset() { *m = OldReply{} }
+func (m *OldReply) String() string { return proto.CompactTextString(m) }
+func (*OldReply) ProtoMessage() {}
+
+func (m *OldReply) Marshal() ([]byte, error) {
+ return proto.MarshalMessageSet(&m.XXX_InternalExtensions)
+}
+func (m *OldReply) Unmarshal(buf []byte) error {
+ return proto.UnmarshalMessageSet(buf, &m.XXX_InternalExtensions)
+}
+func (m *OldReply) MarshalJSON() ([]byte, error) {
+ return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions)
+}
+func (m *OldReply) UnmarshalJSON(buf []byte) error {
+ return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions)
+}
+
+// ensure OldReply satisfies proto.Marshaler and proto.Unmarshaler
+var _ proto.Marshaler = (*OldReply)(nil)
+var _ proto.Unmarshaler = (*OldReply)(nil)
+
+var extRange_OldReply = []proto.ExtensionRange{
+ {100, 2147483646},
+}
+
+func (*OldReply) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_OldReply
+}
+
+type Communique struct {
+ MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"`
+ // This is a oneof, called "union".
+ //
+ // Types that are valid to be assigned to Union:
+ // *Communique_Number
+ // *Communique_Name
+ // *Communique_Data
+ // *Communique_TempC
+ // *Communique_Height
+ // *Communique_Today
+ // *Communique_Maybe
+ // *Communique_Delta_
+ // *Communique_Msg
+ // *Communique_Somegroup
+ Union isCommunique_Union `protobuf_oneof:"union"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Communique) Reset() { *m = Communique{} }
+func (m *Communique) String() string { return proto.CompactTextString(m) }
+func (*Communique) ProtoMessage() {}
+
+type isCommunique_Union interface {
+ isCommunique_Union()
+}
+
+type Communique_Number struct {
+ Number int32 `protobuf:"varint,5,opt,name=number,oneof"`
+}
+type Communique_Name struct {
+ Name string `protobuf:"bytes,6,opt,name=name,oneof"`
+}
+type Communique_Data struct {
+ Data []byte `protobuf:"bytes,7,opt,name=data,oneof"`
+}
+type Communique_TempC struct {
+ TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"`
+}
+type Communique_Height struct {
+ Height float32 `protobuf:"fixed32,9,opt,name=height,oneof"`
+}
+type Communique_Today struct {
+ Today Days `protobuf:"varint,10,opt,name=today,enum=my.test.Days,oneof"`
+}
+type Communique_Maybe struct {
+ Maybe bool `protobuf:"varint,11,opt,name=maybe,oneof"`
+}
+type Communique_Delta_ struct {
+ Delta int32 `protobuf:"zigzag32,12,opt,name=delta,oneof"`
+}
+type Communique_Msg struct {
+ Msg *Reply `protobuf:"bytes,13,opt,name=msg,oneof"`
+}
+type Communique_Somegroup struct {
+ Somegroup *Communique_SomeGroup `protobuf:"group,14,opt,name=SomeGroup,json=somegroup,oneof"`
+}
+
+func (*Communique_Number) isCommunique_Union() {}
+func (*Communique_Name) isCommunique_Union() {}
+func (*Communique_Data) isCommunique_Union() {}
+func (*Communique_TempC) isCommunique_Union() {}
+func (*Communique_Height) isCommunique_Union() {}
+func (*Communique_Today) isCommunique_Union() {}
+func (*Communique_Maybe) isCommunique_Union() {}
+func (*Communique_Delta_) isCommunique_Union() {}
+func (*Communique_Msg) isCommunique_Union() {}
+func (*Communique_Somegroup) isCommunique_Union() {}
+
+func (m *Communique) GetUnion() isCommunique_Union {
+ if m != nil {
+ return m.Union
+ }
+ return nil
+}
+
+func (m *Communique) GetMakeMeCry() bool {
+ if m != nil && m.MakeMeCry != nil {
+ return *m.MakeMeCry
+ }
+ return false
+}
+
+func (m *Communique) GetNumber() int32 {
+ if x, ok := m.GetUnion().(*Communique_Number); ok {
+ return x.Number
+ }
+ return 0
+}
+
+func (m *Communique) GetName() string {
+ if x, ok := m.GetUnion().(*Communique_Name); ok {
+ return x.Name
+ }
+ return ""
+}
+
+func (m *Communique) GetData() []byte {
+ if x, ok := m.GetUnion().(*Communique_Data); ok {
+ return x.Data
+ }
+ return nil
+}
+
+func (m *Communique) GetTempC() float64 {
+ if x, ok := m.GetUnion().(*Communique_TempC); ok {
+ return x.TempC
+ }
+ return 0
+}
+
+func (m *Communique) GetHeight() float32 {
+ if x, ok := m.GetUnion().(*Communique_Height); ok {
+ return x.Height
+ }
+ return 0
+}
+
+func (m *Communique) GetToday() Days {
+ if x, ok := m.GetUnion().(*Communique_Today); ok {
+ return x.Today
+ }
+ return Days_MONDAY
+}
+
+func (m *Communique) GetMaybe() bool {
+ if x, ok := m.GetUnion().(*Communique_Maybe); ok {
+ return x.Maybe
+ }
+ return false
+}
+
+func (m *Communique) GetDelta() int32 {
+ if x, ok := m.GetUnion().(*Communique_Delta_); ok {
+ return x.Delta
+ }
+ return 0
+}
+
+func (m *Communique) GetMsg() *Reply {
+ if x, ok := m.GetUnion().(*Communique_Msg); ok {
+ return x.Msg
+ }
+ return nil
+}
+
+func (m *Communique) GetSomegroup() *Communique_SomeGroup {
+ if x, ok := m.GetUnion().(*Communique_Somegroup); ok {
+ return x.Somegroup
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{
+ (*Communique_Number)(nil),
+ (*Communique_Name)(nil),
+ (*Communique_Data)(nil),
+ (*Communique_TempC)(nil),
+ (*Communique_Height)(nil),
+ (*Communique_Today)(nil),
+ (*Communique_Maybe)(nil),
+ (*Communique_Delta_)(nil),
+ (*Communique_Msg)(nil),
+ (*Communique_Somegroup)(nil),
+ }
+}
+
+func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*Communique)
+ // union
+ switch x := m.Union.(type) {
+ case *Communique_Number:
+ b.EncodeVarint(5<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.Number))
+ case *Communique_Name:
+ b.EncodeVarint(6<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.Name)
+ case *Communique_Data:
+ b.EncodeVarint(7<<3 | proto.WireBytes)
+ b.EncodeRawBytes(x.Data)
+ case *Communique_TempC:
+ b.EncodeVarint(8<<3 | proto.WireFixed64)
+ b.EncodeFixed64(math.Float64bits(x.TempC))
+ case *Communique_Height:
+ b.EncodeVarint(9<<3 | proto.WireFixed32)
+ b.EncodeFixed32(uint64(math.Float32bits(x.Height)))
+ case *Communique_Today:
+ b.EncodeVarint(10<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.Today))
+ case *Communique_Maybe:
+ t := uint64(0)
+ if x.Maybe {
+ t = 1
+ }
+ b.EncodeVarint(11<<3 | proto.WireVarint)
+ b.EncodeVarint(t)
+ case *Communique_Delta_:
+ b.EncodeVarint(12<<3 | proto.WireVarint)
+ b.EncodeZigzag32(uint64(x.Delta))
+ case *Communique_Msg:
+ b.EncodeVarint(13<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Msg); err != nil {
+ return err
+ }
+ case *Communique_Somegroup:
+ b.EncodeVarint(14<<3 | proto.WireStartGroup)
+ if err := b.Marshal(x.Somegroup); err != nil {
+ return err
+ }
+ b.EncodeVarint(14<<3 | proto.WireEndGroup)
+ case nil:
+ default:
+ return fmt.Errorf("Communique.Union has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*Communique)
+ switch tag {
+ case 5: // union.number
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Communique_Number{int32(x)}
+ return true, err
+ case 6: // union.name
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Union = &Communique_Name{x}
+ return true, err
+ case 7: // union.data
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeRawBytes(true)
+ m.Union = &Communique_Data{x}
+ return true, err
+ case 8: // union.temp_c
+ if wire != proto.WireFixed64 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed64()
+ m.Union = &Communique_TempC{math.Float64frombits(x)}
+ return true, err
+ case 9: // union.height
+ if wire != proto.WireFixed32 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed32()
+ m.Union = &Communique_Height{math.Float32frombits(uint32(x))}
+ return true, err
+ case 10: // union.today
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Communique_Today{Days(x)}
+ return true, err
+ case 11: // union.maybe
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Communique_Maybe{x != 0}
+ return true, err
+ case 12: // union.delta
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeZigzag32()
+ m.Union = &Communique_Delta_{int32(x)}
+ return true, err
+ case 13: // union.msg
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Reply)
+ err := b.DecodeMessage(msg)
+ m.Union = &Communique_Msg{msg}
+ return true, err
+ case 14: // union.somegroup
+ if wire != proto.WireStartGroup {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Communique_SomeGroup)
+ err := b.DecodeGroup(msg)
+ m.Union = &Communique_Somegroup{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _Communique_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*Communique)
+ // union
+ switch x := m.Union.(type) {
+ case *Communique_Number:
+ n += proto.SizeVarint(5<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.Number))
+ case *Communique_Name:
+ n += proto.SizeVarint(6<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Name)))
+ n += len(x.Name)
+ case *Communique_Data:
+ n += proto.SizeVarint(7<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Data)))
+ n += len(x.Data)
+ case *Communique_TempC:
+ n += proto.SizeVarint(8<<3 | proto.WireFixed64)
+ n += 8
+ case *Communique_Height:
+ n += proto.SizeVarint(9<<3 | proto.WireFixed32)
+ n += 4
+ case *Communique_Today:
+ n += proto.SizeVarint(10<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.Today))
+ case *Communique_Maybe:
+ n += proto.SizeVarint(11<<3 | proto.WireVarint)
+ n += 1
+ case *Communique_Delta_:
+ n += proto.SizeVarint(12<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64((uint32(x.Delta) << 1) ^ uint32((int32(x.Delta) >> 31))))
+ case *Communique_Msg:
+ s := proto.Size(x.Msg)
+ n += proto.SizeVarint(13<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Communique_Somegroup:
+ n += proto.SizeVarint(14<<3 | proto.WireStartGroup)
+ n += proto.Size(x.Somegroup)
+ n += proto.SizeVarint(14<<3 | proto.WireEndGroup)
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+type Communique_SomeGroup struct {
+ Member *string `protobuf:"bytes,15,opt,name=member" json:"member,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Communique_SomeGroup) Reset() { *m = Communique_SomeGroup{} }
+func (m *Communique_SomeGroup) String() string { return proto.CompactTextString(m) }
+func (*Communique_SomeGroup) ProtoMessage() {}
+
+func (m *Communique_SomeGroup) GetMember() string {
+ if m != nil && m.Member != nil {
+ return *m.Member
+ }
+ return ""
+}
+
+type Communique_Delta struct {
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Communique_Delta) Reset() { *m = Communique_Delta{} }
+func (m *Communique_Delta) String() string { return proto.CompactTextString(m) }
+func (*Communique_Delta) ProtoMessage() {}
+
+var E_Tag = &proto.ExtensionDesc{
+ ExtendedType: (*Reply)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 103,
+ Name: "my.test.tag",
+ Tag: "bytes,103,opt,name=tag",
+ Filename: "my_test/test.proto",
+}
+
+var E_Donut = &proto.ExtensionDesc{
+ ExtendedType: (*Reply)(nil),
+ ExtensionType: (*OtherReplyExtensions)(nil),
+ Field: 106,
+ Name: "my.test.donut",
+ Tag: "bytes,106,opt,name=donut",
+ Filename: "my_test/test.proto",
+}
+
+func init() {
+ proto.RegisterType((*Request)(nil), "my.test.Request")
+ proto.RegisterType((*Request_SomeGroup)(nil), "my.test.Request.SomeGroup")
+ proto.RegisterType((*Reply)(nil), "my.test.Reply")
+ proto.RegisterType((*Reply_Entry)(nil), "my.test.Reply.Entry")
+ proto.RegisterType((*OtherBase)(nil), "my.test.OtherBase")
+ proto.RegisterType((*ReplyExtensions)(nil), "my.test.ReplyExtensions")
+ proto.RegisterType((*OtherReplyExtensions)(nil), "my.test.OtherReplyExtensions")
+ proto.RegisterType((*OldReply)(nil), "my.test.OldReply")
+ proto.RegisterType((*Communique)(nil), "my.test.Communique")
+ proto.RegisterType((*Communique_SomeGroup)(nil), "my.test.Communique.SomeGroup")
+ proto.RegisterType((*Communique_Delta)(nil), "my.test.Communique.Delta")
+ proto.RegisterEnum("my.test.HatType", HatType_name, HatType_value)
+ proto.RegisterEnum("my.test.Days", Days_name, Days_value)
+ proto.RegisterEnum("my.test.Request_Color", Request_Color_name, Request_Color_value)
+ proto.RegisterEnum("my.test.Reply_Entry_Game", Reply_Entry_Game_name, Reply_Entry_Game_value)
+ proto.RegisterExtension(E_ReplyExtensions_Time)
+ proto.RegisterExtension(E_ReplyExtensions_Carrot)
+ proto.RegisterExtension(E_ReplyExtensions_Donut)
+ proto.RegisterExtension(E_Tag)
+ proto.RegisterExtension(E_Donut)
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go.golden b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go.golden
new file mode 100644
index 0000000..1954e3f
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.pb.go.golden
@@ -0,0 +1,870 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: my_test/test.proto
+
+/*
+Package my_test is a generated protocol buffer package.
+
+This package holds interesting messages.
+
+It is generated from these files:
+ my_test/test.proto
+
+It has these top-level messages:
+ Request
+ Reply
+ OtherBase
+ ReplyExtensions
+ OtherReplyExtensions
+ OldReply
+ Communique
+*/
+package my_test
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+import _ "github.com/golang/protobuf/protoc-gen-go/testdata/multi"
+
+// 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
+
+type HatType int32
+
+const (
+ // deliberately skipping 0
+ HatType_FEDORA HatType = 1
+ HatType_FEZ HatType = 2
+)
+
+var HatType_name = map[int32]string{
+ 1: "FEDORA",
+ 2: "FEZ",
+}
+var HatType_value = map[string]int32{
+ "FEDORA": 1,
+ "FEZ": 2,
+}
+
+func (x HatType) Enum() *HatType {
+ p := new(HatType)
+ *p = x
+ return p
+}
+func (x HatType) String() string {
+ return proto.EnumName(HatType_name, int32(x))
+}
+func (x *HatType) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(HatType_value, data, "HatType")
+ if err != nil {
+ return err
+ }
+ *x = HatType(value)
+ return nil
+}
+
+// This enum represents days of the week.
+type Days int32
+
+const (
+ Days_MONDAY Days = 1
+ Days_TUESDAY Days = 2
+ Days_LUNDI Days = 1
+)
+
+var Days_name = map[int32]string{
+ 1: "MONDAY",
+ 2: "TUESDAY",
+ // Duplicate value: 1: "LUNDI",
+}
+var Days_value = map[string]int32{
+ "MONDAY": 1,
+ "TUESDAY": 2,
+ "LUNDI": 1,
+}
+
+func (x Days) Enum() *Days {
+ p := new(Days)
+ *p = x
+ return p
+}
+func (x Days) String() string {
+ return proto.EnumName(Days_name, int32(x))
+}
+func (x *Days) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(Days_value, data, "Days")
+ if err != nil {
+ return err
+ }
+ *x = Days(value)
+ return nil
+}
+
+type Request_Color int32
+
+const (
+ Request_RED Request_Color = 0
+ Request_GREEN Request_Color = 1
+ Request_BLUE Request_Color = 2
+)
+
+var Request_Color_name = map[int32]string{
+ 0: "RED",
+ 1: "GREEN",
+ 2: "BLUE",
+}
+var Request_Color_value = map[string]int32{
+ "RED": 0,
+ "GREEN": 1,
+ "BLUE": 2,
+}
+
+func (x Request_Color) Enum() *Request_Color {
+ p := new(Request_Color)
+ *p = x
+ return p
+}
+func (x Request_Color) String() string {
+ return proto.EnumName(Request_Color_name, int32(x))
+}
+func (x *Request_Color) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(Request_Color_value, data, "Request_Color")
+ if err != nil {
+ return err
+ }
+ *x = Request_Color(value)
+ return nil
+}
+
+type Reply_Entry_Game int32
+
+const (
+ Reply_Entry_FOOTBALL Reply_Entry_Game = 1
+ Reply_Entry_TENNIS Reply_Entry_Game = 2
+)
+
+var Reply_Entry_Game_name = map[int32]string{
+ 1: "FOOTBALL",
+ 2: "TENNIS",
+}
+var Reply_Entry_Game_value = map[string]int32{
+ "FOOTBALL": 1,
+ "TENNIS": 2,
+}
+
+func (x Reply_Entry_Game) Enum() *Reply_Entry_Game {
+ p := new(Reply_Entry_Game)
+ *p = x
+ return p
+}
+func (x Reply_Entry_Game) String() string {
+ return proto.EnumName(Reply_Entry_Game_name, int32(x))
+}
+func (x *Reply_Entry_Game) UnmarshalJSON(data []byte) error {
+ value, err := proto.UnmarshalJSONEnum(Reply_Entry_Game_value, data, "Reply_Entry_Game")
+ if err != nil {
+ return err
+ }
+ *x = Reply_Entry_Game(value)
+ return nil
+}
+
+// This is a message that might be sent somewhere.
+type Request struct {
+ Key []int64 `protobuf:"varint,1,rep,name=key" json:"key,omitempty"`
+ // optional imp.ImportedMessage imported_message = 2;
+ Hue *Request_Color `protobuf:"varint,3,opt,name=hue,enum=my.test.Request_Color" json:"hue,omitempty"`
+ Hat *HatType `protobuf:"varint,4,opt,name=hat,enum=my.test.HatType,def=1" json:"hat,omitempty"`
+ // optional imp.ImportedMessage.Owner owner = 6;
+ Deadline *float32 `protobuf:"fixed32,7,opt,name=deadline,def=inf" json:"deadline,omitempty"`
+ Somegroup *Request_SomeGroup `protobuf:"group,8,opt,name=SomeGroup,json=somegroup" json:"somegroup,omitempty"`
+ // This is a map field. It will generate map[int32]string.
+ NameMapping map[int32]string `protobuf:"bytes,14,rep,name=name_mapping,json=nameMapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ // This is a map field whose value type is a message.
+ MsgMapping map[int64]*Reply `protobuf:"bytes,15,rep,name=msg_mapping,json=msgMapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ Reset_ *int32 `protobuf:"varint,12,opt,name=reset" json:"reset,omitempty"`
+ // This field should not conflict with any getters.
+ GetKey_ *string `protobuf:"bytes,16,opt,name=get_key,json=getKey" json:"get_key,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Request) Reset() { *m = Request{} }
+func (m *Request) String() string { return proto.CompactTextString(m) }
+func (*Request) ProtoMessage() {}
+
+const Default_Request_Hat HatType = HatType_FEDORA
+
+var Default_Request_Deadline float32 = float32(math.Inf(1))
+
+func (m *Request) GetKey() []int64 {
+ if m != nil {
+ return m.Key
+ }
+ return nil
+}
+
+func (m *Request) GetHue() Request_Color {
+ if m != nil && m.Hue != nil {
+ return *m.Hue
+ }
+ return Request_RED
+}
+
+func (m *Request) GetHat() HatType {
+ if m != nil && m.Hat != nil {
+ return *m.Hat
+ }
+ return Default_Request_Hat
+}
+
+func (m *Request) GetDeadline() float32 {
+ if m != nil && m.Deadline != nil {
+ return *m.Deadline
+ }
+ return Default_Request_Deadline
+}
+
+func (m *Request) GetSomegroup() *Request_SomeGroup {
+ if m != nil {
+ return m.Somegroup
+ }
+ return nil
+}
+
+func (m *Request) GetNameMapping() map[int32]string {
+ if m != nil {
+ return m.NameMapping
+ }
+ return nil
+}
+
+func (m *Request) GetMsgMapping() map[int64]*Reply {
+ if m != nil {
+ return m.MsgMapping
+ }
+ return nil
+}
+
+func (m *Request) GetReset_() int32 {
+ if m != nil && m.Reset_ != nil {
+ return *m.Reset_
+ }
+ return 0
+}
+
+func (m *Request) GetGetKey_() string {
+ if m != nil && m.GetKey_ != nil {
+ return *m.GetKey_
+ }
+ return ""
+}
+
+type Request_SomeGroup struct {
+ GroupField *int32 `protobuf:"varint,9,opt,name=group_field,json=groupField" json:"group_field,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Request_SomeGroup) Reset() { *m = Request_SomeGroup{} }
+func (m *Request_SomeGroup) String() string { return proto.CompactTextString(m) }
+func (*Request_SomeGroup) ProtoMessage() {}
+
+func (m *Request_SomeGroup) GetGroupField() int32 {
+ if m != nil && m.GroupField != nil {
+ return *m.GroupField
+ }
+ return 0
+}
+
+type Reply struct {
+ Found []*Reply_Entry `protobuf:"bytes,1,rep,name=found" json:"found,omitempty"`
+ CompactKeys []int32 `protobuf:"varint,2,rep,packed,name=compact_keys,json=compactKeys" json:"compact_keys,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Reply) Reset() { *m = Reply{} }
+func (m *Reply) String() string { return proto.CompactTextString(m) }
+func (*Reply) ProtoMessage() {}
+
+var extRange_Reply = []proto.ExtensionRange{
+ {100, 536870911},
+}
+
+func (*Reply) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_Reply
+}
+
+func (m *Reply) GetFound() []*Reply_Entry {
+ if m != nil {
+ return m.Found
+ }
+ return nil
+}
+
+func (m *Reply) GetCompactKeys() []int32 {
+ if m != nil {
+ return m.CompactKeys
+ }
+ return nil
+}
+
+type Reply_Entry struct {
+ KeyThatNeeds_1234Camel_CasIng *int64 `protobuf:"varint,1,req,name=key_that_needs_1234camel_CasIng,json=keyThatNeeds1234camelCasIng" json:"key_that_needs_1234camel_CasIng,omitempty"`
+ Value *int64 `protobuf:"varint,2,opt,name=value,def=7" json:"value,omitempty"`
+ XMyFieldName_2 *int64 `protobuf:"varint,3,opt,name=_my_field_name_2,json=MyFieldName2" json:"_my_field_name_2,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Reply_Entry) Reset() { *m = Reply_Entry{} }
+func (m *Reply_Entry) String() string { return proto.CompactTextString(m) }
+func (*Reply_Entry) ProtoMessage() {}
+
+const Default_Reply_Entry_Value int64 = 7
+
+func (m *Reply_Entry) GetKeyThatNeeds_1234Camel_CasIng() int64 {
+ if m != nil && m.KeyThatNeeds_1234Camel_CasIng != nil {
+ return *m.KeyThatNeeds_1234Camel_CasIng
+ }
+ return 0
+}
+
+func (m *Reply_Entry) GetValue() int64 {
+ if m != nil && m.Value != nil {
+ return *m.Value
+ }
+ return Default_Reply_Entry_Value
+}
+
+func (m *Reply_Entry) GetXMyFieldName_2() int64 {
+ if m != nil && m.XMyFieldName_2 != nil {
+ return *m.XMyFieldName_2
+ }
+ return 0
+}
+
+type OtherBase struct {
+ Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OtherBase) Reset() { *m = OtherBase{} }
+func (m *OtherBase) String() string { return proto.CompactTextString(m) }
+func (*OtherBase) ProtoMessage() {}
+
+var extRange_OtherBase = []proto.ExtensionRange{
+ {100, 536870911},
+}
+
+func (*OtherBase) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_OtherBase
+}
+
+func (m *OtherBase) GetName() string {
+ if m != nil && m.Name != nil {
+ return *m.Name
+ }
+ return ""
+}
+
+type ReplyExtensions struct {
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *ReplyExtensions) Reset() { *m = ReplyExtensions{} }
+func (m *ReplyExtensions) String() string { return proto.CompactTextString(m) }
+func (*ReplyExtensions) ProtoMessage() {}
+
+var E_ReplyExtensions_Time = &proto.ExtensionDesc{
+ ExtendedType: (*Reply)(nil),
+ ExtensionType: (*float64)(nil),
+ Field: 101,
+ Name: "my.test.ReplyExtensions.time",
+ Tag: "fixed64,101,opt,name=time",
+ Filename: "my_test/test.proto",
+}
+
+var E_ReplyExtensions_Carrot = &proto.ExtensionDesc{
+ ExtendedType: (*Reply)(nil),
+ ExtensionType: (*ReplyExtensions)(nil),
+ Field: 105,
+ Name: "my.test.ReplyExtensions.carrot",
+ Tag: "bytes,105,opt,name=carrot",
+ Filename: "my_test/test.proto",
+}
+
+var E_ReplyExtensions_Donut = &proto.ExtensionDesc{
+ ExtendedType: (*OtherBase)(nil),
+ ExtensionType: (*ReplyExtensions)(nil),
+ Field: 101,
+ Name: "my.test.ReplyExtensions.donut",
+ Tag: "bytes,101,opt,name=donut",
+ Filename: "my_test/test.proto",
+}
+
+type OtherReplyExtensions struct {
+ Key *int32 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OtherReplyExtensions) Reset() { *m = OtherReplyExtensions{} }
+func (m *OtherReplyExtensions) String() string { return proto.CompactTextString(m) }
+func (*OtherReplyExtensions) ProtoMessage() {}
+
+func (m *OtherReplyExtensions) GetKey() int32 {
+ if m != nil && m.Key != nil {
+ return *m.Key
+ }
+ return 0
+}
+
+type OldReply struct {
+ proto.XXX_InternalExtensions `json:"-"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *OldReply) Reset() { *m = OldReply{} }
+func (m *OldReply) String() string { return proto.CompactTextString(m) }
+func (*OldReply) ProtoMessage() {}
+
+func (m *OldReply) Marshal() ([]byte, error) {
+ return proto.MarshalMessageSet(&m.XXX_InternalExtensions)
+}
+func (m *OldReply) Unmarshal(buf []byte) error {
+ return proto.UnmarshalMessageSet(buf, &m.XXX_InternalExtensions)
+}
+func (m *OldReply) MarshalJSON() ([]byte, error) {
+ return proto.MarshalMessageSetJSON(&m.XXX_InternalExtensions)
+}
+func (m *OldReply) UnmarshalJSON(buf []byte) error {
+ return proto.UnmarshalMessageSetJSON(buf, &m.XXX_InternalExtensions)
+}
+
+// ensure OldReply satisfies proto.Marshaler and proto.Unmarshaler
+var _ proto.Marshaler = (*OldReply)(nil)
+var _ proto.Unmarshaler = (*OldReply)(nil)
+
+var extRange_OldReply = []proto.ExtensionRange{
+ {100, 2147483646},
+}
+
+func (*OldReply) ExtensionRangeArray() []proto.ExtensionRange {
+ return extRange_OldReply
+}
+
+type Communique struct {
+ MakeMeCry *bool `protobuf:"varint,1,opt,name=make_me_cry,json=makeMeCry" json:"make_me_cry,omitempty"`
+ // This is a oneof, called "union".
+ //
+ // Types that are valid to be assigned to Union:
+ // *Communique_Number
+ // *Communique_Name
+ // *Communique_Data
+ // *Communique_TempC
+ // *Communique_Height
+ // *Communique_Today
+ // *Communique_Maybe
+ // *Communique_Delta_
+ // *Communique_Msg
+ // *Communique_Somegroup
+ Union isCommunique_Union `protobuf_oneof:"union"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Communique) Reset() { *m = Communique{} }
+func (m *Communique) String() string { return proto.CompactTextString(m) }
+func (*Communique) ProtoMessage() {}
+
+type isCommunique_Union interface {
+ isCommunique_Union()
+}
+
+type Communique_Number struct {
+ Number int32 `protobuf:"varint,5,opt,name=number,oneof"`
+}
+type Communique_Name struct {
+ Name string `protobuf:"bytes,6,opt,name=name,oneof"`
+}
+type Communique_Data struct {
+ Data []byte `protobuf:"bytes,7,opt,name=data,oneof"`
+}
+type Communique_TempC struct {
+ TempC float64 `protobuf:"fixed64,8,opt,name=temp_c,json=tempC,oneof"`
+}
+type Communique_Height struct {
+ Height float32 `protobuf:"fixed32,9,opt,name=height,oneof"`
+}
+type Communique_Today struct {
+ Today Days `protobuf:"varint,10,opt,name=today,enum=my.test.Days,oneof"`
+}
+type Communique_Maybe struct {
+ Maybe bool `protobuf:"varint,11,opt,name=maybe,oneof"`
+}
+type Communique_Delta_ struct {
+ Delta int32 `protobuf:"zigzag32,12,opt,name=delta,oneof"`
+}
+type Communique_Msg struct {
+ Msg *Reply `protobuf:"bytes,13,opt,name=msg,oneof"`
+}
+type Communique_Somegroup struct {
+ Somegroup *Communique_SomeGroup `protobuf:"group,14,opt,name=SomeGroup,json=somegroup,oneof"`
+}
+
+func (*Communique_Number) isCommunique_Union() {}
+func (*Communique_Name) isCommunique_Union() {}
+func (*Communique_Data) isCommunique_Union() {}
+func (*Communique_TempC) isCommunique_Union() {}
+func (*Communique_Height) isCommunique_Union() {}
+func (*Communique_Today) isCommunique_Union() {}
+func (*Communique_Maybe) isCommunique_Union() {}
+func (*Communique_Delta_) isCommunique_Union() {}
+func (*Communique_Msg) isCommunique_Union() {}
+func (*Communique_Somegroup) isCommunique_Union() {}
+
+func (m *Communique) GetUnion() isCommunique_Union {
+ if m != nil {
+ return m.Union
+ }
+ return nil
+}
+
+func (m *Communique) GetMakeMeCry() bool {
+ if m != nil && m.MakeMeCry != nil {
+ return *m.MakeMeCry
+ }
+ return false
+}
+
+func (m *Communique) GetNumber() int32 {
+ if x, ok := m.GetUnion().(*Communique_Number); ok {
+ return x.Number
+ }
+ return 0
+}
+
+func (m *Communique) GetName() string {
+ if x, ok := m.GetUnion().(*Communique_Name); ok {
+ return x.Name
+ }
+ return ""
+}
+
+func (m *Communique) GetData() []byte {
+ if x, ok := m.GetUnion().(*Communique_Data); ok {
+ return x.Data
+ }
+ return nil
+}
+
+func (m *Communique) GetTempC() float64 {
+ if x, ok := m.GetUnion().(*Communique_TempC); ok {
+ return x.TempC
+ }
+ return 0
+}
+
+func (m *Communique) GetHeight() float32 {
+ if x, ok := m.GetUnion().(*Communique_Height); ok {
+ return x.Height
+ }
+ return 0
+}
+
+func (m *Communique) GetToday() Days {
+ if x, ok := m.GetUnion().(*Communique_Today); ok {
+ return x.Today
+ }
+ return Days_MONDAY
+}
+
+func (m *Communique) GetMaybe() bool {
+ if x, ok := m.GetUnion().(*Communique_Maybe); ok {
+ return x.Maybe
+ }
+ return false
+}
+
+func (m *Communique) GetDelta() int32 {
+ if x, ok := m.GetUnion().(*Communique_Delta_); ok {
+ return x.Delta
+ }
+ return 0
+}
+
+func (m *Communique) GetMsg() *Reply {
+ if x, ok := m.GetUnion().(*Communique_Msg); ok {
+ return x.Msg
+ }
+ return nil
+}
+
+func (m *Communique) GetSomegroup() *Communique_SomeGroup {
+ if x, ok := m.GetUnion().(*Communique_Somegroup); ok {
+ return x.Somegroup
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*Communique) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _Communique_OneofMarshaler, _Communique_OneofUnmarshaler, _Communique_OneofSizer, []interface{}{
+ (*Communique_Number)(nil),
+ (*Communique_Name)(nil),
+ (*Communique_Data)(nil),
+ (*Communique_TempC)(nil),
+ (*Communique_Height)(nil),
+ (*Communique_Today)(nil),
+ (*Communique_Maybe)(nil),
+ (*Communique_Delta_)(nil),
+ (*Communique_Msg)(nil),
+ (*Communique_Somegroup)(nil),
+ }
+}
+
+func _Communique_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*Communique)
+ // union
+ switch x := m.Union.(type) {
+ case *Communique_Number:
+ b.EncodeVarint(5<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.Number))
+ case *Communique_Name:
+ b.EncodeVarint(6<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.Name)
+ case *Communique_Data:
+ b.EncodeVarint(7<<3 | proto.WireBytes)
+ b.EncodeRawBytes(x.Data)
+ case *Communique_TempC:
+ b.EncodeVarint(8<<3 | proto.WireFixed64)
+ b.EncodeFixed64(math.Float64bits(x.TempC))
+ case *Communique_Height:
+ b.EncodeVarint(9<<3 | proto.WireFixed32)
+ b.EncodeFixed32(uint64(math.Float32bits(x.Height)))
+ case *Communique_Today:
+ b.EncodeVarint(10<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.Today))
+ case *Communique_Maybe:
+ t := uint64(0)
+ if x.Maybe {
+ t = 1
+ }
+ b.EncodeVarint(11<<3 | proto.WireVarint)
+ b.EncodeVarint(t)
+ case *Communique_Delta_:
+ b.EncodeVarint(12<<3 | proto.WireVarint)
+ b.EncodeZigzag32(uint64(x.Delta))
+ case *Communique_Msg:
+ b.EncodeVarint(13<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.Msg); err != nil {
+ return err
+ }
+ case *Communique_Somegroup:
+ b.EncodeVarint(14<<3 | proto.WireStartGroup)
+ if err := b.Marshal(x.Somegroup); err != nil {
+ return err
+ }
+ b.EncodeVarint(14<<3 | proto.WireEndGroup)
+ case nil:
+ default:
+ return fmt.Errorf("Communique.Union has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _Communique_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*Communique)
+ switch tag {
+ case 5: // union.number
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Communique_Number{int32(x)}
+ return true, err
+ case 6: // union.name
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Union = &Communique_Name{x}
+ return true, err
+ case 7: // union.data
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeRawBytes(true)
+ m.Union = &Communique_Data{x}
+ return true, err
+ case 8: // union.temp_c
+ if wire != proto.WireFixed64 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed64()
+ m.Union = &Communique_TempC{math.Float64frombits(x)}
+ return true, err
+ case 9: // union.height
+ if wire != proto.WireFixed32 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed32()
+ m.Union = &Communique_Height{math.Float32frombits(uint32(x))}
+ return true, err
+ case 10: // union.today
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Communique_Today{Days(x)}
+ return true, err
+ case 11: // union.maybe
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Union = &Communique_Maybe{x != 0}
+ return true, err
+ case 12: // union.delta
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeZigzag32()
+ m.Union = &Communique_Delta_{int32(x)}
+ return true, err
+ case 13: // union.msg
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Reply)
+ err := b.DecodeMessage(msg)
+ m.Union = &Communique_Msg{msg}
+ return true, err
+ case 14: // union.somegroup
+ if wire != proto.WireStartGroup {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Communique_SomeGroup)
+ err := b.DecodeGroup(msg)
+ m.Union = &Communique_Somegroup{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _Communique_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*Communique)
+ // union
+ switch x := m.Union.(type) {
+ case *Communique_Number:
+ n += proto.SizeVarint(5<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.Number))
+ case *Communique_Name:
+ n += proto.SizeVarint(6<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Name)))
+ n += len(x.Name)
+ case *Communique_Data:
+ n += proto.SizeVarint(7<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.Data)))
+ n += len(x.Data)
+ case *Communique_TempC:
+ n += proto.SizeVarint(8<<3 | proto.WireFixed64)
+ n += 8
+ case *Communique_Height:
+ n += proto.SizeVarint(9<<3 | proto.WireFixed32)
+ n += 4
+ case *Communique_Today:
+ n += proto.SizeVarint(10<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.Today))
+ case *Communique_Maybe:
+ n += proto.SizeVarint(11<<3 | proto.WireVarint)
+ n += 1
+ case *Communique_Delta_:
+ n += proto.SizeVarint(12<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64((uint32(x.Delta) << 1) ^ uint32((int32(x.Delta) >> 31))))
+ case *Communique_Msg:
+ s := proto.Size(x.Msg)
+ n += proto.SizeVarint(13<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Communique_Somegroup:
+ n += proto.SizeVarint(14<<3 | proto.WireStartGroup)
+ n += proto.Size(x.Somegroup)
+ n += proto.SizeVarint(14<<3 | proto.WireEndGroup)
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+type Communique_SomeGroup struct {
+ Member *string `protobuf:"bytes,15,opt,name=member" json:"member,omitempty"`
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Communique_SomeGroup) Reset() { *m = Communique_SomeGroup{} }
+func (m *Communique_SomeGroup) String() string { return proto.CompactTextString(m) }
+func (*Communique_SomeGroup) ProtoMessage() {}
+
+func (m *Communique_SomeGroup) GetMember() string {
+ if m != nil && m.Member != nil {
+ return *m.Member
+ }
+ return ""
+}
+
+type Communique_Delta struct {
+ XXX_unrecognized []byte `json:"-"`
+}
+
+func (m *Communique_Delta) Reset() { *m = Communique_Delta{} }
+func (m *Communique_Delta) String() string { return proto.CompactTextString(m) }
+func (*Communique_Delta) ProtoMessage() {}
+
+var E_Tag = &proto.ExtensionDesc{
+ ExtendedType: (*Reply)(nil),
+ ExtensionType: (*string)(nil),
+ Field: 103,
+ Name: "my.test.tag",
+ Tag: "bytes,103,opt,name=tag",
+ Filename: "my_test/test.proto",
+}
+
+var E_Donut = &proto.ExtensionDesc{
+ ExtendedType: (*Reply)(nil),
+ ExtensionType: (*OtherReplyExtensions)(nil),
+ Field: 106,
+ Name: "my.test.donut",
+ Tag: "bytes,106,opt,name=donut",
+ Filename: "my_test/test.proto",
+}
+
+func init() {
+ proto.RegisterType((*Request)(nil), "my.test.Request")
+ proto.RegisterType((*Request_SomeGroup)(nil), "my.test.Request.SomeGroup")
+ proto.RegisterType((*Reply)(nil), "my.test.Reply")
+ proto.RegisterType((*Reply_Entry)(nil), "my.test.Reply.Entry")
+ proto.RegisterType((*OtherBase)(nil), "my.test.OtherBase")
+ proto.RegisterType((*ReplyExtensions)(nil), "my.test.ReplyExtensions")
+ proto.RegisterType((*OtherReplyExtensions)(nil), "my.test.OtherReplyExtensions")
+ proto.RegisterType((*OldReply)(nil), "my.test.OldReply")
+ proto.RegisterType((*Communique)(nil), "my.test.Communique")
+ proto.RegisterType((*Communique_SomeGroup)(nil), "my.test.Communique.SomeGroup")
+ proto.RegisterType((*Communique_Delta)(nil), "my.test.Communique.Delta")
+ proto.RegisterEnum("my.test.HatType", HatType_name, HatType_value)
+ proto.RegisterEnum("my.test.Days", Days_name, Days_value)
+ proto.RegisterEnum("my.test.Request_Color", Request_Color_name, Request_Color_value)
+ proto.RegisterEnum("my.test.Reply_Entry_Game", Reply_Entry_Game_name, Reply_Entry_Game_value)
+ proto.RegisterExtension(E_ReplyExtensions_Time)
+ proto.RegisterExtension(E_ReplyExtensions_Carrot)
+ proto.RegisterExtension(E_ReplyExtensions_Donut)
+ proto.RegisterExtension(E_Tag)
+ proto.RegisterExtension(E_Donut)
+}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.proto
new file mode 100644
index 0000000..8e70946
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/my_test/test.proto
@@ -0,0 +1,156 @@
+// 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.
+
+syntax = "proto2";
+
+// This package holds interesting messages.
+package my.test; // dotted package name
+
+//import "imp.proto";
+import "multi/multi1.proto"; // unused import
+
+enum HatType {
+ // deliberately skipping 0
+ FEDORA = 1;
+ FEZ = 2;
+}
+
+// This enum represents days of the week.
+enum Days {
+ option allow_alias = true;
+
+ MONDAY = 1;
+ TUESDAY = 2;
+ LUNDI = 1; // same value as MONDAY
+}
+
+// This is a message that might be sent somewhere.
+message Request {
+ enum Color {
+ RED = 0;
+ GREEN = 1;
+ BLUE = 2;
+ }
+ repeated int64 key = 1;
+// optional imp.ImportedMessage imported_message = 2;
+ optional Color hue = 3; // no default
+ optional HatType hat = 4 [default=FEDORA];
+// optional imp.ImportedMessage.Owner owner = 6;
+ optional float deadline = 7 [default=inf];
+ optional group SomeGroup = 8 {
+ optional int32 group_field = 9;
+ }
+
+ // These foreign types are in imp2.proto,
+ // which is publicly imported by imp.proto.
+// optional imp.PubliclyImportedMessage pub = 10;
+// optional imp.PubliclyImportedEnum pub_enum = 13 [default=HAIR];
+
+
+ // This is a map field. It will generate map[int32]string.
+ map name_mapping = 14;
+ // This is a map field whose value type is a message.
+ map msg_mapping = 15;
+
+ optional int32 reset = 12;
+ // This field should not conflict with any getters.
+ optional string get_key = 16;
+}
+
+message Reply {
+ message Entry {
+ required int64 key_that_needs_1234camel_CasIng = 1;
+ optional int64 value = 2 [default=7];
+ optional int64 _my_field_name_2 = 3;
+ enum Game {
+ FOOTBALL = 1;
+ TENNIS = 2;
+ }
+ }
+ repeated Entry found = 1;
+ repeated int32 compact_keys = 2 [packed=true];
+ extensions 100 to max;
+}
+
+message OtherBase {
+ optional string name = 1;
+ extensions 100 to max;
+}
+
+message ReplyExtensions {
+ extend Reply {
+ optional double time = 101;
+ optional ReplyExtensions carrot = 105;
+ }
+ extend OtherBase {
+ optional ReplyExtensions donut = 101;
+ }
+}
+
+message OtherReplyExtensions {
+ optional int32 key = 1;
+}
+
+// top-level extension
+extend Reply {
+ optional string tag = 103;
+ optional OtherReplyExtensions donut = 106;
+// optional imp.ImportedMessage elephant = 107; // extend with message from another file.
+}
+
+message OldReply {
+ // Extensions will be encoded in MessageSet wire format.
+ option message_set_wire_format = true;
+ extensions 100 to max;
+}
+
+message Communique {
+ optional bool make_me_cry = 1;
+
+ // This is a oneof, called "union".
+ oneof union {
+ int32 number = 5;
+ string name = 6;
+ bytes data = 7;
+ double temp_c = 8;
+ float height = 9;
+ Days today = 10;
+ bool maybe = 11;
+ sint32 delta = 12; // name will conflict with Delta below
+ Reply msg = 13;
+ group SomeGroup = 14 {
+ optional string member = 15;
+ }
+ }
+
+ message Delta {}
+}
+
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/proto3.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/proto3.proto
new file mode 100644
index 0000000..869b9af
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/protoc-gen-go/testdata/proto3.proto
@@ -0,0 +1,53 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2014 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.
+
+syntax = "proto3";
+
+package proto3;
+
+message Request {
+ enum Flavour {
+ SWEET = 0;
+ SOUR = 1;
+ UMAMI = 2;
+ GOPHERLICIOUS = 3;
+ }
+ string name = 1;
+ repeated int64 key = 2;
+ Flavour taste = 3;
+ Book book = 4;
+ repeated int64 unpacked = 5 [packed=false];
+}
+
+message Book {
+ string title = 1;
+ bytes raw_data = 2;
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any.go b/vendor/github.com/golang/protobuf/ptypes/any.go
new file mode 100644
index 0000000..b2af97f
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/any.go
@@ -0,0 +1,139 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 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 ptypes
+
+// This file implements functions to marshal proto.Message to/from
+// google.protobuf.Any message.
+
+import (
+ "fmt"
+ "reflect"
+ "strings"
+
+ "github.com/golang/protobuf/proto"
+ "github.com/golang/protobuf/ptypes/any"
+)
+
+const googleApis = "type.googleapis.com/"
+
+// AnyMessageName returns the name of the message contained in a google.protobuf.Any message.
+//
+// Note that regular type assertions should be done using the Is
+// function. AnyMessageName is provided for less common use cases like filtering a
+// sequence of Any messages based on a set of allowed message type names.
+func AnyMessageName(any *any.Any) (string, error) {
+ if any == nil {
+ return "", fmt.Errorf("message is nil")
+ }
+ slash := strings.LastIndex(any.TypeUrl, "/")
+ if slash < 0 {
+ return "", fmt.Errorf("message type url %q is invalid", any.TypeUrl)
+ }
+ return any.TypeUrl[slash+1:], nil
+}
+
+// MarshalAny takes the protocol buffer and encodes it into google.protobuf.Any.
+func MarshalAny(pb proto.Message) (*any.Any, error) {
+ value, err := proto.Marshal(pb)
+ if err != nil {
+ return nil, err
+ }
+ return &any.Any{TypeUrl: googleApis + proto.MessageName(pb), Value: value}, nil
+}
+
+// DynamicAny is a value that can be passed to UnmarshalAny to automatically
+// allocate a proto.Message for the type specified in a google.protobuf.Any
+// message. The allocated message is stored in the embedded proto.Message.
+//
+// Example:
+//
+// var x ptypes.DynamicAny
+// if err := ptypes.UnmarshalAny(a, &x); err != nil { ... }
+// fmt.Printf("unmarshaled message: %v", x.Message)
+type DynamicAny struct {
+ proto.Message
+}
+
+// Empty returns a new proto.Message of the type specified in a
+// google.protobuf.Any message. It returns an error if corresponding message
+// type isn't linked in.
+func Empty(any *any.Any) (proto.Message, error) {
+ aname, err := AnyMessageName(any)
+ if err != nil {
+ return nil, err
+ }
+
+ t := proto.MessageType(aname)
+ if t == nil {
+ return nil, fmt.Errorf("any: message type %q isn't linked in", aname)
+ }
+ return reflect.New(t.Elem()).Interface().(proto.Message), nil
+}
+
+// UnmarshalAny parses the protocol buffer representation in a google.protobuf.Any
+// message and places the decoded result in pb. It returns an error if type of
+// contents of Any message does not match type of pb message.
+//
+// pb can be a proto.Message, or a *DynamicAny.
+func UnmarshalAny(any *any.Any, pb proto.Message) error {
+ if d, ok := pb.(*DynamicAny); ok {
+ if d.Message == nil {
+ var err error
+ d.Message, err = Empty(any)
+ if err != nil {
+ return err
+ }
+ }
+ return UnmarshalAny(any, d.Message)
+ }
+
+ aname, err := AnyMessageName(any)
+ if err != nil {
+ return err
+ }
+
+ mname := proto.MessageName(pb)
+ if aname != mname {
+ return fmt.Errorf("mismatched message type: got %q want %q", aname, mname)
+ }
+ return proto.Unmarshal(any.Value, pb)
+}
+
+// Is returns true if any value contains a given message type.
+func Is(any *any.Any, pb proto.Message) bool {
+ aname, err := AnyMessageName(any)
+ if err != nil {
+ return false
+ }
+
+ return aname == proto.MessageName(pb)
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go b/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go
new file mode 100644
index 0000000..f346017
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/any/any.pb.go
@@ -0,0 +1,178 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: google/protobuf/any.proto
+
+/*
+Package any is a generated protocol buffer package.
+
+It is generated from these files:
+ google/protobuf/any.proto
+
+It has these top-level messages:
+ Any
+*/
+package any
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// `Any` contains an arbitrary serialized protocol buffer message along with a
+// URL that describes the type of the serialized message.
+//
+// Protobuf library provides support to pack/unpack Any values in the form
+// of utility functions or additional generated methods of the Any type.
+//
+// Example 1: Pack and unpack a message in C++.
+//
+// Foo foo = ...;
+// Any any;
+// any.PackFrom(foo);
+// ...
+// if (any.UnpackTo(&foo)) {
+// ...
+// }
+//
+// Example 2: Pack and unpack a message in Java.
+//
+// Foo foo = ...;
+// Any any = Any.pack(foo);
+// ...
+// if (any.is(Foo.class)) {
+// foo = any.unpack(Foo.class);
+// }
+//
+// Example 3: Pack and unpack a message in Python.
+//
+// foo = Foo(...)
+// any = Any()
+// any.Pack(foo)
+// ...
+// if any.Is(Foo.DESCRIPTOR):
+// any.Unpack(foo)
+// ...
+//
+// Example 4: Pack and unpack a message in Go
+//
+// foo := &pb.Foo{...}
+// any, err := ptypes.MarshalAny(foo)
+// ...
+// foo := &pb.Foo{}
+// if err := ptypes.UnmarshalAny(any, foo); err != nil {
+// ...
+// }
+//
+// The pack methods provided by protobuf library will by default use
+// 'type.googleapis.com/full.type.name' as the type URL and the unpack
+// methods only use the fully qualified type name after the last '/'
+// in the type URL, for example "foo.bar.com/x/y.z" will yield type
+// name "y.z".
+//
+//
+// JSON
+// ====
+// The JSON representation of an `Any` value uses the regular
+// representation of the deserialized, embedded message, with an
+// additional field `@type` which contains the type URL. Example:
+//
+// package google.profile;
+// message Person {
+// string first_name = 1;
+// string last_name = 2;
+// }
+//
+// {
+// "@type": "type.googleapis.com/google.profile.Person",
+// "firstName": ,
+// "lastName":
+// }
+//
+// If the embedded message type is well-known and has a custom JSON
+// representation, that representation will be embedded adding a field
+// `value` which holds the custom JSON in addition to the `@type`
+// field. Example (for message [google.protobuf.Duration][]):
+//
+// {
+// "@type": "type.googleapis.com/google.protobuf.Duration",
+// "value": "1.212s"
+// }
+//
+type Any struct {
+ // A URL/resource name whose content describes the type of the
+ // serialized protocol buffer message.
+ //
+ // For URLs which use the scheme `http`, `https`, or no scheme, the
+ // following restrictions and interpretations apply:
+ //
+ // * If no scheme is provided, `https` is assumed.
+ // * The last segment of the URL's path must represent the fully
+ // qualified name of the type (as in `path/google.protobuf.Duration`).
+ // The name should be in a canonical form (e.g., leading "." is
+ // not accepted).
+ // * An HTTP GET on the URL must yield a [google.protobuf.Type][]
+ // value in binary format, or produce an error.
+ // * Applications are allowed to cache lookup results based on the
+ // URL, or have them precompiled into a binary to avoid any
+ // lookup. Therefore, binary compatibility needs to be preserved
+ // on changes to types. (Use versioned type names to manage
+ // breaking changes.)
+ //
+ // Schemes other than `http`, `https` (or the empty scheme) might be
+ // used with implementation specific semantics.
+ //
+ TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl" json:"type_url,omitempty"`
+ // Must be a valid serialized protocol buffer of the above specified type.
+ Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *Any) Reset() { *m = Any{} }
+func (m *Any) String() string { return proto.CompactTextString(m) }
+func (*Any) ProtoMessage() {}
+func (*Any) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+func (*Any) XXX_WellKnownType() string { return "Any" }
+
+func (m *Any) GetTypeUrl() string {
+ if m != nil {
+ return m.TypeUrl
+ }
+ return ""
+}
+
+func (m *Any) GetValue() []byte {
+ if m != nil {
+ return m.Value
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*Any)(nil), "google.protobuf.Any")
+}
+
+func init() { proto.RegisterFile("google/protobuf/any.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 185 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4c, 0xcf, 0xcf, 0x4f,
+ 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcc, 0xab, 0xd4,
+ 0x03, 0x73, 0x84, 0xf8, 0x21, 0x52, 0x7a, 0x30, 0x29, 0x25, 0x33, 0x2e, 0x66, 0xc7, 0xbc, 0x4a,
+ 0x21, 0x49, 0x2e, 0x8e, 0x92, 0xca, 0x82, 0xd4, 0xf8, 0xd2, 0xa2, 0x1c, 0x09, 0x46, 0x05, 0x46,
+ 0x0d, 0xce, 0x20, 0x76, 0x10, 0x3f, 0xb4, 0x28, 0x47, 0x48, 0x84, 0x8b, 0xb5, 0x2c, 0x31, 0xa7,
+ 0x34, 0x55, 0x82, 0x49, 0x81, 0x51, 0x83, 0x27, 0x08, 0xc2, 0x71, 0xca, 0xe7, 0x12, 0x4e, 0xce,
+ 0xcf, 0xd5, 0x43, 0x33, 0xce, 0x89, 0xc3, 0x31, 0xaf, 0x32, 0x00, 0xc4, 0x09, 0x60, 0x8c, 0x52,
+ 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc,
+ 0x4b, 0x47, 0xb8, 0xa8, 0x00, 0x64, 0x7a, 0x31, 0xc8, 0x61, 0x8b, 0x98, 0x98, 0xdd, 0x03, 0x9c,
+ 0x56, 0x31, 0xc9, 0xb9, 0x43, 0x8c, 0x0a, 0x80, 0x2a, 0xd1, 0x0b, 0x4f, 0xcd, 0xc9, 0xf1, 0xce,
+ 0xcb, 0x2f, 0xcf, 0x0b, 0x01, 0x29, 0x4d, 0x62, 0x03, 0xeb, 0x35, 0x06, 0x04, 0x00, 0x00, 0xff,
+ 0xff, 0x13, 0xf8, 0xe8, 0x42, 0xdd, 0x00, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any/any.proto b/vendor/github.com/golang/protobuf/ptypes/any/any.proto
new file mode 100644
index 0000000..c748667
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/any/any.proto
@@ -0,0 +1,149 @@
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option go_package = "github.com/golang/protobuf/ptypes/any";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "AnyProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+
+// `Any` contains an arbitrary serialized protocol buffer message along with a
+// URL that describes the type of the serialized message.
+//
+// Protobuf library provides support to pack/unpack Any values in the form
+// of utility functions or additional generated methods of the Any type.
+//
+// Example 1: Pack and unpack a message in C++.
+//
+// Foo foo = ...;
+// Any any;
+// any.PackFrom(foo);
+// ...
+// if (any.UnpackTo(&foo)) {
+// ...
+// }
+//
+// Example 2: Pack and unpack a message in Java.
+//
+// Foo foo = ...;
+// Any any = Any.pack(foo);
+// ...
+// if (any.is(Foo.class)) {
+// foo = any.unpack(Foo.class);
+// }
+//
+// Example 3: Pack and unpack a message in Python.
+//
+// foo = Foo(...)
+// any = Any()
+// any.Pack(foo)
+// ...
+// if any.Is(Foo.DESCRIPTOR):
+// any.Unpack(foo)
+// ...
+//
+// Example 4: Pack and unpack a message in Go
+//
+// foo := &pb.Foo{...}
+// any, err := ptypes.MarshalAny(foo)
+// ...
+// foo := &pb.Foo{}
+// if err := ptypes.UnmarshalAny(any, foo); err != nil {
+// ...
+// }
+//
+// The pack methods provided by protobuf library will by default use
+// 'type.googleapis.com/full.type.name' as the type URL and the unpack
+// methods only use the fully qualified type name after the last '/'
+// in the type URL, for example "foo.bar.com/x/y.z" will yield type
+// name "y.z".
+//
+//
+// JSON
+// ====
+// The JSON representation of an `Any` value uses the regular
+// representation of the deserialized, embedded message, with an
+// additional field `@type` which contains the type URL. Example:
+//
+// package google.profile;
+// message Person {
+// string first_name = 1;
+// string last_name = 2;
+// }
+//
+// {
+// "@type": "type.googleapis.com/google.profile.Person",
+// "firstName": ,
+// "lastName":
+// }
+//
+// If the embedded message type is well-known and has a custom JSON
+// representation, that representation will be embedded adding a field
+// `value` which holds the custom JSON in addition to the `@type`
+// field. Example (for message [google.protobuf.Duration][]):
+//
+// {
+// "@type": "type.googleapis.com/google.protobuf.Duration",
+// "value": "1.212s"
+// }
+//
+message Any {
+ // A URL/resource name whose content describes the type of the
+ // serialized protocol buffer message.
+ //
+ // For URLs which use the scheme `http`, `https`, or no scheme, the
+ // following restrictions and interpretations apply:
+ //
+ // * If no scheme is provided, `https` is assumed.
+ // * The last segment of the URL's path must represent the fully
+ // qualified name of the type (as in `path/google.protobuf.Duration`).
+ // The name should be in a canonical form (e.g., leading "." is
+ // not accepted).
+ // * An HTTP GET on the URL must yield a [google.protobuf.Type][]
+ // value in binary format, or produce an error.
+ // * Applications are allowed to cache lookup results based on the
+ // URL, or have them precompiled into a binary to avoid any
+ // lookup. Therefore, binary compatibility needs to be preserved
+ // on changes to types. (Use versioned type names to manage
+ // breaking changes.)
+ //
+ // Schemes other than `http`, `https` (or the empty scheme) might be
+ // used with implementation specific semantics.
+ //
+ string type_url = 1;
+
+ // Must be a valid serialized protocol buffer of the above specified type.
+ bytes value = 2;
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/any_test.go b/vendor/github.com/golang/protobuf/ptypes/any_test.go
new file mode 100644
index 0000000..ed675b4
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/any_test.go
@@ -0,0 +1,113 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 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 ptypes
+
+import (
+ "testing"
+
+ "github.com/golang/protobuf/proto"
+ pb "github.com/golang/protobuf/protoc-gen-go/descriptor"
+ "github.com/golang/protobuf/ptypes/any"
+)
+
+func TestMarshalUnmarshal(t *testing.T) {
+ orig := &any.Any{Value: []byte("test")}
+
+ packed, err := MarshalAny(orig)
+ if err != nil {
+ t.Errorf("MarshalAny(%+v): got: _, %v exp: _, nil", orig, err)
+ }
+
+ unpacked := &any.Any{}
+ err = UnmarshalAny(packed, unpacked)
+ if err != nil || !proto.Equal(unpacked, orig) {
+ t.Errorf("got: %v, %+v; want nil, %+v", err, unpacked, orig)
+ }
+}
+
+func TestIs(t *testing.T) {
+ a, err := MarshalAny(&pb.FileDescriptorProto{})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if Is(a, &pb.DescriptorProto{}) {
+ t.Error("FileDescriptorProto is not a DescriptorProto, but Is says it is")
+ }
+ if !Is(a, &pb.FileDescriptorProto{}) {
+ t.Error("FileDescriptorProto is indeed a FileDescriptorProto, but Is says it is not")
+ }
+}
+
+func TestIsDifferentUrlPrefixes(t *testing.T) {
+ m := &pb.FileDescriptorProto{}
+ a := &any.Any{TypeUrl: "foo/bar/" + proto.MessageName(m)}
+ if !Is(a, m) {
+ t.Errorf("message with type url %q didn't satisfy Is for type %q", a.TypeUrl, proto.MessageName(m))
+ }
+}
+
+func TestUnmarshalDynamic(t *testing.T) {
+ want := &pb.FileDescriptorProto{Name: proto.String("foo")}
+ a, err := MarshalAny(want)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got DynamicAny
+ if err := UnmarshalAny(a, &got); err != nil {
+ t.Fatal(err)
+ }
+ if !proto.Equal(got.Message, want) {
+ t.Errorf("invalid result from UnmarshalAny, got %q want %q", got.Message, want)
+ }
+}
+
+func TestEmpty(t *testing.T) {
+ want := &pb.FileDescriptorProto{}
+ a, err := MarshalAny(want)
+ if err != nil {
+ t.Fatal(err)
+ }
+ got, err := Empty(a)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !proto.Equal(got, want) {
+ t.Errorf("unequal empty message, got %q, want %q", got, want)
+ }
+
+ // that's a valid type_url for a message which shouldn't be linked into this
+ // test binary. We want an error.
+ a.TypeUrl = "type.googleapis.com/google.protobuf.FieldMask"
+ if _, err := Empty(a); err == nil {
+ t.Errorf("got no error for an attempt to create a message of type %q, which shouldn't be linked in", a.TypeUrl)
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/doc.go b/vendor/github.com/golang/protobuf/ptypes/doc.go
new file mode 100644
index 0000000..c0d595d
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/doc.go
@@ -0,0 +1,35 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 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 ptypes contains code for interacting with well-known types.
+*/
+package ptypes
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration.go b/vendor/github.com/golang/protobuf/ptypes/duration.go
new file mode 100644
index 0000000..65cb0f8
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/duration.go
@@ -0,0 +1,102 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 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 ptypes
+
+// This file implements conversions between google.protobuf.Duration
+// and time.Duration.
+
+import (
+ "errors"
+ "fmt"
+ "time"
+
+ durpb "github.com/golang/protobuf/ptypes/duration"
+)
+
+const (
+ // Range of a durpb.Duration in seconds, as specified in
+ // google/protobuf/duration.proto. This is about 10,000 years in seconds.
+ maxSeconds = int64(10000 * 365.25 * 24 * 60 * 60)
+ minSeconds = -maxSeconds
+)
+
+// validateDuration determines whether the durpb.Duration is valid according to the
+// definition in google/protobuf/duration.proto. A valid durpb.Duration
+// may still be too large to fit into a time.Duration (the range of durpb.Duration
+// is about 10,000 years, and the range of time.Duration is about 290).
+func validateDuration(d *durpb.Duration) error {
+ if d == nil {
+ return errors.New("duration: nil Duration")
+ }
+ if d.Seconds < minSeconds || d.Seconds > maxSeconds {
+ return fmt.Errorf("duration: %v: seconds out of range", d)
+ }
+ if d.Nanos <= -1e9 || d.Nanos >= 1e9 {
+ return fmt.Errorf("duration: %v: nanos out of range", d)
+ }
+ // Seconds and Nanos must have the same sign, unless d.Nanos is zero.
+ if (d.Seconds < 0 && d.Nanos > 0) || (d.Seconds > 0 && d.Nanos < 0) {
+ return fmt.Errorf("duration: %v: seconds and nanos have different signs", d)
+ }
+ return nil
+}
+
+// Duration converts a durpb.Duration to a time.Duration. Duration
+// returns an error if the durpb.Duration is invalid or is too large to be
+// represented in a time.Duration.
+func Duration(p *durpb.Duration) (time.Duration, error) {
+ if err := validateDuration(p); err != nil {
+ return 0, err
+ }
+ d := time.Duration(p.Seconds) * time.Second
+ if int64(d/time.Second) != p.Seconds {
+ return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p)
+ }
+ if p.Nanos != 0 {
+ d += time.Duration(p.Nanos)
+ if (d < 0) != (p.Nanos < 0) {
+ return 0, fmt.Errorf("duration: %v is out of range for time.Duration", p)
+ }
+ }
+ return d, nil
+}
+
+// DurationProto converts a time.Duration to a durpb.Duration.
+func DurationProto(d time.Duration) *durpb.Duration {
+ nanos := d.Nanoseconds()
+ secs := nanos / 1e9
+ nanos -= secs * 1e9
+ return &durpb.Duration{
+ Seconds: secs,
+ Nanos: int32(nanos),
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go b/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go
new file mode 100644
index 0000000..b2410a0
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/duration/duration.pb.go
@@ -0,0 +1,144 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: google/protobuf/duration.proto
+
+/*
+Package duration is a generated protocol buffer package.
+
+It is generated from these files:
+ google/protobuf/duration.proto
+
+It has these top-level messages:
+ Duration
+*/
+package duration
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// A Duration represents a signed, fixed-length span of time represented
+// as a count of seconds and fractions of seconds at nanosecond
+// resolution. It is independent of any calendar and concepts like "day"
+// or "month". It is related to Timestamp in that the difference between
+// two Timestamp values is a Duration and it can be added or subtracted
+// from a Timestamp. Range is approximately +-10,000 years.
+//
+// # Examples
+//
+// Example 1: Compute Duration from two Timestamps in pseudo code.
+//
+// Timestamp start = ...;
+// Timestamp end = ...;
+// Duration duration = ...;
+//
+// duration.seconds = end.seconds - start.seconds;
+// duration.nanos = end.nanos - start.nanos;
+//
+// if (duration.seconds < 0 && duration.nanos > 0) {
+// duration.seconds += 1;
+// duration.nanos -= 1000000000;
+// } else if (durations.seconds > 0 && duration.nanos < 0) {
+// duration.seconds -= 1;
+// duration.nanos += 1000000000;
+// }
+//
+// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
+//
+// Timestamp start = ...;
+// Duration duration = ...;
+// Timestamp end = ...;
+//
+// end.seconds = start.seconds + duration.seconds;
+// end.nanos = start.nanos + duration.nanos;
+//
+// if (end.nanos < 0) {
+// end.seconds -= 1;
+// end.nanos += 1000000000;
+// } else if (end.nanos >= 1000000000) {
+// end.seconds += 1;
+// end.nanos -= 1000000000;
+// }
+//
+// Example 3: Compute Duration from datetime.timedelta in Python.
+//
+// td = datetime.timedelta(days=3, minutes=10)
+// duration = Duration()
+// duration.FromTimedelta(td)
+//
+// # JSON Mapping
+//
+// In JSON format, the Duration type is encoded as a string rather than an
+// object, where the string ends in the suffix "s" (indicating seconds) and
+// is preceded by the number of seconds, with nanoseconds expressed as
+// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
+// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
+// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
+// microsecond should be expressed in JSON format as "3.000001s".
+//
+//
+type Duration struct {
+ // Signed seconds of the span of time. Must be from -315,576,000,000
+ // to +315,576,000,000 inclusive. Note: these bounds are computed from:
+ // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
+ Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"`
+ // Signed fractions of a second at nanosecond resolution of the span
+ // of time. Durations less than one second are represented with a 0
+ // `seconds` field and a positive or negative `nanos` field. For durations
+ // of one second or more, a non-zero value for the `nanos` field must be
+ // of the same sign as the `seconds` field. Must be from -999,999,999
+ // to +999,999,999 inclusive.
+ Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"`
+}
+
+func (m *Duration) Reset() { *m = Duration{} }
+func (m *Duration) String() string { return proto.CompactTextString(m) }
+func (*Duration) ProtoMessage() {}
+func (*Duration) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+func (*Duration) XXX_WellKnownType() string { return "Duration" }
+
+func (m *Duration) GetSeconds() int64 {
+ if m != nil {
+ return m.Seconds
+ }
+ return 0
+}
+
+func (m *Duration) GetNanos() int32 {
+ if m != nil {
+ return m.Nanos
+ }
+ return 0
+}
+
+func init() {
+ proto.RegisterType((*Duration)(nil), "google.protobuf.Duration")
+}
+
+func init() { proto.RegisterFile("google/protobuf/duration.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 190 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f,
+ 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0x29, 0x2d, 0x4a,
+ 0x2c, 0xc9, 0xcc, 0xcf, 0xd3, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0x56,
+ 0x5c, 0x1c, 0x2e, 0x50, 0x25, 0x42, 0x12, 0x5c, 0xec, 0xc5, 0xa9, 0xc9, 0xf9, 0x79, 0x29, 0xc5,
+ 0x12, 0x8c, 0x0a, 0x8c, 0x1a, 0xcc, 0x41, 0x30, 0xae, 0x90, 0x08, 0x17, 0x6b, 0x5e, 0x62, 0x5e,
+ 0x7e, 0xb1, 0x04, 0x93, 0x02, 0xa3, 0x06, 0x6b, 0x10, 0x84, 0xe3, 0x54, 0xc3, 0x25, 0x9c, 0x9c,
+ 0x9f, 0xab, 0x87, 0x66, 0xa4, 0x13, 0x2f, 0xcc, 0xc0, 0x00, 0x90, 0x48, 0x00, 0x63, 0x94, 0x56,
+ 0x7a, 0x66, 0x49, 0x46, 0x69, 0x92, 0x5e, 0x72, 0x7e, 0xae, 0x7e, 0x7a, 0x7e, 0x4e, 0x62, 0x5e,
+ 0x3a, 0xc2, 0x7d, 0x05, 0x25, 0x95, 0x05, 0xa9, 0xc5, 0x70, 0x67, 0xfe, 0x60, 0x64, 0x5c, 0xc4,
+ 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e, 0x00, 0x54, 0xa9, 0x5e, 0x78,
+ 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b, 0x12, 0x1b, 0xd8, 0x0c, 0x63,
+ 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0xdc, 0x84, 0x30, 0xff, 0xf3, 0x00, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto b/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto
new file mode 100644
index 0000000..975fce4
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/duration/duration.proto
@@ -0,0 +1,117 @@
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option cc_enable_arenas = true;
+option go_package = "github.com/golang/protobuf/ptypes/duration";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "DurationProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+
+// A Duration represents a signed, fixed-length span of time represented
+// as a count of seconds and fractions of seconds at nanosecond
+// resolution. It is independent of any calendar and concepts like "day"
+// or "month". It is related to Timestamp in that the difference between
+// two Timestamp values is a Duration and it can be added or subtracted
+// from a Timestamp. Range is approximately +-10,000 years.
+//
+// # Examples
+//
+// Example 1: Compute Duration from two Timestamps in pseudo code.
+//
+// Timestamp start = ...;
+// Timestamp end = ...;
+// Duration duration = ...;
+//
+// duration.seconds = end.seconds - start.seconds;
+// duration.nanos = end.nanos - start.nanos;
+//
+// if (duration.seconds < 0 && duration.nanos > 0) {
+// duration.seconds += 1;
+// duration.nanos -= 1000000000;
+// } else if (durations.seconds > 0 && duration.nanos < 0) {
+// duration.seconds -= 1;
+// duration.nanos += 1000000000;
+// }
+//
+// Example 2: Compute Timestamp from Timestamp + Duration in pseudo code.
+//
+// Timestamp start = ...;
+// Duration duration = ...;
+// Timestamp end = ...;
+//
+// end.seconds = start.seconds + duration.seconds;
+// end.nanos = start.nanos + duration.nanos;
+//
+// if (end.nanos < 0) {
+// end.seconds -= 1;
+// end.nanos += 1000000000;
+// } else if (end.nanos >= 1000000000) {
+// end.seconds += 1;
+// end.nanos -= 1000000000;
+// }
+//
+// Example 3: Compute Duration from datetime.timedelta in Python.
+//
+// td = datetime.timedelta(days=3, minutes=10)
+// duration = Duration()
+// duration.FromTimedelta(td)
+//
+// # JSON Mapping
+//
+// In JSON format, the Duration type is encoded as a string rather than an
+// object, where the string ends in the suffix "s" (indicating seconds) and
+// is preceded by the number of seconds, with nanoseconds expressed as
+// fractional seconds. For example, 3 seconds with 0 nanoseconds should be
+// encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should
+// be expressed in JSON format as "3.000000001s", and 3 seconds and 1
+// microsecond should be expressed in JSON format as "3.000001s".
+//
+//
+message Duration {
+
+ // Signed seconds of the span of time. Must be from -315,576,000,000
+ // to +315,576,000,000 inclusive. Note: these bounds are computed from:
+ // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years
+ int64 seconds = 1;
+
+ // Signed fractions of a second at nanosecond resolution of the span
+ // of time. Durations less than one second are represented with a 0
+ // `seconds` field and a positive or negative `nanos` field. For durations
+ // of one second or more, a non-zero value for the `nanos` field must be
+ // of the same sign as the `seconds` field. Must be from -999,999,999
+ // to +999,999,999 inclusive.
+ int32 nanos = 2;
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/duration_test.go b/vendor/github.com/golang/protobuf/ptypes/duration_test.go
new file mode 100644
index 0000000..e00491a
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/duration_test.go
@@ -0,0 +1,121 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 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 ptypes
+
+import (
+ "math"
+ "testing"
+ "time"
+
+ "github.com/golang/protobuf/proto"
+ durpb "github.com/golang/protobuf/ptypes/duration"
+)
+
+const (
+ minGoSeconds = math.MinInt64 / int64(1e9)
+ maxGoSeconds = math.MaxInt64 / int64(1e9)
+)
+
+var durationTests = []struct {
+ proto *durpb.Duration
+ isValid bool
+ inRange bool
+ dur time.Duration
+}{
+ // The zero duration.
+ {&durpb.Duration{Seconds: 0, Nanos: 0}, true, true, 0},
+ // Some ordinary non-zero durations.
+ {&durpb.Duration{Seconds: 100, Nanos: 0}, true, true, 100 * time.Second},
+ {&durpb.Duration{Seconds: -100, Nanos: 0}, true, true, -100 * time.Second},
+ {&durpb.Duration{Seconds: 100, Nanos: 987}, true, true, 100*time.Second + 987},
+ {&durpb.Duration{Seconds: -100, Nanos: -987}, true, true, -(100*time.Second + 987)},
+ // The largest duration representable in Go.
+ {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, true, math.MaxInt64},
+ // The smallest duration representable in Go.
+ {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, true, math.MinInt64},
+ {nil, false, false, 0},
+ {&durpb.Duration{Seconds: -100, Nanos: 987}, false, false, 0},
+ {&durpb.Duration{Seconds: 100, Nanos: -987}, false, false, 0},
+ {&durpb.Duration{Seconds: math.MinInt64, Nanos: 0}, false, false, 0},
+ {&durpb.Duration{Seconds: math.MaxInt64, Nanos: 0}, false, false, 0},
+ // The largest valid duration.
+ {&durpb.Duration{Seconds: maxSeconds, Nanos: 1e9 - 1}, true, false, 0},
+ // The smallest valid duration.
+ {&durpb.Duration{Seconds: minSeconds, Nanos: -(1e9 - 1)}, true, false, 0},
+ // The smallest invalid duration above the valid range.
+ {&durpb.Duration{Seconds: maxSeconds + 1, Nanos: 0}, false, false, 0},
+ // The largest invalid duration below the valid range.
+ {&durpb.Duration{Seconds: minSeconds - 1, Nanos: -(1e9 - 1)}, false, false, 0},
+ // One nanosecond past the largest duration representable in Go.
+ {&durpb.Duration{Seconds: maxGoSeconds, Nanos: int32(math.MaxInt64-1e9*maxGoSeconds) + 1}, true, false, 0},
+ // One nanosecond past the smallest duration representable in Go.
+ {&durpb.Duration{Seconds: minGoSeconds, Nanos: int32(math.MinInt64-1e9*minGoSeconds) - 1}, true, false, 0},
+ // One second past the largest duration representable in Go.
+ {&durpb.Duration{Seconds: maxGoSeconds + 1, Nanos: int32(math.MaxInt64 - 1e9*maxGoSeconds)}, true, false, 0},
+ // One second past the smallest duration representable in Go.
+ {&durpb.Duration{Seconds: minGoSeconds - 1, Nanos: int32(math.MinInt64 - 1e9*minGoSeconds)}, true, false, 0},
+}
+
+func TestValidateDuration(t *testing.T) {
+ for _, test := range durationTests {
+ err := validateDuration(test.proto)
+ gotValid := (err == nil)
+ if gotValid != test.isValid {
+ t.Errorf("validateDuration(%v) = %t, want %t", test.proto, gotValid, test.isValid)
+ }
+ }
+}
+
+func TestDuration(t *testing.T) {
+ for _, test := range durationTests {
+ got, err := Duration(test.proto)
+ gotOK := (err == nil)
+ wantOK := test.isValid && test.inRange
+ if gotOK != wantOK {
+ t.Errorf("Duration(%v) ok = %t, want %t", test.proto, gotOK, wantOK)
+ }
+ if err == nil && got != test.dur {
+ t.Errorf("Duration(%v) = %v, want %v", test.proto, got, test.dur)
+ }
+ }
+}
+
+func TestDurationProto(t *testing.T) {
+ for _, test := range durationTests {
+ if test.isValid && test.inRange {
+ got := DurationProto(test.dur)
+ if !proto.Equal(got, test.proto) {
+ t.Errorf("DurationProto(%v) = %v, want %v", test.dur, got, test.proto)
+ }
+ }
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go b/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go
new file mode 100644
index 0000000..e877b72
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go
@@ -0,0 +1,66 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: google/protobuf/empty.proto
+
+/*
+Package empty is a generated protocol buffer package.
+
+It is generated from these files:
+ google/protobuf/empty.proto
+
+It has these top-level messages:
+ Empty
+*/
+package empty
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// A generic empty message that you can re-use to avoid defining duplicated
+// empty messages in your APIs. A typical example is to use it as the request
+// or the response type of an API method. For instance:
+//
+// service Foo {
+// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+// }
+//
+// The JSON representation for `Empty` is empty JSON object `{}`.
+type Empty struct {
+}
+
+func (m *Empty) Reset() { *m = Empty{} }
+func (m *Empty) String() string { return proto.CompactTextString(m) }
+func (*Empty) ProtoMessage() {}
+func (*Empty) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+func (*Empty) XXX_WellKnownType() string { return "Empty" }
+
+func init() {
+ proto.RegisterType((*Empty)(nil), "google.protobuf.Empty")
+}
+
+func init() { proto.RegisterFile("google/protobuf/empty.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 148 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4e, 0xcf, 0xcf, 0x4f,
+ 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x4f, 0xcd, 0x2d, 0x28,
+ 0xa9, 0xd4, 0x03, 0x73, 0x85, 0xf8, 0x21, 0x92, 0x7a, 0x30, 0x49, 0x25, 0x76, 0x2e, 0x56, 0x57,
+ 0x90, 0xbc, 0x53, 0x19, 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0xbc, 0x13, 0x17, 0x58, 0x36,
+ 0x00, 0xc4, 0x0d, 0x60, 0x8c, 0x52, 0x4f, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf,
+ 0xd5, 0x4f, 0xcf, 0xcf, 0x49, 0xcc, 0x4b, 0x47, 0x58, 0x53, 0x50, 0x52, 0x59, 0x90, 0x5a, 0x0c,
+ 0xb1, 0xed, 0x07, 0x23, 0xe3, 0x22, 0x26, 0x66, 0xf7, 0x00, 0xa7, 0x55, 0x4c, 0x72, 0xee, 0x10,
+ 0x13, 0x03, 0xa0, 0xea, 0xf4, 0xc2, 0x53, 0x73, 0x72, 0xbc, 0xf3, 0xf2, 0xcb, 0xf3, 0x42, 0x40,
+ 0xea, 0x93, 0xd8, 0xc0, 0x06, 0x18, 0x03, 0x02, 0x00, 0x00, 0xff, 0xff, 0x64, 0xd4, 0xb3, 0xa6,
+ 0xb7, 0x00, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/empty/empty.proto b/vendor/github.com/golang/protobuf/ptypes/empty/empty.proto
new file mode 100644
index 0000000..03cacd2
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/empty/empty.proto
@@ -0,0 +1,52 @@
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option go_package = "github.com/golang/protobuf/ptypes/empty";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "EmptyProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+option cc_enable_arenas = true;
+
+// A generic empty message that you can re-use to avoid defining duplicated
+// empty messages in your APIs. A typical example is to use it as the request
+// or the response type of an API method. For instance:
+//
+// service Foo {
+// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
+// }
+//
+// The JSON representation for `Empty` is empty JSON object `{}`.
+message Empty {}
diff --git a/vendor/github.com/golang/protobuf/ptypes/regen.sh b/vendor/github.com/golang/protobuf/ptypes/regen.sh
new file mode 100755
index 0000000..b50a941
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/regen.sh
@@ -0,0 +1,43 @@
+#!/bin/bash -e
+#
+# This script fetches and rebuilds the "well-known types" protocol buffers.
+# To run this you will need protoc and goprotobuf installed;
+# see https://github.com/golang/protobuf for instructions.
+# You also need Go and Git installed.
+
+PKG=github.com/golang/protobuf/ptypes
+UPSTREAM=https://github.com/google/protobuf
+UPSTREAM_SUBDIR=src/google/protobuf
+PROTO_FILES=(any duration empty struct timestamp wrappers)
+
+function die() {
+ echo 1>&2 $*
+ exit 1
+}
+
+# Sanity check that the right tools are accessible.
+for tool in go git protoc protoc-gen-go; do
+ q=$(which $tool) || die "didn't find $tool"
+ echo 1>&2 "$tool: $q"
+done
+
+tmpdir=$(mktemp -d -t regen-wkt.XXXXXX)
+trap 'rm -rf $tmpdir' EXIT
+
+echo -n 1>&2 "finding package dir... "
+pkgdir=$(go list -f '{{.Dir}}' $PKG)
+echo 1>&2 $pkgdir
+base=$(echo $pkgdir | sed "s,/$PKG\$,,")
+echo 1>&2 "base: $base"
+cd "$base"
+
+echo 1>&2 "fetching latest protos... "
+git clone -q $UPSTREAM $tmpdir
+
+for file in ${PROTO_FILES[@]}; do
+ echo 1>&2 "* $file"
+ protoc --go_out=. -I$tmpdir/src $tmpdir/src/google/protobuf/$file.proto || die
+ cp $tmpdir/src/google/protobuf/$file.proto $PKG/$file
+done
+
+echo 1>&2 "All OK"
diff --git a/vendor/github.com/golang/protobuf/ptypes/struct/struct.pb.go b/vendor/github.com/golang/protobuf/ptypes/struct/struct.pb.go
new file mode 100644
index 0000000..4cfe608
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/struct/struct.pb.go
@@ -0,0 +1,380 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: google/protobuf/struct.proto
+
+/*
+Package structpb is a generated protocol buffer package.
+
+It is generated from these files:
+ google/protobuf/struct.proto
+
+It has these top-level messages:
+ Struct
+ Value
+ ListValue
+*/
+package structpb
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// `NullValue` is a singleton enumeration to represent the null value for the
+// `Value` type union.
+//
+// The JSON representation for `NullValue` is JSON `null`.
+type NullValue int32
+
+const (
+ // Null value.
+ NullValue_NULL_VALUE NullValue = 0
+)
+
+var NullValue_name = map[int32]string{
+ 0: "NULL_VALUE",
+}
+var NullValue_value = map[string]int32{
+ "NULL_VALUE": 0,
+}
+
+func (x NullValue) String() string {
+ return proto.EnumName(NullValue_name, int32(x))
+}
+func (NullValue) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+func (NullValue) XXX_WellKnownType() string { return "NullValue" }
+
+// `Struct` represents a structured data value, consisting of fields
+// which map to dynamically typed values. In some languages, `Struct`
+// might be supported by a native representation. For example, in
+// scripting languages like JS a struct is represented as an
+// object. The details of that representation are described together
+// with the proto support for the language.
+//
+// The JSON representation for `Struct` is JSON object.
+type Struct struct {
+ // Unordered map of dynamically typed values.
+ Fields map[string]*Value `protobuf:"bytes,1,rep,name=fields" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+}
+
+func (m *Struct) Reset() { *m = Struct{} }
+func (m *Struct) String() string { return proto.CompactTextString(m) }
+func (*Struct) ProtoMessage() {}
+func (*Struct) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+func (*Struct) XXX_WellKnownType() string { return "Struct" }
+
+func (m *Struct) GetFields() map[string]*Value {
+ if m != nil {
+ return m.Fields
+ }
+ return nil
+}
+
+// `Value` represents a dynamically typed value which can be either
+// null, a number, a string, a boolean, a recursive struct value, or a
+// list of values. A producer of value is expected to set one of that
+// variants, absence of any variant indicates an error.
+//
+// The JSON representation for `Value` is JSON value.
+type Value struct {
+ // The kind of value.
+ //
+ // Types that are valid to be assigned to Kind:
+ // *Value_NullValue
+ // *Value_NumberValue
+ // *Value_StringValue
+ // *Value_BoolValue
+ // *Value_StructValue
+ // *Value_ListValue
+ Kind isValue_Kind `protobuf_oneof:"kind"`
+}
+
+func (m *Value) Reset() { *m = Value{} }
+func (m *Value) String() string { return proto.CompactTextString(m) }
+func (*Value) ProtoMessage() {}
+func (*Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+func (*Value) XXX_WellKnownType() string { return "Value" }
+
+type isValue_Kind interface {
+ isValue_Kind()
+}
+
+type Value_NullValue struct {
+ NullValue NullValue `protobuf:"varint,1,opt,name=null_value,json=nullValue,enum=google.protobuf.NullValue,oneof"`
+}
+type Value_NumberValue struct {
+ NumberValue float64 `protobuf:"fixed64,2,opt,name=number_value,json=numberValue,oneof"`
+}
+type Value_StringValue struct {
+ StringValue string `protobuf:"bytes,3,opt,name=string_value,json=stringValue,oneof"`
+}
+type Value_BoolValue struct {
+ BoolValue bool `protobuf:"varint,4,opt,name=bool_value,json=boolValue,oneof"`
+}
+type Value_StructValue struct {
+ StructValue *Struct `protobuf:"bytes,5,opt,name=struct_value,json=structValue,oneof"`
+}
+type Value_ListValue struct {
+ ListValue *ListValue `protobuf:"bytes,6,opt,name=list_value,json=listValue,oneof"`
+}
+
+func (*Value_NullValue) isValue_Kind() {}
+func (*Value_NumberValue) isValue_Kind() {}
+func (*Value_StringValue) isValue_Kind() {}
+func (*Value_BoolValue) isValue_Kind() {}
+func (*Value_StructValue) isValue_Kind() {}
+func (*Value_ListValue) isValue_Kind() {}
+
+func (m *Value) GetKind() isValue_Kind {
+ if m != nil {
+ return m.Kind
+ }
+ return nil
+}
+
+func (m *Value) GetNullValue() NullValue {
+ if x, ok := m.GetKind().(*Value_NullValue); ok {
+ return x.NullValue
+ }
+ return NullValue_NULL_VALUE
+}
+
+func (m *Value) GetNumberValue() float64 {
+ if x, ok := m.GetKind().(*Value_NumberValue); ok {
+ return x.NumberValue
+ }
+ return 0
+}
+
+func (m *Value) GetStringValue() string {
+ if x, ok := m.GetKind().(*Value_StringValue); ok {
+ return x.StringValue
+ }
+ return ""
+}
+
+func (m *Value) GetBoolValue() bool {
+ if x, ok := m.GetKind().(*Value_BoolValue); ok {
+ return x.BoolValue
+ }
+ return false
+}
+
+func (m *Value) GetStructValue() *Struct {
+ if x, ok := m.GetKind().(*Value_StructValue); ok {
+ return x.StructValue
+ }
+ return nil
+}
+
+func (m *Value) GetListValue() *ListValue {
+ if x, ok := m.GetKind().(*Value_ListValue); ok {
+ return x.ListValue
+ }
+ return nil
+}
+
+// XXX_OneofFuncs is for the internal use of the proto package.
+func (*Value) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
+ return _Value_OneofMarshaler, _Value_OneofUnmarshaler, _Value_OneofSizer, []interface{}{
+ (*Value_NullValue)(nil),
+ (*Value_NumberValue)(nil),
+ (*Value_StringValue)(nil),
+ (*Value_BoolValue)(nil),
+ (*Value_StructValue)(nil),
+ (*Value_ListValue)(nil),
+ }
+}
+
+func _Value_OneofMarshaler(msg proto.Message, b *proto.Buffer) error {
+ m := msg.(*Value)
+ // kind
+ switch x := m.Kind.(type) {
+ case *Value_NullValue:
+ b.EncodeVarint(1<<3 | proto.WireVarint)
+ b.EncodeVarint(uint64(x.NullValue))
+ case *Value_NumberValue:
+ b.EncodeVarint(2<<3 | proto.WireFixed64)
+ b.EncodeFixed64(math.Float64bits(x.NumberValue))
+ case *Value_StringValue:
+ b.EncodeVarint(3<<3 | proto.WireBytes)
+ b.EncodeStringBytes(x.StringValue)
+ case *Value_BoolValue:
+ t := uint64(0)
+ if x.BoolValue {
+ t = 1
+ }
+ b.EncodeVarint(4<<3 | proto.WireVarint)
+ b.EncodeVarint(t)
+ case *Value_StructValue:
+ b.EncodeVarint(5<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.StructValue); err != nil {
+ return err
+ }
+ case *Value_ListValue:
+ b.EncodeVarint(6<<3 | proto.WireBytes)
+ if err := b.EncodeMessage(x.ListValue); err != nil {
+ return err
+ }
+ case nil:
+ default:
+ return fmt.Errorf("Value.Kind has unexpected type %T", x)
+ }
+ return nil
+}
+
+func _Value_OneofUnmarshaler(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error) {
+ m := msg.(*Value)
+ switch tag {
+ case 1: // kind.null_value
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Kind = &Value_NullValue{NullValue(x)}
+ return true, err
+ case 2: // kind.number_value
+ if wire != proto.WireFixed64 {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeFixed64()
+ m.Kind = &Value_NumberValue{math.Float64frombits(x)}
+ return true, err
+ case 3: // kind.string_value
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeStringBytes()
+ m.Kind = &Value_StringValue{x}
+ return true, err
+ case 4: // kind.bool_value
+ if wire != proto.WireVarint {
+ return true, proto.ErrInternalBadWireType
+ }
+ x, err := b.DecodeVarint()
+ m.Kind = &Value_BoolValue{x != 0}
+ return true, err
+ case 5: // kind.struct_value
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(Struct)
+ err := b.DecodeMessage(msg)
+ m.Kind = &Value_StructValue{msg}
+ return true, err
+ case 6: // kind.list_value
+ if wire != proto.WireBytes {
+ return true, proto.ErrInternalBadWireType
+ }
+ msg := new(ListValue)
+ err := b.DecodeMessage(msg)
+ m.Kind = &Value_ListValue{msg}
+ return true, err
+ default:
+ return false, nil
+ }
+}
+
+func _Value_OneofSizer(msg proto.Message) (n int) {
+ m := msg.(*Value)
+ // kind
+ switch x := m.Kind.(type) {
+ case *Value_NullValue:
+ n += proto.SizeVarint(1<<3 | proto.WireVarint)
+ n += proto.SizeVarint(uint64(x.NullValue))
+ case *Value_NumberValue:
+ n += proto.SizeVarint(2<<3 | proto.WireFixed64)
+ n += 8
+ case *Value_StringValue:
+ n += proto.SizeVarint(3<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(len(x.StringValue)))
+ n += len(x.StringValue)
+ case *Value_BoolValue:
+ n += proto.SizeVarint(4<<3 | proto.WireVarint)
+ n += 1
+ case *Value_StructValue:
+ s := proto.Size(x.StructValue)
+ n += proto.SizeVarint(5<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case *Value_ListValue:
+ s := proto.Size(x.ListValue)
+ n += proto.SizeVarint(6<<3 | proto.WireBytes)
+ n += proto.SizeVarint(uint64(s))
+ n += s
+ case nil:
+ default:
+ panic(fmt.Sprintf("proto: unexpected type %T in oneof", x))
+ }
+ return n
+}
+
+// `ListValue` is a wrapper around a repeated field of values.
+//
+// The JSON representation for `ListValue` is JSON array.
+type ListValue struct {
+ // Repeated field of dynamically typed values.
+ Values []*Value `protobuf:"bytes,1,rep,name=values" json:"values,omitempty"`
+}
+
+func (m *ListValue) Reset() { *m = ListValue{} }
+func (m *ListValue) String() string { return proto.CompactTextString(m) }
+func (*ListValue) ProtoMessage() {}
+func (*ListValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
+func (*ListValue) XXX_WellKnownType() string { return "ListValue" }
+
+func (m *ListValue) GetValues() []*Value {
+ if m != nil {
+ return m.Values
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*Struct)(nil), "google.protobuf.Struct")
+ proto.RegisterType((*Value)(nil), "google.protobuf.Value")
+ proto.RegisterType((*ListValue)(nil), "google.protobuf.ListValue")
+ proto.RegisterEnum("google.protobuf.NullValue", NullValue_name, NullValue_value)
+}
+
+func init() { proto.RegisterFile("google/protobuf/struct.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 417 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0x41, 0x8b, 0xd3, 0x40,
+ 0x14, 0xc7, 0x3b, 0xc9, 0x36, 0x98, 0x17, 0x59, 0x97, 0x11, 0xb4, 0xac, 0xa2, 0xa1, 0x7b, 0x09,
+ 0x22, 0x29, 0xd6, 0x8b, 0x18, 0x2f, 0x06, 0xd6, 0x5d, 0x30, 0x2c, 0x31, 0xba, 0x15, 0xbc, 0x94,
+ 0x26, 0x4d, 0x63, 0xe8, 0x74, 0x26, 0x24, 0x33, 0x4a, 0x8f, 0x7e, 0x0b, 0xcf, 0x1e, 0x3d, 0xfa,
+ 0xe9, 0x3c, 0xca, 0xcc, 0x24, 0xa9, 0xb4, 0xf4, 0x94, 0xbc, 0xf7, 0x7e, 0xef, 0x3f, 0xef, 0xff,
+ 0x66, 0xe0, 0x71, 0xc1, 0x58, 0x41, 0xf2, 0x49, 0x55, 0x33, 0xce, 0x52, 0xb1, 0x9a, 0x34, 0xbc,
+ 0x16, 0x19, 0xf7, 0x55, 0x8c, 0xef, 0xe9, 0xaa, 0xdf, 0x55, 0xc7, 0x3f, 0x11, 0x58, 0x1f, 0x15,
+ 0x81, 0x03, 0xb0, 0x56, 0x65, 0x4e, 0x96, 0xcd, 0x08, 0xb9, 0xa6, 0xe7, 0x4c, 0x2f, 0xfc, 0x3d,
+ 0xd8, 0xd7, 0xa0, 0xff, 0x4e, 0x51, 0x97, 0x94, 0xd7, 0xdb, 0xa4, 0x6d, 0x39, 0xff, 0x00, 0xce,
+ 0x7f, 0x69, 0x7c, 0x06, 0xe6, 0x3a, 0xdf, 0x8e, 0x90, 0x8b, 0x3c, 0x3b, 0x91, 0xbf, 0xf8, 0x39,
+ 0x0c, 0xbf, 0x2d, 0x88, 0xc8, 0x47, 0x86, 0x8b, 0x3c, 0x67, 0xfa, 0xe0, 0x40, 0x7c, 0x26, 0xab,
+ 0x89, 0x86, 0x5e, 0x1b, 0xaf, 0xd0, 0xf8, 0x8f, 0x01, 0x43, 0x95, 0xc4, 0x01, 0x00, 0x15, 0x84,
+ 0xcc, 0xb5, 0x80, 0x14, 0x3d, 0x9d, 0x9e, 0x1f, 0x08, 0xdc, 0x08, 0x42, 0x14, 0x7f, 0x3d, 0x48,
+ 0x6c, 0xda, 0x05, 0xf8, 0x02, 0xee, 0x52, 0xb1, 0x49, 0xf3, 0x7a, 0xbe, 0x3b, 0x1f, 0x5d, 0x0f,
+ 0x12, 0x47, 0x67, 0x7b, 0xa8, 0xe1, 0x75, 0x49, 0x8b, 0x16, 0x32, 0xe5, 0xe0, 0x12, 0xd2, 0x59,
+ 0x0d, 0x3d, 0x05, 0x48, 0x19, 0xeb, 0xc6, 0x38, 0x71, 0x91, 0x77, 0x47, 0x1e, 0x25, 0x73, 0x1a,
+ 0x78, 0xa3, 0x54, 0x44, 0xc6, 0x5b, 0x64, 0xa8, 0xac, 0x3e, 0x3c, 0xb2, 0xc7, 0x56, 0x5e, 0x64,
+ 0xbc, 0x77, 0x49, 0xca, 0xa6, 0xeb, 0xb5, 0x54, 0xef, 0xa1, 0xcb, 0xa8, 0x6c, 0x78, 0xef, 0x92,
+ 0x74, 0x41, 0x68, 0xc1, 0xc9, 0xba, 0xa4, 0xcb, 0x71, 0x00, 0x76, 0x4f, 0x60, 0x1f, 0x2c, 0x25,
+ 0xd6, 0xdd, 0xe8, 0xb1, 0xa5, 0xb7, 0xd4, 0xb3, 0x47, 0x60, 0xf7, 0x4b, 0xc4, 0xa7, 0x00, 0x37,
+ 0xb7, 0x51, 0x34, 0x9f, 0xbd, 0x8d, 0x6e, 0x2f, 0xcf, 0x06, 0xe1, 0x0f, 0x04, 0xf7, 0x33, 0xb6,
+ 0xd9, 0x97, 0x08, 0x1d, 0xed, 0x26, 0x96, 0x71, 0x8c, 0xbe, 0xbc, 0x28, 0x4a, 0xfe, 0x55, 0xa4,
+ 0x7e, 0xc6, 0x36, 0x93, 0x82, 0x91, 0x05, 0x2d, 0x76, 0x4f, 0xb1, 0xe2, 0xdb, 0x2a, 0x6f, 0xda,
+ 0x17, 0x19, 0xe8, 0x4f, 0x95, 0xfe, 0x45, 0xe8, 0x97, 0x61, 0x5e, 0xc5, 0xe1, 0x6f, 0xe3, 0xc9,
+ 0x95, 0x16, 0x8f, 0xbb, 0xf9, 0x3e, 0xe7, 0x84, 0xbc, 0xa7, 0xec, 0x3b, 0xfd, 0x24, 0x3b, 0x53,
+ 0x4b, 0x49, 0xbd, 0xfc, 0x17, 0x00, 0x00, 0xff, 0xff, 0xe8, 0x1b, 0x59, 0xf8, 0xe5, 0x02, 0x00,
+ 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/struct/struct.proto b/vendor/github.com/golang/protobuf/ptypes/struct/struct.proto
new file mode 100644
index 0000000..7d7808e
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/struct/struct.proto
@@ -0,0 +1,96 @@
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option cc_enable_arenas = true;
+option go_package = "github.com/golang/protobuf/ptypes/struct;structpb";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "StructProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+
+
+// `Struct` represents a structured data value, consisting of fields
+// which map to dynamically typed values. In some languages, `Struct`
+// might be supported by a native representation. For example, in
+// scripting languages like JS a struct is represented as an
+// object. The details of that representation are described together
+// with the proto support for the language.
+//
+// The JSON representation for `Struct` is JSON object.
+message Struct {
+ // Unordered map of dynamically typed values.
+ map fields = 1;
+}
+
+// `Value` represents a dynamically typed value which can be either
+// null, a number, a string, a boolean, a recursive struct value, or a
+// list of values. A producer of value is expected to set one of that
+// variants, absence of any variant indicates an error.
+//
+// The JSON representation for `Value` is JSON value.
+message Value {
+ // The kind of value.
+ oneof kind {
+ // Represents a null value.
+ NullValue null_value = 1;
+ // Represents a double value.
+ double number_value = 2;
+ // Represents a string value.
+ string string_value = 3;
+ // Represents a boolean value.
+ bool bool_value = 4;
+ // Represents a structured value.
+ Struct struct_value = 5;
+ // Represents a repeated `Value`.
+ ListValue list_value = 6;
+ }
+}
+
+// `NullValue` is a singleton enumeration to represent the null value for the
+// `Value` type union.
+//
+// The JSON representation for `NullValue` is JSON `null`.
+enum NullValue {
+ // Null value.
+ NULL_VALUE = 0;
+}
+
+// `ListValue` is a wrapper around a repeated field of values.
+//
+// The JSON representation for `ListValue` is JSON array.
+message ListValue {
+ // Repeated field of dynamically typed values.
+ repeated Value values = 1;
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp.go b/vendor/github.com/golang/protobuf/ptypes/timestamp.go
new file mode 100644
index 0000000..47f10db
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/timestamp.go
@@ -0,0 +1,134 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 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 ptypes
+
+// This file implements operations on google.protobuf.Timestamp.
+
+import (
+ "errors"
+ "fmt"
+ "time"
+
+ tspb "github.com/golang/protobuf/ptypes/timestamp"
+)
+
+const (
+ // Seconds field of the earliest valid Timestamp.
+ // This is time.Date(1, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
+ minValidSeconds = -62135596800
+ // Seconds field just after the latest valid Timestamp.
+ // This is time.Date(10000, 1, 1, 0, 0, 0, 0, time.UTC).Unix().
+ maxValidSeconds = 253402300800
+)
+
+// validateTimestamp determines whether a Timestamp is valid.
+// A valid timestamp represents a time in the range
+// [0001-01-01, 10000-01-01) and has a Nanos field
+// in the range [0, 1e9).
+//
+// If the Timestamp is valid, validateTimestamp returns nil.
+// Otherwise, it returns an error that describes
+// the problem.
+//
+// Every valid Timestamp can be represented by a time.Time, but the converse is not true.
+func validateTimestamp(ts *tspb.Timestamp) error {
+ if ts == nil {
+ return errors.New("timestamp: nil Timestamp")
+ }
+ if ts.Seconds < minValidSeconds {
+ return fmt.Errorf("timestamp: %v before 0001-01-01", ts)
+ }
+ if ts.Seconds >= maxValidSeconds {
+ return fmt.Errorf("timestamp: %v after 10000-01-01", ts)
+ }
+ if ts.Nanos < 0 || ts.Nanos >= 1e9 {
+ return fmt.Errorf("timestamp: %v: nanos not in range [0, 1e9)", ts)
+ }
+ return nil
+}
+
+// Timestamp converts a google.protobuf.Timestamp proto to a time.Time.
+// It returns an error if the argument is invalid.
+//
+// Unlike most Go functions, if Timestamp returns an error, the first return value
+// is not the zero time.Time. Instead, it is the value obtained from the
+// time.Unix function when passed the contents of the Timestamp, in the UTC
+// locale. This may or may not be a meaningful time; many invalid Timestamps
+// do map to valid time.Times.
+//
+// A nil Timestamp returns an error. The first return value in that case is
+// undefined.
+func Timestamp(ts *tspb.Timestamp) (time.Time, error) {
+ // Don't return the zero value on error, because corresponds to a valid
+ // timestamp. Instead return whatever time.Unix gives us.
+ var t time.Time
+ if ts == nil {
+ t = time.Unix(0, 0).UTC() // treat nil like the empty Timestamp
+ } else {
+ t = time.Unix(ts.Seconds, int64(ts.Nanos)).UTC()
+ }
+ return t, validateTimestamp(ts)
+}
+
+// TimestampNow returns a google.protobuf.Timestamp for the current time.
+func TimestampNow() *tspb.Timestamp {
+ ts, err := TimestampProto(time.Now())
+ if err != nil {
+ panic("ptypes: time.Now() out of Timestamp range")
+ }
+ return ts
+}
+
+// TimestampProto converts the time.Time to a google.protobuf.Timestamp proto.
+// It returns an error if the resulting Timestamp is invalid.
+func TimestampProto(t time.Time) (*tspb.Timestamp, error) {
+ seconds := t.Unix()
+ nanos := int32(t.Sub(time.Unix(seconds, 0)))
+ ts := &tspb.Timestamp{
+ Seconds: seconds,
+ Nanos: nanos,
+ }
+ if err := validateTimestamp(ts); err != nil {
+ return nil, err
+ }
+ return ts, nil
+}
+
+// TimestampString returns the RFC 3339 string for valid Timestamps. For invalid
+// Timestamps, it returns an error message in parentheses.
+func TimestampString(ts *tspb.Timestamp) string {
+ t, err := Timestamp(ts)
+ if err != nil {
+ return fmt.Sprintf("(%v)", err)
+ }
+ return t.Format(time.RFC3339Nano)
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go
new file mode 100644
index 0000000..e23e4a2
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.pb.go
@@ -0,0 +1,160 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: google/protobuf/timestamp.proto
+
+/*
+Package timestamp is a generated protocol buffer package.
+
+It is generated from these files:
+ google/protobuf/timestamp.proto
+
+It has these top-level messages:
+ Timestamp
+*/
+package timestamp
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// A Timestamp represents a point in time independent of any time zone
+// or calendar, represented as seconds and fractions of seconds at
+// nanosecond resolution in UTC Epoch time. It is encoded using the
+// Proleptic Gregorian Calendar which extends the Gregorian calendar
+// backwards to year one. It is encoded assuming all minutes are 60
+// seconds long, i.e. leap seconds are "smeared" so that no leap second
+// table is needed for interpretation. Range is from
+// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
+// By restricting to that range, we ensure that we can convert to
+// and from RFC 3339 date strings.
+// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
+//
+// # Examples
+//
+// Example 1: Compute Timestamp from POSIX `time()`.
+//
+// Timestamp timestamp;
+// timestamp.set_seconds(time(NULL));
+// timestamp.set_nanos(0);
+//
+// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
+//
+// struct timeval tv;
+// gettimeofday(&tv, NULL);
+//
+// Timestamp timestamp;
+// timestamp.set_seconds(tv.tv_sec);
+// timestamp.set_nanos(tv.tv_usec * 1000);
+//
+// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
+//
+// FILETIME ft;
+// GetSystemTimeAsFileTime(&ft);
+// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
+//
+// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
+// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
+// Timestamp timestamp;
+// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
+// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
+//
+// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
+//
+// long millis = System.currentTimeMillis();
+//
+// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
+// .setNanos((int) ((millis % 1000) * 1000000)).build();
+//
+//
+// Example 5: Compute Timestamp from current time in Python.
+//
+// timestamp = Timestamp()
+// timestamp.GetCurrentTime()
+//
+// # JSON Mapping
+//
+// In JSON format, the Timestamp type is encoded as a string in the
+// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
+// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
+// where {year} is always expressed using four digits while {month}, {day},
+// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
+// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
+// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
+// is required, though only UTC (as indicated by "Z") is presently supported.
+//
+// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
+// 01:30 UTC on January 15, 2017.
+//
+// In JavaScript, one can convert a Date object to this format using the
+// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
+// method. In Python, a standard `datetime.datetime` object can be converted
+// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
+// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
+// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
+// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime())
+// to obtain a formatter capable of generating timestamps in this format.
+//
+//
+type Timestamp struct {
+ // Represents seconds of UTC time since Unix epoch
+ // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
+ // 9999-12-31T23:59:59Z inclusive.
+ Seconds int64 `protobuf:"varint,1,opt,name=seconds" json:"seconds,omitempty"`
+ // Non-negative fractions of a second at nanosecond resolution. Negative
+ // second values with fractions must still have non-negative nanos values
+ // that count forward in time. Must be from 0 to 999,999,999
+ // inclusive.
+ Nanos int32 `protobuf:"varint,2,opt,name=nanos" json:"nanos,omitempty"`
+}
+
+func (m *Timestamp) Reset() { *m = Timestamp{} }
+func (m *Timestamp) String() string { return proto.CompactTextString(m) }
+func (*Timestamp) ProtoMessage() {}
+func (*Timestamp) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+func (*Timestamp) XXX_WellKnownType() string { return "Timestamp" }
+
+func (m *Timestamp) GetSeconds() int64 {
+ if m != nil {
+ return m.Seconds
+ }
+ return 0
+}
+
+func (m *Timestamp) GetNanos() int32 {
+ if m != nil {
+ return m.Nanos
+ }
+ return 0
+}
+
+func init() {
+ proto.RegisterType((*Timestamp)(nil), "google.protobuf.Timestamp")
+}
+
+func init() { proto.RegisterFile("google/protobuf/timestamp.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 191 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0xcf, 0xcf, 0x4f,
+ 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0xc9, 0xcc, 0x4d,
+ 0x2d, 0x2e, 0x49, 0xcc, 0x2d, 0xd0, 0x03, 0x0b, 0x09, 0xf1, 0x43, 0x14, 0xe8, 0xc1, 0x14, 0x28,
+ 0x59, 0x73, 0x71, 0x86, 0xc0, 0xd4, 0x08, 0x49, 0x70, 0xb1, 0x17, 0xa7, 0x26, 0xe7, 0xe7, 0xa5,
+ 0x14, 0x4b, 0x30, 0x2a, 0x30, 0x6a, 0x30, 0x07, 0xc1, 0xb8, 0x42, 0x22, 0x5c, 0xac, 0x79, 0x89,
+ 0x79, 0xf9, 0xc5, 0x12, 0x4c, 0x0a, 0x8c, 0x1a, 0xac, 0x41, 0x10, 0x8e, 0x53, 0x1d, 0x97, 0x70,
+ 0x72, 0x7e, 0xae, 0x1e, 0x9a, 0x99, 0x4e, 0x7c, 0x70, 0x13, 0x03, 0x40, 0x42, 0x01, 0x8c, 0x51,
+ 0xda, 0xe9, 0x99, 0x25, 0x19, 0xa5, 0x49, 0x7a, 0xc9, 0xf9, 0xb9, 0xfa, 0xe9, 0xf9, 0x39, 0x89,
+ 0x79, 0xe9, 0x08, 0x27, 0x16, 0x94, 0x54, 0x16, 0xa4, 0x16, 0x23, 0x5c, 0xfa, 0x83, 0x91, 0x71,
+ 0x11, 0x13, 0xb3, 0x7b, 0x80, 0xd3, 0x2a, 0x26, 0x39, 0x77, 0x88, 0xc9, 0x01, 0x50, 0xb5, 0x7a,
+ 0xe1, 0xa9, 0x39, 0x39, 0xde, 0x79, 0xf9, 0xe5, 0x79, 0x21, 0x20, 0x3d, 0x49, 0x6c, 0x60, 0x43,
+ 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, 0xff, 0xbc, 0x77, 0x4a, 0x07, 0xf7, 0x00, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto
new file mode 100644
index 0000000..b7cbd17
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/timestamp/timestamp.proto
@@ -0,0 +1,133 @@
+// 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.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option cc_enable_arenas = true;
+option go_package = "github.com/golang/protobuf/ptypes/timestamp";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "TimestampProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+
+// A Timestamp represents a point in time independent of any time zone
+// or calendar, represented as seconds and fractions of seconds at
+// nanosecond resolution in UTC Epoch time. It is encoded using the
+// Proleptic Gregorian Calendar which extends the Gregorian calendar
+// backwards to year one. It is encoded assuming all minutes are 60
+// seconds long, i.e. leap seconds are "smeared" so that no leap second
+// table is needed for interpretation. Range is from
+// 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
+// By restricting to that range, we ensure that we can convert to
+// and from RFC 3339 date strings.
+// See [https://www.ietf.org/rfc/rfc3339.txt](https://www.ietf.org/rfc/rfc3339.txt).
+//
+// # Examples
+//
+// Example 1: Compute Timestamp from POSIX `time()`.
+//
+// Timestamp timestamp;
+// timestamp.set_seconds(time(NULL));
+// timestamp.set_nanos(0);
+//
+// Example 2: Compute Timestamp from POSIX `gettimeofday()`.
+//
+// struct timeval tv;
+// gettimeofday(&tv, NULL);
+//
+// Timestamp timestamp;
+// timestamp.set_seconds(tv.tv_sec);
+// timestamp.set_nanos(tv.tv_usec * 1000);
+//
+// Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`.
+//
+// FILETIME ft;
+// GetSystemTimeAsFileTime(&ft);
+// UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime;
+//
+// // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z
+// // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z.
+// Timestamp timestamp;
+// timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL));
+// timestamp.set_nanos((INT32) ((ticks % 10000000) * 100));
+//
+// Example 4: Compute Timestamp from Java `System.currentTimeMillis()`.
+//
+// long millis = System.currentTimeMillis();
+//
+// Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000)
+// .setNanos((int) ((millis % 1000) * 1000000)).build();
+//
+//
+// Example 5: Compute Timestamp from current time in Python.
+//
+// timestamp = Timestamp()
+// timestamp.GetCurrentTime()
+//
+// # JSON Mapping
+//
+// In JSON format, the Timestamp type is encoded as a string in the
+// [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the
+// format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z"
+// where {year} is always expressed using four digits while {month}, {day},
+// {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional
+// seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution),
+// are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone
+// is required, though only UTC (as indicated by "Z") is presently supported.
+//
+// For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past
+// 01:30 UTC on January 15, 2017.
+//
+// In JavaScript, one can convert a Date object to this format using the
+// standard [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString]
+// method. In Python, a standard `datetime.datetime` object can be converted
+// to this format using [`strftime`](https://docs.python.org/2/library/time.html#time.strftime)
+// with the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one
+// can use the Joda Time's [`ISODateTimeFormat.dateTime()`](
+// http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime())
+// to obtain a formatter capable of generating timestamps in this format.
+//
+//
+message Timestamp {
+
+ // Represents seconds of UTC time since Unix epoch
+ // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
+ // 9999-12-31T23:59:59Z inclusive.
+ int64 seconds = 1;
+
+ // Non-negative fractions of a second at nanosecond resolution. Negative
+ // second values with fractions must still have non-negative nanos values
+ // that count forward in time. Must be from 0 to 999,999,999
+ // inclusive.
+ int32 nanos = 2;
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go b/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go
new file mode 100644
index 0000000..6e3c969
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/timestamp_test.go
@@ -0,0 +1,153 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2016 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 ptypes
+
+import (
+ "math"
+ "testing"
+ "time"
+
+ "github.com/golang/protobuf/proto"
+ tspb "github.com/golang/protobuf/ptypes/timestamp"
+)
+
+var tests = []struct {
+ ts *tspb.Timestamp
+ valid bool
+ t time.Time
+}{
+ // The timestamp representing the Unix epoch date.
+ {&tspb.Timestamp{Seconds: 0, Nanos: 0}, true, utcDate(1970, 1, 1)},
+ // The smallest representable timestamp.
+ {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: math.MinInt32}, false,
+ time.Unix(math.MinInt64, math.MinInt32).UTC()},
+ // The smallest representable timestamp with non-negative nanos.
+ {&tspb.Timestamp{Seconds: math.MinInt64, Nanos: 0}, false, time.Unix(math.MinInt64, 0).UTC()},
+ // The earliest valid timestamp.
+ {&tspb.Timestamp{Seconds: minValidSeconds, Nanos: 0}, true, utcDate(1, 1, 1)},
+ //"0001-01-01T00:00:00Z"},
+ // The largest representable timestamp.
+ {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: math.MaxInt32}, false,
+ time.Unix(math.MaxInt64, math.MaxInt32).UTC()},
+ // The largest representable timestamp with nanos in range.
+ {&tspb.Timestamp{Seconds: math.MaxInt64, Nanos: 1e9 - 1}, false,
+ time.Unix(math.MaxInt64, 1e9-1).UTC()},
+ // The largest valid timestamp.
+ {&tspb.Timestamp{Seconds: maxValidSeconds - 1, Nanos: 1e9 - 1}, true,
+ time.Date(9999, 12, 31, 23, 59, 59, 1e9-1, time.UTC)},
+ // The smallest invalid timestamp that is larger than the valid range.
+ {&tspb.Timestamp{Seconds: maxValidSeconds, Nanos: 0}, false, time.Unix(maxValidSeconds, 0).UTC()},
+ // A date before the epoch.
+ {&tspb.Timestamp{Seconds: -281836800, Nanos: 0}, true, utcDate(1961, 1, 26)},
+ // A date after the epoch.
+ {&tspb.Timestamp{Seconds: 1296000000, Nanos: 0}, true, utcDate(2011, 1, 26)},
+ // A date after the epoch, in the middle of the day.
+ {&tspb.Timestamp{Seconds: 1296012345, Nanos: 940483}, true,
+ time.Date(2011, 1, 26, 3, 25, 45, 940483, time.UTC)},
+}
+
+func TestValidateTimestamp(t *testing.T) {
+ for _, s := range tests {
+ got := validateTimestamp(s.ts)
+ if (got == nil) != s.valid {
+ t.Errorf("validateTimestamp(%v) = %v, want %v", s.ts, got, s.valid)
+ }
+ }
+}
+
+func TestTimestamp(t *testing.T) {
+ for _, s := range tests {
+ got, err := Timestamp(s.ts)
+ if (err == nil) != s.valid {
+ t.Errorf("Timestamp(%v) error = %v, but valid = %t", s.ts, err, s.valid)
+ } else if s.valid && got != s.t {
+ t.Errorf("Timestamp(%v) = %v, want %v", s.ts, got, s.t)
+ }
+ }
+ // Special case: a nil Timestamp is an error, but returns the 0 Unix time.
+ got, err := Timestamp(nil)
+ want := time.Unix(0, 0).UTC()
+ if got != want {
+ t.Errorf("Timestamp(nil) = %v, want %v", got, want)
+ }
+ if err == nil {
+ t.Errorf("Timestamp(nil) error = nil, expected error")
+ }
+}
+
+func TestTimestampProto(t *testing.T) {
+ for _, s := range tests {
+ got, err := TimestampProto(s.t)
+ if (err == nil) != s.valid {
+ t.Errorf("TimestampProto(%v) error = %v, but valid = %t", s.t, err, s.valid)
+ } else if s.valid && !proto.Equal(got, s.ts) {
+ t.Errorf("TimestampProto(%v) = %v, want %v", s.t, got, s.ts)
+ }
+ }
+ // No corresponding special case here: no time.Time results in a nil Timestamp.
+}
+
+func TestTimestampString(t *testing.T) {
+ for _, test := range []struct {
+ ts *tspb.Timestamp
+ want string
+ }{
+ // Not much testing needed because presumably time.Format is
+ // well-tested.
+ {&tspb.Timestamp{Seconds: 0, Nanos: 0}, "1970-01-01T00:00:00Z"},
+ {&tspb.Timestamp{Seconds: minValidSeconds - 1, Nanos: 0}, "(timestamp: seconds:-62135596801 before 0001-01-01)"},
+ } {
+ got := TimestampString(test.ts)
+ if got != test.want {
+ t.Errorf("TimestampString(%v) = %q, want %q", test.ts, got, test.want)
+ }
+ }
+}
+
+func utcDate(year, month, day int) time.Time {
+ return time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)
+}
+
+func TestTimestampNow(t *testing.T) {
+ // Bracket the expected time.
+ before := time.Now()
+ ts := TimestampNow()
+ after := time.Now()
+
+ tm, err := Timestamp(ts)
+ if err != nil {
+ t.Errorf("between %v and %v\nTimestampNow() = %v\nwhich is invalid (%v)", before, after, ts, err)
+ }
+ if tm.Before(before) || tm.After(after) {
+ t.Errorf("between %v and %v\nTimestamp(TimestampNow()) = %v", before, after, tm)
+ }
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/wrappers/wrappers.pb.go b/vendor/github.com/golang/protobuf/ptypes/wrappers/wrappers.pb.go
new file mode 100644
index 0000000..0ed59bf
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/wrappers/wrappers.pb.go
@@ -0,0 +1,260 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// source: google/protobuf/wrappers.proto
+
+/*
+Package wrappers is a generated protocol buffer package.
+
+It is generated from these files:
+ google/protobuf/wrappers.proto
+
+It has these top-level messages:
+ DoubleValue
+ FloatValue
+ Int64Value
+ UInt64Value
+ Int32Value
+ UInt32Value
+ BoolValue
+ StringValue
+ BytesValue
+*/
+package wrappers
+
+import proto "github.com/golang/protobuf/proto"
+import fmt "fmt"
+import math "math"
+
+// Reference imports to suppress errors if they are not otherwise used.
+var _ = proto.Marshal
+var _ = fmt.Errorf
+var _ = math.Inf
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the proto package it is being compiled against.
+// A compilation error at this line likely means your copy of the
+// proto package needs to be updated.
+const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
+
+// Wrapper message for `double`.
+//
+// The JSON representation for `DoubleValue` is JSON number.
+type DoubleValue struct {
+ // The double value.
+ Value float64 `protobuf:"fixed64,1,opt,name=value" json:"value,omitempty"`
+}
+
+func (m *DoubleValue) Reset() { *m = DoubleValue{} }
+func (m *DoubleValue) String() string { return proto.CompactTextString(m) }
+func (*DoubleValue) ProtoMessage() {}
+func (*DoubleValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
+func (*DoubleValue) XXX_WellKnownType() string { return "DoubleValue" }
+
+func (m *DoubleValue) GetValue() float64 {
+ if m != nil {
+ return m.Value
+ }
+ return 0
+}
+
+// Wrapper message for `float`.
+//
+// The JSON representation for `FloatValue` is JSON number.
+type FloatValue struct {
+ // The float value.
+ Value float32 `protobuf:"fixed32,1,opt,name=value" json:"value,omitempty"`
+}
+
+func (m *FloatValue) Reset() { *m = FloatValue{} }
+func (m *FloatValue) String() string { return proto.CompactTextString(m) }
+func (*FloatValue) ProtoMessage() {}
+func (*FloatValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
+func (*FloatValue) XXX_WellKnownType() string { return "FloatValue" }
+
+func (m *FloatValue) GetValue() float32 {
+ if m != nil {
+ return m.Value
+ }
+ return 0
+}
+
+// Wrapper message for `int64`.
+//
+// The JSON representation for `Int64Value` is JSON string.
+type Int64Value struct {
+ // The int64 value.
+ Value int64 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"`
+}
+
+func (m *Int64Value) Reset() { *m = Int64Value{} }
+func (m *Int64Value) String() string { return proto.CompactTextString(m) }
+func (*Int64Value) ProtoMessage() {}
+func (*Int64Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
+func (*Int64Value) XXX_WellKnownType() string { return "Int64Value" }
+
+func (m *Int64Value) GetValue() int64 {
+ if m != nil {
+ return m.Value
+ }
+ return 0
+}
+
+// Wrapper message for `uint64`.
+//
+// The JSON representation for `UInt64Value` is JSON string.
+type UInt64Value struct {
+ // The uint64 value.
+ Value uint64 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"`
+}
+
+func (m *UInt64Value) Reset() { *m = UInt64Value{} }
+func (m *UInt64Value) String() string { return proto.CompactTextString(m) }
+func (*UInt64Value) ProtoMessage() {}
+func (*UInt64Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{3} }
+func (*UInt64Value) XXX_WellKnownType() string { return "UInt64Value" }
+
+func (m *UInt64Value) GetValue() uint64 {
+ if m != nil {
+ return m.Value
+ }
+ return 0
+}
+
+// Wrapper message for `int32`.
+//
+// The JSON representation for `Int32Value` is JSON number.
+type Int32Value struct {
+ // The int32 value.
+ Value int32 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"`
+}
+
+func (m *Int32Value) Reset() { *m = Int32Value{} }
+func (m *Int32Value) String() string { return proto.CompactTextString(m) }
+func (*Int32Value) ProtoMessage() {}
+func (*Int32Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{4} }
+func (*Int32Value) XXX_WellKnownType() string { return "Int32Value" }
+
+func (m *Int32Value) GetValue() int32 {
+ if m != nil {
+ return m.Value
+ }
+ return 0
+}
+
+// Wrapper message for `uint32`.
+//
+// The JSON representation for `UInt32Value` is JSON number.
+type UInt32Value struct {
+ // The uint32 value.
+ Value uint32 `protobuf:"varint,1,opt,name=value" json:"value,omitempty"`
+}
+
+func (m *UInt32Value) Reset() { *m = UInt32Value{} }
+func (m *UInt32Value) String() string { return proto.CompactTextString(m) }
+func (*UInt32Value) ProtoMessage() {}
+func (*UInt32Value) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
+func (*UInt32Value) XXX_WellKnownType() string { return "UInt32Value" }
+
+func (m *UInt32Value) GetValue() uint32 {
+ if m != nil {
+ return m.Value
+ }
+ return 0
+}
+
+// Wrapper message for `bool`.
+//
+// The JSON representation for `BoolValue` is JSON `true` and `false`.
+type BoolValue struct {
+ // The bool value.
+ Value bool `protobuf:"varint,1,opt,name=value" json:"value,omitempty"`
+}
+
+func (m *BoolValue) Reset() { *m = BoolValue{} }
+func (m *BoolValue) String() string { return proto.CompactTextString(m) }
+func (*BoolValue) ProtoMessage() {}
+func (*BoolValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{6} }
+func (*BoolValue) XXX_WellKnownType() string { return "BoolValue" }
+
+func (m *BoolValue) GetValue() bool {
+ if m != nil {
+ return m.Value
+ }
+ return false
+}
+
+// Wrapper message for `string`.
+//
+// The JSON representation for `StringValue` is JSON string.
+type StringValue struct {
+ // The string value.
+ Value string `protobuf:"bytes,1,opt,name=value" json:"value,omitempty"`
+}
+
+func (m *StringValue) Reset() { *m = StringValue{} }
+func (m *StringValue) String() string { return proto.CompactTextString(m) }
+func (*StringValue) ProtoMessage() {}
+func (*StringValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{7} }
+func (*StringValue) XXX_WellKnownType() string { return "StringValue" }
+
+func (m *StringValue) GetValue() string {
+ if m != nil {
+ return m.Value
+ }
+ return ""
+}
+
+// Wrapper message for `bytes`.
+//
+// The JSON representation for `BytesValue` is JSON string.
+type BytesValue struct {
+ // The bytes value.
+ Value []byte `protobuf:"bytes,1,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (m *BytesValue) Reset() { *m = BytesValue{} }
+func (m *BytesValue) String() string { return proto.CompactTextString(m) }
+func (*BytesValue) ProtoMessage() {}
+func (*BytesValue) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{8} }
+func (*BytesValue) XXX_WellKnownType() string { return "BytesValue" }
+
+func (m *BytesValue) GetValue() []byte {
+ if m != nil {
+ return m.Value
+ }
+ return nil
+}
+
+func init() {
+ proto.RegisterType((*DoubleValue)(nil), "google.protobuf.DoubleValue")
+ proto.RegisterType((*FloatValue)(nil), "google.protobuf.FloatValue")
+ proto.RegisterType((*Int64Value)(nil), "google.protobuf.Int64Value")
+ proto.RegisterType((*UInt64Value)(nil), "google.protobuf.UInt64Value")
+ proto.RegisterType((*Int32Value)(nil), "google.protobuf.Int32Value")
+ proto.RegisterType((*UInt32Value)(nil), "google.protobuf.UInt32Value")
+ proto.RegisterType((*BoolValue)(nil), "google.protobuf.BoolValue")
+ proto.RegisterType((*StringValue)(nil), "google.protobuf.StringValue")
+ proto.RegisterType((*BytesValue)(nil), "google.protobuf.BytesValue")
+}
+
+func init() { proto.RegisterFile("google/protobuf/wrappers.proto", fileDescriptor0) }
+
+var fileDescriptor0 = []byte{
+ // 259 bytes of a gzipped FileDescriptorProto
+ 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4b, 0xcf, 0xcf, 0x4f,
+ 0xcf, 0x49, 0xd5, 0x2f, 0x28, 0xca, 0x2f, 0xc9, 0x4f, 0x2a, 0x4d, 0xd3, 0x2f, 0x2f, 0x4a, 0x2c,
+ 0x28, 0x48, 0x2d, 0x2a, 0xd6, 0x03, 0x8b, 0x08, 0xf1, 0x43, 0xe4, 0xf5, 0x60, 0xf2, 0x4a, 0xca,
+ 0x5c, 0xdc, 0x2e, 0xf9, 0xa5, 0x49, 0x39, 0xa9, 0x61, 0x89, 0x39, 0xa5, 0xa9, 0x42, 0x22, 0x5c,
+ 0xac, 0x65, 0x20, 0x86, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x63, 0x10, 0x84, 0xa3, 0xa4, 0xc4, 0xc5,
+ 0xe5, 0x96, 0x93, 0x9f, 0x58, 0x82, 0x45, 0x0d, 0x13, 0x92, 0x1a, 0xcf, 0xbc, 0x12, 0x33, 0x13,
+ 0x2c, 0x6a, 0x98, 0x61, 0x6a, 0x94, 0xb9, 0xb8, 0x43, 0x71, 0x29, 0x62, 0x41, 0x35, 0xc8, 0xd8,
+ 0x08, 0x8b, 0x1a, 0x56, 0x34, 0x83, 0xb0, 0x2a, 0xe2, 0x85, 0x29, 0x52, 0xe4, 0xe2, 0x74, 0xca,
+ 0xcf, 0xcf, 0xc1, 0xa2, 0x84, 0x03, 0xc9, 0x9c, 0xe0, 0x92, 0xa2, 0xcc, 0xbc, 0x74, 0x2c, 0x8a,
+ 0x38, 0x91, 0x1c, 0xe4, 0x54, 0x59, 0x92, 0x5a, 0x8c, 0x45, 0x0d, 0x0f, 0x54, 0x8d, 0x53, 0x0d,
+ 0x97, 0x70, 0x72, 0x7e, 0xae, 0x1e, 0x5a, 0xe8, 0x3a, 0xf1, 0x86, 0x43, 0x83, 0x3f, 0x00, 0x24,
+ 0x12, 0xc0, 0x18, 0xa5, 0x95, 0x9e, 0x59, 0x92, 0x51, 0x9a, 0xa4, 0x97, 0x9c, 0x9f, 0xab, 0x9f,
+ 0x9e, 0x9f, 0x93, 0x98, 0x97, 0x8e, 0x88, 0xaa, 0x82, 0x92, 0xca, 0x82, 0xd4, 0x62, 0x78, 0x8c,
+ 0xfd, 0x60, 0x64, 0x5c, 0xc4, 0xc4, 0xec, 0x1e, 0xe0, 0xb4, 0x8a, 0x49, 0xce, 0x1d, 0x62, 0x6e,
+ 0x00, 0x54, 0xa9, 0x5e, 0x78, 0x6a, 0x4e, 0x8e, 0x77, 0x5e, 0x7e, 0x79, 0x5e, 0x08, 0x48, 0x4b,
+ 0x12, 0x1b, 0xd8, 0x0c, 0x63, 0x40, 0x00, 0x00, 0x00, 0xff, 0xff, 0x19, 0x6c, 0xb9, 0xb8, 0xfe,
+ 0x01, 0x00, 0x00,
+}
diff --git a/vendor/github.com/golang/protobuf/ptypes/wrappers/wrappers.proto b/vendor/github.com/golang/protobuf/ptypes/wrappers/wrappers.proto
new file mode 100644
index 0000000..0194763
--- /dev/null
+++ b/vendor/github.com/golang/protobuf/ptypes/wrappers/wrappers.proto
@@ -0,0 +1,118 @@
+// 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.
+
+// Wrappers for primitive (non-message) types. These types are useful
+// for embedding primitives in the `google.protobuf.Any` type and for places
+// where we need to distinguish between the absence of a primitive
+// typed field and its default value.
+
+syntax = "proto3";
+
+package google.protobuf;
+
+option csharp_namespace = "Google.Protobuf.WellKnownTypes";
+option cc_enable_arenas = true;
+option go_package = "github.com/golang/protobuf/ptypes/wrappers";
+option java_package = "com.google.protobuf";
+option java_outer_classname = "WrappersProto";
+option java_multiple_files = true;
+option objc_class_prefix = "GPB";
+
+// Wrapper message for `double`.
+//
+// The JSON representation for `DoubleValue` is JSON number.
+message DoubleValue {
+ // The double value.
+ double value = 1;
+}
+
+// Wrapper message for `float`.
+//
+// The JSON representation for `FloatValue` is JSON number.
+message FloatValue {
+ // The float value.
+ float value = 1;
+}
+
+// Wrapper message for `int64`.
+//
+// The JSON representation for `Int64Value` is JSON string.
+message Int64Value {
+ // The int64 value.
+ int64 value = 1;
+}
+
+// Wrapper message for `uint64`.
+//
+// The JSON representation for `UInt64Value` is JSON string.
+message UInt64Value {
+ // The uint64 value.
+ uint64 value = 1;
+}
+
+// Wrapper message for `int32`.
+//
+// The JSON representation for `Int32Value` is JSON number.
+message Int32Value {
+ // The int32 value.
+ int32 value = 1;
+}
+
+// Wrapper message for `uint32`.
+//
+// The JSON representation for `UInt32Value` is JSON number.
+message UInt32Value {
+ // The uint32 value.
+ uint32 value = 1;
+}
+
+// Wrapper message for `bool`.
+//
+// The JSON representation for `BoolValue` is JSON `true` and `false`.
+message BoolValue {
+ // The bool value.
+ bool value = 1;
+}
+
+// Wrapper message for `string`.
+//
+// The JSON representation for `StringValue` is JSON string.
+message StringValue {
+ // The string value.
+ string value = 1;
+}
+
+// Wrapper message for `bytes`.
+//
+// The JSON representation for `BytesValue` is JSON string.
+message BytesValue {
+ // The bytes value.
+ bytes value = 1;
+}
diff --git a/vendor/github.com/gorilla/context/.travis.yml b/vendor/github.com/gorilla/context/.travis.yml
index 6796581..faca4da 100644
--- a/vendor/github.com/gorilla/context/.travis.yml
+++ b/vendor/github.com/gorilla/context/.travis.yml
@@ -1,9 +1,19 @@
language: go
+sudo: false
-go:
- - 1.0
- - 1.1
- - 1.2
- - 1.3
- - 1.4
- - tip
+matrix:
+ include:
+ - go: 1.3
+ - go: 1.4
+ - go: 1.5
+ - go: 1.6
+ - go: tip
+
+install:
+ - go get golang.org/x/tools/cmd/vet
+
+script:
+ - go get -t -v ./...
+ - diff -u <(echo -n) <(gofmt -d .)
+ - go tool vet .
+ - go test -v -race ./...
diff --git a/vendor/github.com/gorilla/mux/.travis.yml b/vendor/github.com/gorilla/mux/.travis.yml
index d87d465..ca377e6 100644
--- a/vendor/github.com/gorilla/mux/.travis.yml
+++ b/vendor/github.com/gorilla/mux/.travis.yml
@@ -1,7 +1,22 @@
language: go
+sudo: false
-go:
- - 1.0
- - 1.1
- - 1.2
- - tip
+matrix:
+ include:
+ - go: 1.2
+ - go: 1.3
+ - go: 1.4
+ - go: 1.5
+ - go: 1.6
+ - go: 1.7
+ - go: 1.8
+ - go: tip
+
+install:
+ - # Skip
+
+script:
+ - go get -t -v ./...
+ - diff -u <(echo -n) <(gofmt -d .)
+ - go tool vet .
+ - go test -v -race ./...
diff --git a/vendor/github.com/gorilla/mux/README.md b/vendor/github.com/gorilla/mux/README.md
index e60301b..8dcd718 100644
--- a/vendor/github.com/gorilla/mux/README.md
+++ b/vendor/github.com/gorilla/mux/README.md
@@ -1,7 +1,383 @@
-mux
+gorilla/mux
===
-[![Build Status](https://travis-ci.org/gorilla/mux.png?branch=master)](https://travis-ci.org/gorilla/mux)
+[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux)
+[![Build Status](https://travis-ci.org/gorilla/mux.svg?branch=master)](https://travis-ci.org/gorilla/mux)
+[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/mux/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/mux?badge)
-gorilla/mux is a powerful URL router and dispatcher.
+![Gorilla Logo](http://www.gorillatoolkit.org/static/images/gorilla-icon-64.png)
-Read the full documentation here: http://www.gorillatoolkit.org/pkg/mux
+http://www.gorillatoolkit.org/pkg/mux
+
+Package `gorilla/mux` implements a request router and dispatcher for matching incoming requests to
+their respective handler.
+
+The name mux stands for "HTTP request multiplexer". Like the standard `http.ServeMux`, `mux.Router` matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are:
+
+* It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`.
+* Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers.
+* URL hosts, paths and query values can have variables with an optional regular expression.
+* Registered URLs can be built, or "reversed", which helps maintaining references to resources.
+* Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching.
+
+---
+
+* [Install](#install)
+* [Examples](#examples)
+* [Matching Routes](#matching-routes)
+* [Static Files](#static-files)
+* [Registered URLs](#registered-urls)
+* [Walking Routes](#walking-routes)
+* [Full Example](#full-example)
+
+---
+
+## Install
+
+With a [correctly configured](https://golang.org/doc/install#testing) Go toolchain:
+
+```sh
+go get -u github.com/gorilla/mux
+```
+
+## Examples
+
+Let's start registering a couple of URL paths and handlers:
+
+```go
+func main() {
+ r := mux.NewRouter()
+ r.HandleFunc("/", HomeHandler)
+ r.HandleFunc("/products", ProductsHandler)
+ r.HandleFunc("/articles", ArticlesHandler)
+ http.Handle("/", r)
+}
+```
+
+Here we register three routes mapping URL paths to handlers. This is equivalent to how `http.HandleFunc()` works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (`http.ResponseWriter`, `*http.Request`) as parameters.
+
+Paths can have variables. They are defined using the format `{name}` or `{name:pattern}`. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example:
+
+```go
+r := mux.NewRouter()
+r.HandleFunc("/products/{key}", ProductHandler)
+r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
+r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
+```
+
+The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`:
+
+```go
+func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) {
+ vars := mux.Vars(r)
+ w.WriteHeader(http.StatusOK)
+ fmt.Fprintf(w, "Category: %v\n", vars["category"])
+}
+```
+
+And this is all you need to know about the basic usage. More advanced options are explained below.
+
+### Matching Routes
+
+Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables:
+
+```go
+r := mux.NewRouter()
+// Only matches if domain is "www.example.com".
+r.Host("www.example.com")
+// Matches a dynamic subdomain.
+r.Host("{subdomain:[a-z]+}.domain.com")
+```
+
+There are several other matchers that can be added. To match path prefixes:
+
+```go
+r.PathPrefix("/products/")
+```
+
+...or HTTP methods:
+
+```go
+r.Methods("GET", "POST")
+```
+
+...or URL schemes:
+
+```go
+r.Schemes("https")
+```
+
+...or header values:
+
+```go
+r.Headers("X-Requested-With", "XMLHttpRequest")
+```
+
+...or query values:
+
+```go
+r.Queries("key", "value")
+```
+
+...or to use a custom matcher function:
+
+```go
+r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
+ return r.ProtoMajor == 0
+})
+```
+
+...and finally, it is possible to combine several matchers in a single route:
+
+```go
+r.HandleFunc("/products", ProductsHandler).
+ Host("www.example.com").
+ Methods("GET").
+ Schemes("http")
+```
+
+Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting".
+
+For example, let's say we have several URLs that should only match when the host is `www.example.com`. Create a route for that host and get a "subrouter" from it:
+
+```go
+r := mux.NewRouter()
+s := r.Host("www.example.com").Subrouter()
+```
+
+Then register routes in the subrouter:
+
+```go
+s.HandleFunc("/products/", ProductsHandler)
+s.HandleFunc("/products/{key}", ProductHandler)
+s.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
+```
+
+The three URL paths we registered above will only be tested if the domain is `www.example.com`, because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route.
+
+Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter.
+
+There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths:
+
+```go
+r := mux.NewRouter()
+s := r.PathPrefix("/products").Subrouter()
+// "/products/"
+s.HandleFunc("/", ProductsHandler)
+// "/products/{key}/"
+s.HandleFunc("/{key}/", ProductHandler)
+// "/products/{key}/details"
+s.HandleFunc("/{key}/details", ProductDetailsHandler)
+```
+### Listing Routes
+
+Routes on a mux can be listed using the Router.Walk method—useful for generating documentation:
+
+```go
+package main
+
+import (
+ "fmt"
+ "net/http"
+ "strings"
+
+ "github.com/gorilla/mux"
+)
+
+func handler(w http.ResponseWriter, r *http.Request) {
+ return
+}
+
+func main() {
+ r := mux.NewRouter()
+ r.HandleFunc("/", handler)
+ r.HandleFunc("/products", handler).Methods("POST")
+ r.HandleFunc("/articles", handler).Methods("GET")
+ r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT")
+ r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
+ t, err := route.GetPathTemplate()
+ if err != nil {
+ return err
+ }
+ // p will contain regular expression is compatible with regular expression in Perl, Python, and other languages.
+ // for instance the regular expression for path '/articles/{id}' will be '^/articles/(?P[^/]+)$'
+ p, err := route.GetPathRegexp()
+ if err != nil {
+ return err
+ }
+ m, err := route.GetMethods()
+ if err != nil {
+ return err
+ }
+ fmt.Println(strings.Join(m, ","), t, p)
+ return nil
+ })
+ http.Handle("/", r)
+}
+```
+
+### Static Files
+
+Note that the path provided to `PathPrefix()` represents a "wildcard": calling
+`PathPrefix("/static/").Handler(...)` means that the handler will be passed any
+request that matches "/static/*". This makes it easy to serve static files with mux:
+
+```go
+func main() {
+ var dir string
+
+ flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
+ flag.Parse()
+ r := mux.NewRouter()
+
+ // This will serve files under http://localhost:8000/static/
+ r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
+
+ srv := &http.Server{
+ Handler: r,
+ Addr: "127.0.0.1:8000",
+ // Good practice: enforce timeouts for servers you create!
+ WriteTimeout: 15 * time.Second,
+ ReadTimeout: 15 * time.Second,
+ }
+
+ log.Fatal(srv.ListenAndServe())
+}
+```
+
+### Registered URLs
+
+Now let's see how to build registered URLs.
+
+Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling `Name()` on a route. For example:
+
+```go
+r := mux.NewRouter()
+r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler).
+ Name("article")
+```
+
+To build a URL, get the route and call the `URL()` method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do:
+
+```go
+url, err := r.Get("article").URL("category", "technology", "id", "42")
+```
+
+...and the result will be a `url.URL` with the following path:
+
+```
+"/articles/technology/42"
+```
+
+This also works for host and query value variables:
+
+```go
+r := mux.NewRouter()
+r.Host("{subdomain}.domain.com").
+ Path("/articles/{category}/{id:[0-9]+}").
+ Queries("filter", "{filter}").
+ HandlerFunc(ArticleHandler).
+ Name("article")
+
+// url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla"
+url, err := r.Get("article").URL("subdomain", "news",
+ "category", "technology",
+ "id", "42",
+ "filter", "gorilla")
+```
+
+All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match.
+
+Regex support also exists for matching Headers within a route. For example, we could do:
+
+```go
+r.HeadersRegexp("Content-Type", "application/(text|json)")
+```
+
+...and the route will match both requests with a Content-Type of `application/json` as well as `application/text`
+
+There's also a way to build only the URL host or path for a route: use the methods `URLHost()` or `URLPath()` instead. For the previous route, we would do:
+
+```go
+// "http://news.domain.com/"
+host, err := r.Get("article").URLHost("subdomain", "news")
+
+// "/articles/technology/42"
+path, err := r.Get("article").URLPath("category", "technology", "id", "42")
+```
+
+And if you use subrouters, host and path defined separately can be built as well:
+
+```go
+r := mux.NewRouter()
+s := r.Host("{subdomain}.domain.com").Subrouter()
+s.Path("/articles/{category}/{id:[0-9]+}").
+ HandlerFunc(ArticleHandler).
+ Name("article")
+
+// "http://news.domain.com/articles/technology/42"
+url, err := r.Get("article").URL("subdomain", "news",
+ "category", "technology",
+ "id", "42")
+```
+
+### Walking Routes
+
+The `Walk` function on `mux.Router` can be used to visit all of the routes that are registered on a router. For example,
+the following prints all of the registered routes:
+
+```go
+r := mux.NewRouter()
+r.HandleFunc("/", handler)
+r.HandleFunc("/products", handler).Methods("POST")
+r.HandleFunc("/articles", handler).Methods("GET")
+r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT")
+r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
+ t, err := route.GetPathTemplate()
+ if err != nil {
+ return err
+ }
+ // p will contain a regular expression that is compatible with regular expressions in Perl, Python, and other languages.
+ // For example, the regular expression for path '/articles/{id}' will be '^/articles/(?P[^/]+)$'.
+ p, err := route.GetPathRegexp()
+ if err != nil {
+ return err
+ }
+ m, err := route.GetMethods()
+ if err != nil {
+ return err
+ }
+ fmt.Println(strings.Join(m, ","), t, p)
+ return nil
+})
+```
+
+## Full Example
+
+Here's a complete, runnable example of a small `mux` based server:
+
+```go
+package main
+
+import (
+ "net/http"
+ "log"
+ "github.com/gorilla/mux"
+)
+
+func YourHandler(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte("Gorilla!\n"))
+}
+
+func main() {
+ r := mux.NewRouter()
+ // Routes consist of a path and a handler function.
+ r.HandleFunc("/", YourHandler)
+
+ // Bind to a port and pass our router in
+ log.Fatal(http.ListenAndServe(":8000", r))
+}
+```
+
+## License
+
+BSD licensed. See the LICENSE file for details.
diff --git a/vendor/github.com/gorilla/mux/bench_test.go b/vendor/github.com/gorilla/mux/bench_test.go
index c5f97b2..522156d 100644
--- a/vendor/github.com/gorilla/mux/bench_test.go
+++ b/vendor/github.com/gorilla/mux/bench_test.go
@@ -6,6 +6,7 @@ package mux
import (
"net/http"
+ "net/http/httptest"
"testing"
)
@@ -19,3 +20,30 @@ func BenchmarkMux(b *testing.B) {
router.ServeHTTP(nil, request)
}
}
+
+func BenchmarkMuxAlternativeInRegexp(b *testing.B) {
+ router := new(Router)
+ handler := func(w http.ResponseWriter, r *http.Request) {}
+ router.HandleFunc("/v1/{v1:(?:a|b)}", handler)
+
+ requestA, _ := http.NewRequest("GET", "/v1/a", nil)
+ requestB, _ := http.NewRequest("GET", "/v1/b", nil)
+ for i := 0; i < b.N; i++ {
+ router.ServeHTTP(nil, requestA)
+ router.ServeHTTP(nil, requestB)
+ }
+}
+
+func BenchmarkManyPathVariables(b *testing.B) {
+ router := new(Router)
+ handler := func(w http.ResponseWriter, r *http.Request) {}
+ router.HandleFunc("/v1/{v1}/{v2}/{v3}/{v4}/{v5}", handler)
+
+ matchingRequest, _ := http.NewRequest("GET", "/v1/1/2/3/4/5", nil)
+ notMatchingRequest, _ := http.NewRequest("GET", "/v1/1/2/3/4", nil)
+ recorder := httptest.NewRecorder()
+ for i := 0; i < b.N; i++ {
+ router.ServeHTTP(nil, matchingRequest)
+ router.ServeHTTP(recorder, notMatchingRequest)
+ }
+}
diff --git a/vendor/github.com/gorilla/mux/context_gorilla.go b/vendor/github.com/gorilla/mux/context_gorilla.go
new file mode 100644
index 0000000..d7adaa8
--- /dev/null
+++ b/vendor/github.com/gorilla/mux/context_gorilla.go
@@ -0,0 +1,26 @@
+// +build !go1.7
+
+package mux
+
+import (
+ "net/http"
+
+ "github.com/gorilla/context"
+)
+
+func contextGet(r *http.Request, key interface{}) interface{} {
+ return context.Get(r, key)
+}
+
+func contextSet(r *http.Request, key, val interface{}) *http.Request {
+ if val == nil {
+ return r
+ }
+
+ context.Set(r, key, val)
+ return r
+}
+
+func contextClear(r *http.Request) {
+ context.Clear(r)
+}
diff --git a/vendor/github.com/gorilla/mux/context_gorilla_test.go b/vendor/github.com/gorilla/mux/context_gorilla_test.go
new file mode 100644
index 0000000..ffaf384
--- /dev/null
+++ b/vendor/github.com/gorilla/mux/context_gorilla_test.go
@@ -0,0 +1,40 @@
+// +build !go1.7
+
+package mux
+
+import (
+ "net/http"
+ "testing"
+
+ "github.com/gorilla/context"
+)
+
+// Tests that the context is cleared or not cleared properly depending on
+// the configuration of the router
+func TestKeepContext(t *testing.T) {
+ func1 := func(w http.ResponseWriter, r *http.Request) {}
+
+ r := NewRouter()
+ r.HandleFunc("/", func1).Name("func1")
+
+ req, _ := http.NewRequest("GET", "http://localhost/", nil)
+ context.Set(req, "t", 1)
+
+ res := new(http.ResponseWriter)
+ r.ServeHTTP(*res, req)
+
+ if _, ok := context.GetOk(req, "t"); ok {
+ t.Error("Context should have been cleared at end of request")
+ }
+
+ r.KeepContext = true
+
+ req, _ = http.NewRequest("GET", "http://localhost/", nil)
+ context.Set(req, "t", 1)
+
+ r.ServeHTTP(*res, req)
+ if _, ok := context.GetOk(req, "t"); !ok {
+ t.Error("Context should NOT have been cleared at end of request")
+ }
+
+}
diff --git a/vendor/github.com/gorilla/mux/context_native.go b/vendor/github.com/gorilla/mux/context_native.go
new file mode 100644
index 0000000..209cbea
--- /dev/null
+++ b/vendor/github.com/gorilla/mux/context_native.go
@@ -0,0 +1,24 @@
+// +build go1.7
+
+package mux
+
+import (
+ "context"
+ "net/http"
+)
+
+func contextGet(r *http.Request, key interface{}) interface{} {
+ return r.Context().Value(key)
+}
+
+func contextSet(r *http.Request, key, val interface{}) *http.Request {
+ if val == nil {
+ return r
+ }
+
+ return r.WithContext(context.WithValue(r.Context(), key, val))
+}
+
+func contextClear(r *http.Request) {
+ return
+}
diff --git a/vendor/github.com/gorilla/mux/context_native_test.go b/vendor/github.com/gorilla/mux/context_native_test.go
new file mode 100644
index 0000000..c150edf
--- /dev/null
+++ b/vendor/github.com/gorilla/mux/context_native_test.go
@@ -0,0 +1,32 @@
+// +build go1.7
+
+package mux
+
+import (
+ "context"
+ "net/http"
+ "testing"
+ "time"
+)
+
+func TestNativeContextMiddleware(t *testing.T) {
+ withTimeout := func(h http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ ctx, cancel := context.WithTimeout(r.Context(), time.Minute)
+ defer cancel()
+ h.ServeHTTP(w, r.WithContext(ctx))
+ })
+ }
+
+ r := NewRouter()
+ r.Handle("/path/{foo}", withTimeout(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ vars := Vars(r)
+ if vars["foo"] != "bar" {
+ t.Fatal("Expected foo var to be set")
+ }
+ })))
+
+ rec := NewRecorder()
+ req := newRequest("GET", "/path/bar")
+ r.ServeHTTP(rec, req)
+}
diff --git a/vendor/github.com/gorilla/mux/doc.go b/vendor/github.com/gorilla/mux/doc.go
index b2deed3..cce30b2 100644
--- a/vendor/github.com/gorilla/mux/doc.go
+++ b/vendor/github.com/gorilla/mux/doc.go
@@ -3,7 +3,7 @@
// license that can be found in the LICENSE file.
/*
-Package gorilla/mux implements a request router and dispatcher.
+Package mux implements a request router and dispatcher.
The name mux stands for "HTTP request multiplexer". Like the standard
http.ServeMux, mux.Router matches incoming requests against a list of
@@ -12,8 +12,8 @@ or other conditions. The main features are:
* Requests can be matched based on URL host, path, path prefix, schemes,
header and query values, HTTP methods or using custom matchers.
- * URL hosts and paths can have variables with an optional regular
- expression.
+ * URL hosts, paths and query values can have variables with an optional
+ regular expression.
* Registered URLs can be built, or "reversed", which helps maintaining
references to resources.
* Routes can be used as subrouters: nested routes are only tested if the
@@ -47,12 +47,21 @@ variable will be anything until the next slash. For example:
r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler)
r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler)
+Groups can be used inside patterns, as long as they are non-capturing (?:re). For example:
+
+ r.HandleFunc("/articles/{category}/{sort:(?:asc|desc|new)}", ArticlesCategoryHandler)
+
The names are used to create a map of route variables which can be retrieved
calling mux.Vars():
vars := mux.Vars(request)
category := vars["category"]
+Note that if any capturing groups are present, mux will panic() during parsing. To prevent
+this, convert any capturing groups to non-capturing, e.g. change "/{sort:(asc|desc)}" to
+"/{sort:(?:asc|desc)}". This is a change from prior versions which behaved unpredictably
+when capturing groups were present.
+
And this is all you need to know about the basic usage. More advanced options
are explained below.
@@ -60,8 +69,8 @@ Routes can also be restricted to a domain or subdomain. Just define a host
pattern to be matched. They can also have variables:
r := mux.NewRouter()
- // Only matches if domain is "www.domain.com".
- r.Host("www.domain.com")
+ // Only matches if domain is "www.example.com".
+ r.Host("www.example.com")
// Matches a dynamic subdomain.
r.Host("{subdomain:[a-z]+}.domain.com")
@@ -89,12 +98,12 @@ There are several other matchers that can be added. To match path prefixes:
r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool {
return r.ProtoMajor == 0
- })
+ })
...and finally, it is possible to combine several matchers in a single route:
r.HandleFunc("/products", ProductsHandler).
- Host("www.domain.com").
+ Host("www.example.com").
Methods("GET").
Schemes("http")
@@ -103,11 +112,11 @@ a way to group several routes that share the same requirements.
We call it "subrouting".
For example, let's say we have several URLs that should only match when the
-host is "www.domain.com". Create a route for that host and get a "subrouter"
+host is "www.example.com". Create a route for that host and get a "subrouter"
from it:
r := mux.NewRouter()
- s := r.Host("www.domain.com").Subrouter()
+ s := r.Host("www.example.com").Subrouter()
Then register routes in the subrouter:
@@ -116,7 +125,7 @@ Then register routes in the subrouter:
s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
The three URL paths we registered above will only be tested if the domain is
-"www.domain.com", because the subrouter is tested first. This is not
+"www.example.com", because the subrouter is tested first. This is not
only convenient, but also optimizes request matching. You can create
subrouters combining any attribute matchers accepted by a route.
@@ -136,6 +145,31 @@ the inner routes use it as base for their paths:
// "/products/{key}/details"
s.HandleFunc("/{key}/details", ProductDetailsHandler)
+Note that the path provided to PathPrefix() represents a "wildcard": calling
+PathPrefix("/static/").Handler(...) means that the handler will be passed any
+request that matches "/static/*". This makes it easy to serve static files with mux:
+
+ func main() {
+ var dir string
+
+ flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir")
+ flag.Parse()
+ r := mux.NewRouter()
+
+ // This will serve files under http://localhost:8000/static/
+ r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir))))
+
+ srv := &http.Server{
+ Handler: r,
+ Addr: "127.0.0.1:8000",
+ // Good practice: enforce timeouts for servers you create!
+ WriteTimeout: 15 * time.Second,
+ ReadTimeout: 15 * time.Second,
+ }
+
+ log.Fatal(srv.ListenAndServe())
+ }
+
Now let's see how to build registered URLs.
Routes can be named. All routes that define a name can have their URLs built,
@@ -154,24 +188,33 @@ key/value pairs for the route variables. For the previous route, we would do:
"/articles/technology/42"
-This also works for host variables:
+This also works for host and query value variables:
r := mux.NewRouter()
r.Host("{subdomain}.domain.com").
Path("/articles/{category}/{id:[0-9]+}").
+ Queries("filter", "{filter}").
HandlerFunc(ArticleHandler).
Name("article")
- // url.String() will be "http://news.domain.com/articles/technology/42"
+ // url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla"
url, err := r.Get("article").URL("subdomain", "news",
- "category", "technology",
- "id", "42")
+ "category", "technology",
+ "id", "42",
+ "filter", "gorilla")
All variables defined in the route are required, and their values must
conform to the corresponding patterns. These requirements guarantee that a
generated URL will always match a registered route -- the only exception is
for explicitly defined "build-only" routes which never match.
+Regex support also exists for matching Headers within a route. For example, we could do:
+
+ r.HeadersRegexp("Content-Type", "application/(text|json)")
+
+...and the route will match both requests with a Content-Type of `application/json` as well as
+`application/text`
+
There's also a way to build only the URL host or path for a route:
use the methods URLHost() or URLPath() instead. For the previous route,
we would do:
@@ -193,7 +236,7 @@ as well:
// "http://news.domain.com/articles/technology/42"
url, err := r.Get("article").URL("subdomain", "news",
- "category", "technology",
- "id", "42")
+ "category", "technology",
+ "id", "42")
*/
package mux
diff --git a/vendor/github.com/gorilla/mux/mux.go b/vendor/github.com/gorilla/mux/mux.go
index af31d23..fb69196 100644
--- a/vendor/github.com/gorilla/mux/mux.go
+++ b/vendor/github.com/gorilla/mux/mux.go
@@ -5,11 +5,16 @@
package mux
import (
+ "errors"
"fmt"
"net/http"
"path"
+ "regexp"
+ "strings"
+)
- "github.com/gorilla/context"
+var (
+ ErrMethodMismatch = errors.New("method is not allowed")
)
// NewRouter returns a new router instance.
@@ -38,6 +43,10 @@ func NewRouter() *Router {
type Router struct {
// Configurable Handler to be used when no route matches.
NotFoundHandler http.Handler
+
+ // Configurable Handler to be used when the request method does not match the route.
+ MethodNotAllowedHandler http.Handler
+
// Parent route, if this is a subrouter.
parent parentRoute
// Routes to be matched, in order.
@@ -46,8 +55,14 @@ type Router struct {
namedRoutes map[string]*Route
// See Router.StrictSlash(). This defines the flag for new routes.
strictSlash bool
- // If true, do not clear the request context after handling the request
+ // See Router.SkipClean(). This defines the flag for new routes.
+ skipClean bool
+ // If true, do not clear the request context after handling the request.
+ // This has no effect when go1.7+ is used, since the context is stored
+ // on the request itself.
KeepContext bool
+ // see Router.UseEncodedPath(). This defines a flag for all routes.
+ useEncodedPath bool
}
// Match matches registered routes against the request.
@@ -57,6 +72,17 @@ func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
return true
}
}
+
+ if match.MatchErr == ErrMethodMismatch && r.MethodNotAllowedHandler != nil {
+ match.Handler = r.MethodNotAllowedHandler
+ return true
+ }
+
+ // Closest match for a router (includes sub-routers)
+ if r.NotFoundHandler != nil {
+ match.Handler = r.NotFoundHandler
+ return true
+ }
return false
}
@@ -65,35 +91,44 @@ func (r *Router) Match(req *http.Request, match *RouteMatch) bool {
// When there is a match, the route variables can be retrieved calling
// mux.Vars(request).
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
- // Clean path to canonical form and redirect.
- if p := cleanPath(req.URL.Path); p != req.URL.Path {
+ if !r.skipClean {
+ path := req.URL.Path
+ if r.useEncodedPath {
+ path = getPath(req)
+ }
+ // Clean path to canonical form and redirect.
+ if p := cleanPath(path); p != path {
- // Added 3 lines (Philip Schlump) - It was droping the query string and #whatever from query.
- // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue:
- // http://code.google.com/p/go/issues/detail?id=5252
- url := *req.URL
- url.Path = p
- p = url.String()
+ // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query.
+ // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue:
+ // http://code.google.com/p/go/issues/detail?id=5252
+ url := *req.URL
+ url.Path = p
+ p = url.String()
- w.Header().Set("Location", p)
- w.WriteHeader(http.StatusMovedPermanently)
- return
+ w.Header().Set("Location", p)
+ w.WriteHeader(http.StatusMovedPermanently)
+ return
+ }
}
var match RouteMatch
var handler http.Handler
if r.Match(req, &match) {
handler = match.Handler
- setVars(req, match.Vars)
- setCurrentRoute(req, match.Route)
+ req = setVars(req, match.Vars)
+ req = setCurrentRoute(req, match.Route)
}
+
+ if handler == nil && match.MatchErr == ErrMethodMismatch {
+ handler = methodNotAllowedHandler()
+ }
+
if handler == nil {
- handler = r.NotFoundHandler
- if handler == nil {
- handler = http.NotFoundHandler()
- }
+ handler = http.NotFoundHandler()
}
+
if !r.KeepContext {
- defer context.Clear(req)
+ defer contextClear(req)
}
handler.ServeHTTP(w, req)
}
@@ -128,10 +163,45 @@ func (r *Router) StrictSlash(value bool) *Router {
return r
}
+// SkipClean defines the path cleaning behaviour for new routes. The initial
+// value is false. Users should be careful about which routes are not cleaned
+//
+// When true, if the route path is "/path//to", it will remain with the double
+// slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/
+//
+// When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will
+// become /fetch/http/xkcd.com/534
+func (r *Router) SkipClean(value bool) *Router {
+ r.skipClean = value
+ return r
+}
+
+// UseEncodedPath tells the router to match the encoded original path
+// to the routes.
+// For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to".
+// This behavior has the drawback of needing to match routes against
+// r.RequestURI instead of r.URL.Path. Any modifications (such as http.StripPrefix)
+// to r.URL.Path will not affect routing when this flag is on and thus may
+// induce unintended behavior.
+//
+// If not called, the router will match the unencoded path to the routes.
+// For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to"
+func (r *Router) UseEncodedPath() *Router {
+ r.useEncodedPath = true
+ return r
+}
+
// ----------------------------------------------------------------------------
// parentRoute
// ----------------------------------------------------------------------------
+func (r *Router) getBuildScheme() string {
+ if r.parent != nil {
+ return r.parent.getBuildScheme()
+ }
+ return ""
+}
+
// getNamedRoutes returns the map where named routes are registered.
func (r *Router) getNamedRoutes() map[string]*Route {
if r.namedRoutes == nil {
@@ -165,7 +235,7 @@ func (r *Router) buildVars(m map[string]string) map[string]string {
// NewRoute registers an empty route.
func (r *Router) NewRoute() *Route {
- route := &Route{parent: r, strictSlash: r.strictSlash}
+ route := &Route{parent: r, strictSlash: r.strictSlash, skipClean: r.skipClean, useEncodedPath: r.useEncodedPath}
r.routes = append(r.routes, route)
return route
}
@@ -231,12 +301,59 @@ func (r *Router) Schemes(schemes ...string) *Route {
return r.NewRoute().Schemes(schemes...)
}
-// BuildVars registers a new route with a custom function for modifying
+// BuildVarsFunc registers a new route with a custom function for modifying
// route variables before building a URL.
func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route {
return r.NewRoute().BuildVarsFunc(f)
}
+// Walk walks the router and all its sub-routers, calling walkFn for each route
+// in the tree. The routes are walked in the order they were added. Sub-routers
+// are explored depth-first.
+func (r *Router) Walk(walkFn WalkFunc) error {
+ return r.walk(walkFn, []*Route{})
+}
+
+// SkipRouter is used as a return value from WalkFuncs to indicate that the
+// router that walk is about to descend down to should be skipped.
+var SkipRouter = errors.New("skip this router")
+
+// WalkFunc is the type of the function called for each route visited by Walk.
+// At every invocation, it is given the current route, and the current router,
+// and a list of ancestor routes that lead to the current route.
+type WalkFunc func(route *Route, router *Router, ancestors []*Route) error
+
+func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error {
+ for _, t := range r.routes {
+ err := walkFn(t, r, ancestors)
+ if err == SkipRouter {
+ continue
+ }
+ if err != nil {
+ return err
+ }
+ for _, sr := range t.matchers {
+ if h, ok := sr.(*Router); ok {
+ ancestors = append(ancestors, t)
+ err := h.walk(walkFn, ancestors)
+ if err != nil {
+ return err
+ }
+ ancestors = ancestors[:len(ancestors)-1]
+ }
+ }
+ if h, ok := t.handler.(*Router); ok {
+ ancestors = append(ancestors, t)
+ err := h.walk(walkFn, ancestors)
+ if err != nil {
+ return err
+ }
+ ancestors = ancestors[:len(ancestors)-1]
+ }
+ }
+ return nil
+}
+
// ----------------------------------------------------------------------------
// Context
// ----------------------------------------------------------------------------
@@ -246,6 +363,11 @@ type RouteMatch struct {
Route *Route
Handler http.Handler
Vars map[string]string
+
+ // MatchErr is set to appropriate matching error
+ // It is set to ErrMethodMismatch if there is a mismatch in
+ // the request method and route method
+ MatchErr error
}
type contextKey int
@@ -257,32 +379,58 @@ const (
// Vars returns the route variables for the current request, if any.
func Vars(r *http.Request) map[string]string {
- if rv := context.Get(r, varsKey); rv != nil {
+ if rv := contextGet(r, varsKey); rv != nil {
return rv.(map[string]string)
}
return nil
}
// CurrentRoute returns the matched route for the current request, if any.
+// This only works when called inside the handler of the matched route
+// because the matched route is stored in the request context which is cleared
+// after the handler returns, unless the KeepContext option is set on the
+// Router.
func CurrentRoute(r *http.Request) *Route {
- if rv := context.Get(r, routeKey); rv != nil {
+ if rv := contextGet(r, routeKey); rv != nil {
return rv.(*Route)
}
return nil
}
-func setVars(r *http.Request, val interface{}) {
- context.Set(r, varsKey, val)
+func setVars(r *http.Request, val interface{}) *http.Request {
+ return contextSet(r, varsKey, val)
}
-func setCurrentRoute(r *http.Request, val interface{}) {
- context.Set(r, routeKey, val)
+func setCurrentRoute(r *http.Request, val interface{}) *http.Request {
+ return contextSet(r, routeKey, val)
}
// ----------------------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------------------
+// getPath returns the escaped path if possible; doing what URL.EscapedPath()
+// which was added in go1.5 does
+func getPath(req *http.Request) string {
+ if req.RequestURI != "" {
+ // Extract the path from RequestURI (which is escaped unlike URL.Path)
+ // as detailed here as detailed in https://golang.org/pkg/net/url/#URL
+ // for < 1.5 server side workaround
+ // http://localhost/path/here?v=1 -> /path/here
+ path := req.RequestURI
+ path = strings.TrimPrefix(path, req.URL.Scheme+`://`)
+ path = strings.TrimPrefix(path, req.URL.Host)
+ if i := strings.LastIndex(path, "?"); i > -1 {
+ path = path[:i]
+ }
+ if i := strings.LastIndex(path, "#"); i > -1 {
+ path = path[:i]
+ }
+ return path
+ }
+ return req.URL.Path
+}
+
// cleanPath returns the canonical path for p, eliminating . and .. elements.
// Borrowed from the net/http package.
func cleanPath(p string) string {
@@ -298,6 +446,7 @@ func cleanPath(p string) string {
if p[len(p)-1] == '/' && np != "/" {
np += "/"
}
+
return np
}
@@ -313,13 +462,24 @@ func uniqueVars(s1, s2 []string) error {
return nil
}
-// mapFromPairs converts variadic string parameters to a string map.
-func mapFromPairs(pairs ...string) (map[string]string, error) {
+// checkPairs returns the count of strings passed in, and an error if
+// the count is not an even number.
+func checkPairs(pairs ...string) (int, error) {
length := len(pairs)
if length%2 != 0 {
- return nil, fmt.Errorf(
+ return length, fmt.Errorf(
"mux: number of parameters must be multiple of 2, got %v", pairs)
}
+ return length, nil
+}
+
+// mapFromPairsToString converts variadic string parameters to a
+// string to string map.
+func mapFromPairsToString(pairs ...string) (map[string]string, error) {
+ length, err := checkPairs(pairs...)
+ if err != nil {
+ return nil, err
+ }
m := make(map[string]string, length/2)
for i := 0; i < length; i += 2 {
m[pairs[i]] = pairs[i+1]
@@ -327,6 +487,24 @@ func mapFromPairs(pairs ...string) (map[string]string, error) {
return m, nil
}
+// mapFromPairsToRegex converts variadic string parameters to a
+// string to regex map.
+func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) {
+ length, err := checkPairs(pairs...)
+ if err != nil {
+ return nil, err
+ }
+ m := make(map[string]*regexp.Regexp, length/2)
+ for i := 0; i < length; i += 2 {
+ regex, err := regexp.Compile(pairs[i+1])
+ if err != nil {
+ return nil, err
+ }
+ m[pairs[i]] = regex
+ }
+ return m, nil
+}
+
// matchInArray returns true if the given string value is in the array.
func matchInArray(arr []string, value string) bool {
for _, v := range arr {
@@ -337,9 +515,8 @@ func matchInArray(arr []string, value string) bool {
return false
}
-// matchMap returns true if the given key/value pairs exist in a given map.
-func matchMap(toCheck map[string]string, toMatch map[string][]string,
- canonicalKey bool) bool {
+// matchMapWithString returns true if the given key/value pairs exist in a given map.
+func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool {
for k, v := range toCheck {
// Check if key exists.
if canonicalKey {
@@ -364,3 +541,40 @@ func matchMap(toCheck map[string]string, toMatch map[string][]string,
}
return true
}
+
+// matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against
+// the given regex
+func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool {
+ for k, v := range toCheck {
+ // Check if key exists.
+ if canonicalKey {
+ k = http.CanonicalHeaderKey(k)
+ }
+ if values := toMatch[k]; values == nil {
+ return false
+ } else if v != nil {
+ // If value was defined as an empty string we only check that the
+ // key exists. Otherwise we also check for equality.
+ valueExists := false
+ for _, value := range values {
+ if v.MatchString(value) {
+ valueExists = true
+ break
+ }
+ }
+ if !valueExists {
+ return false
+ }
+ }
+ }
+ return true
+}
+
+// methodNotAllowed replies to the request with an HTTP status code 405.
+func methodNotAllowed(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusMethodNotAllowed)
+}
+
+// methodNotAllowedHandler returns a simple request handler
+// that replies to each request with a status code 405.
+func methodNotAllowedHandler() http.Handler { return http.HandlerFunc(methodNotAllowed) }
diff --git a/vendor/github.com/gorilla/mux/mux_test.go b/vendor/github.com/gorilla/mux/mux_test.go
index 075dedb..484fab4 100644
--- a/vendor/github.com/gorilla/mux/mux_test.go
+++ b/vendor/github.com/gorilla/mux/mux_test.go
@@ -5,20 +5,42 @@
package mux
import (
+ "bufio"
+ "bytes"
+ "errors"
"fmt"
"net/http"
+ "net/url"
+ "reflect"
+ "strings"
"testing"
-
- "github.com/gorilla/context"
)
+func (r *Route) GoString() string {
+ matchers := make([]string, len(r.matchers))
+ for i, m := range r.matchers {
+ matchers[i] = fmt.Sprintf("%#v", m)
+ }
+ return fmt.Sprintf("&Route{matchers:[]matcher{%s}}", strings.Join(matchers, ", "))
+}
+
+func (r *routeRegexp) GoString() string {
+ return fmt.Sprintf("&routeRegexp{template: %q, matchHost: %t, matchQuery: %t, strictSlash: %t, regexp: regexp.MustCompile(%q), reverse: %q, varsN: %v, varsR: %v", r.template, r.matchHost, r.matchQuery, r.strictSlash, r.regexp.String(), r.reverse, r.varsN, r.varsR)
+}
+
type routeTest struct {
title string // title of the test
route *Route // the route being tested
request *http.Request // a request to test the route
vars map[string]string // the expected vars of the match
- host string // the expected host of the match
- path string // the expected path of the match
+ scheme string // the expected scheme of the built URL
+ host string // the expected host of the built URL
+ path string // the expected path of the built URL
+ query string // the expected query string of the built URL
+ pathTemplate string // the expected path template of the route
+ hostTemplate string // the expected host template of the route
+ methods []string // the expected route methods
+ pathRegexp string // the expected path regexp
shouldMatch bool // whether the request is expected to match the route at all
shouldRedirect bool // whether the request should result in a redirect
}
@@ -100,71 +122,89 @@ func TestHost(t *testing.T) {
shouldMatch: false,
},
{
- title: "Host route with pattern, match",
- route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"),
- request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
- vars: map[string]string{"v1": "bbb"},
- host: "aaa.bbb.ccc",
- path: "",
- shouldMatch: true,
+ title: "Host route with pattern, match",
+ route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"),
+ request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v1": "bbb"},
+ host: "aaa.bbb.ccc",
+ path: "",
+ hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`,
+ shouldMatch: true,
},
{
- title: "Host route with pattern, wrong host in request URL",
- route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"),
- request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
- vars: map[string]string{"v1": "bbb"},
- host: "aaa.bbb.ccc",
- path: "",
- shouldMatch: false,
+ title: "Host route with pattern, additional capturing group, match",
+ route: new(Route).Host("aaa.{v1:[a-z]{2}(?:b|c)}.ccc"),
+ request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v1": "bbb"},
+ host: "aaa.bbb.ccc",
+ path: "",
+ hostTemplate: `aaa.{v1:[a-z]{2}(?:b|c)}.ccc`,
+ shouldMatch: true,
},
{
- title: "Host route with multiple patterns, match",
- route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"),
- request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
- vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"},
- host: "aaa.bbb.ccc",
- path: "",
- shouldMatch: true,
+ title: "Host route with pattern, wrong host in request URL",
+ route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc"),
+ request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
+ vars: map[string]string{"v1": "bbb"},
+ host: "aaa.bbb.ccc",
+ path: "",
+ hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`,
+ shouldMatch: false,
},
{
- title: "Host route with multiple patterns, wrong host in request URL",
- route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"),
- request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
- vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"},
- host: "aaa.bbb.ccc",
- path: "",
- shouldMatch: false,
+ title: "Host route with multiple patterns, match",
+ route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"),
+ request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"},
+ host: "aaa.bbb.ccc",
+ path: "",
+ hostTemplate: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`,
+ shouldMatch: true,
},
{
- title: "Path route with single pattern with pipe, match",
- route: new(Route).Path("/{category:a|b/c}"),
- request: newRequest("GET", "http://localhost/a"),
- vars: map[string]string{"category": "a"},
- host: "",
- path: "/a",
- shouldMatch: true,
+ title: "Host route with multiple patterns, wrong host in request URL",
+ route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}"),
+ request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
+ vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc"},
+ host: "aaa.bbb.ccc",
+ path: "",
+ hostTemplate: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`,
+ shouldMatch: false,
},
{
- title: "Path route with single pattern with pipe, match",
- route: new(Route).Path("/{category:a|b/c}"),
- request: newRequest("GET", "http://localhost/b/c"),
- vars: map[string]string{"category": "b/c"},
- host: "",
- path: "/b/c",
- shouldMatch: true,
+ title: "Host route with hyphenated name and pattern, match",
+ route: new(Route).Host("aaa.{v-1:[a-z]{3}}.ccc"),
+ request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v-1": "bbb"},
+ host: "aaa.bbb.ccc",
+ path: "",
+ hostTemplate: `aaa.{v-1:[a-z]{3}}.ccc`,
+ shouldMatch: true,
},
{
- title: "Path route with multiple patterns with pipe, match",
- route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"),
- request: newRequest("GET", "http://localhost/a/product_name/1"),
- vars: map[string]string{"category": "a", "product": "product_name", "id": "1"},
- host: "",
- path: "/a/product_name/1",
- shouldMatch: true,
+ title: "Host route with hyphenated name and pattern, additional capturing group, match",
+ route: new(Route).Host("aaa.{v-1:[a-z]{2}(?:b|c)}.ccc"),
+ request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v-1": "bbb"},
+ host: "aaa.bbb.ccc",
+ path: "",
+ hostTemplate: `aaa.{v-1:[a-z]{2}(?:b|c)}.ccc`,
+ shouldMatch: true,
+ },
+ {
+ title: "Host route with multiple hyphenated names and patterns, match",
+ route: new(Route).Host("{v-1:[a-z]{3}}.{v-2:[a-z]{3}}.{v-3:[a-z]{3}}"),
+ request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v-1": "aaa", "v-2": "bbb", "v-3": "ccc"},
+ host: "aaa.bbb.ccc",
+ path: "",
+ hostTemplate: `{v-1:[a-z]{3}}.{v-2:[a-z]{3}}.{v-3:[a-z]{3}}`,
+ shouldMatch: true,
},
}
for _, test := range tests {
testRoute(t, test)
+ testTemplate(t, test)
}
}
@@ -189,22 +229,50 @@ func TestPath(t *testing.T) {
shouldMatch: true,
},
{
- title: "Path route, do not match with trailing slash in path",
- route: new(Route).Path("/111/"),
- request: newRequest("GET", "http://localhost/111"),
- vars: map[string]string{},
- host: "",
- path: "/111",
- shouldMatch: false,
+ title: "Path route, do not match with trailing slash in path",
+ route: new(Route).Path("/111/"),
+ request: newRequest("GET", "http://localhost/111"),
+ vars: map[string]string{},
+ host: "",
+ path: "/111",
+ pathTemplate: `/111/`,
+ pathRegexp: `^/111/$`,
+ shouldMatch: false,
},
{
- title: "Path route, do not match with trailing slash in request",
- route: new(Route).Path("/111"),
- request: newRequest("GET", "http://localhost/111/"),
- vars: map[string]string{},
- host: "",
- path: "/111/",
- shouldMatch: false,
+ title: "Path route, do not match with trailing slash in request",
+ route: new(Route).Path("/111"),
+ request: newRequest("GET", "http://localhost/111/"),
+ vars: map[string]string{},
+ host: "",
+ path: "/111/",
+ pathTemplate: `/111`,
+ shouldMatch: false,
+ },
+ {
+ title: "Path route, match root with no host",
+ route: new(Route).Path("/"),
+ request: newRequest("GET", "/"),
+ vars: map[string]string{},
+ host: "",
+ path: "/",
+ pathTemplate: `/`,
+ pathRegexp: `^/$`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route, match root with no host, App Engine format",
+ route: new(Route).Path("/"),
+ request: func() *http.Request {
+ r := newRequest("GET", "http://localhost/")
+ r.RequestURI = "/"
+ return r
+ }(),
+ vars: map[string]string{},
+ host: "",
+ path: "/",
+ pathTemplate: `/`,
+ shouldMatch: true,
},
{
title: "Path route, wrong path in request in request URL",
@@ -216,45 +284,161 @@ func TestPath(t *testing.T) {
shouldMatch: false,
},
{
- title: "Path route with pattern, match",
- route: new(Route).Path("/111/{v1:[0-9]{3}}/333"),
- request: newRequest("GET", "http://localhost/111/222/333"),
- vars: map[string]string{"v1": "222"},
- host: "",
- path: "/111/222/333",
- shouldMatch: true,
+ title: "Path route with pattern, match",
+ route: new(Route).Path("/111/{v1:[0-9]{3}}/333"),
+ request: newRequest("GET", "http://localhost/111/222/333"),
+ vars: map[string]string{"v1": "222"},
+ host: "",
+ path: "/111/222/333",
+ pathTemplate: `/111/{v1:[0-9]{3}}/333`,
+ shouldMatch: true,
},
{
- title: "Path route with pattern, URL in request does not match",
- route: new(Route).Path("/111/{v1:[0-9]{3}}/333"),
- request: newRequest("GET", "http://localhost/111/aaa/333"),
- vars: map[string]string{"v1": "222"},
- host: "",
- path: "/111/222/333",
- shouldMatch: false,
+ title: "Path route with pattern, URL in request does not match",
+ route: new(Route).Path("/111/{v1:[0-9]{3}}/333"),
+ request: newRequest("GET", "http://localhost/111/aaa/333"),
+ vars: map[string]string{"v1": "222"},
+ host: "",
+ path: "/111/222/333",
+ pathTemplate: `/111/{v1:[0-9]{3}}/333`,
+ pathRegexp: `^/111/(?P[0-9]{3})/333$`,
+ shouldMatch: false,
},
{
- title: "Path route with multiple patterns, match",
- route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"),
- request: newRequest("GET", "http://localhost/111/222/333"),
- vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"},
- host: "",
- path: "/111/222/333",
- shouldMatch: true,
+ title: "Path route with multiple patterns, match",
+ route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"),
+ request: newRequest("GET", "http://localhost/111/222/333"),
+ vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"},
+ host: "",
+ path: "/111/222/333",
+ pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}`,
+ pathRegexp: `^/(?P[0-9]{3})/(?P[0-9]{3})/(?P[0-9]{3})$`,
+ shouldMatch: true,
},
{
- title: "Path route with multiple patterns, URL in request does not match",
- route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"),
- request: newRequest("GET", "http://localhost/111/aaa/333"),
- vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"},
- host: "",
- path: "/111/222/333",
- shouldMatch: false,
+ title: "Path route with multiple patterns, URL in request does not match",
+ route: new(Route).Path("/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}"),
+ request: newRequest("GET", "http://localhost/111/aaa/333"),
+ vars: map[string]string{"v1": "111", "v2": "222", "v3": "333"},
+ host: "",
+ path: "/111/222/333",
+ pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}/{v3:[0-9]{3}}`,
+ pathRegexp: `^/(?P[0-9]{3})/(?P[0-9]{3})/(?P[0-9]{3})$`,
+ shouldMatch: false,
+ },
+ {
+ title: "Path route with multiple patterns with pipe, match",
+ route: new(Route).Path("/{category:a|(?:b/c)}/{product}/{id:[0-9]+}"),
+ request: newRequest("GET", "http://localhost/a/product_name/1"),
+ vars: map[string]string{"category": "a", "product": "product_name", "id": "1"},
+ host: "",
+ path: "/a/product_name/1",
+ pathTemplate: `/{category:a|(?:b/c)}/{product}/{id:[0-9]+}`,
+ pathRegexp: `^/(?Pa|(?:b/c))/(?P[^/]+)/(?P[0-9]+)$`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with hyphenated name and pattern, match",
+ route: new(Route).Path("/111/{v-1:[0-9]{3}}/333"),
+ request: newRequest("GET", "http://localhost/111/222/333"),
+ vars: map[string]string{"v-1": "222"},
+ host: "",
+ path: "/111/222/333",
+ pathTemplate: `/111/{v-1:[0-9]{3}}/333`,
+ pathRegexp: `^/111/(?P[0-9]{3})/333$`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with multiple hyphenated names and patterns, match",
+ route: new(Route).Path("/{v-1:[0-9]{3}}/{v-2:[0-9]{3}}/{v-3:[0-9]{3}}"),
+ request: newRequest("GET", "http://localhost/111/222/333"),
+ vars: map[string]string{"v-1": "111", "v-2": "222", "v-3": "333"},
+ host: "",
+ path: "/111/222/333",
+ pathTemplate: `/{v-1:[0-9]{3}}/{v-2:[0-9]{3}}/{v-3:[0-9]{3}}`,
+ pathRegexp: `^/(?P[0-9]{3})/(?P[0-9]{3})/(?P[0-9]{3})$`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with multiple hyphenated names and patterns with pipe, match",
+ route: new(Route).Path("/{product-category:a|(?:b/c)}/{product-name}/{product-id:[0-9]+}"),
+ request: newRequest("GET", "http://localhost/a/product_name/1"),
+ vars: map[string]string{"product-category": "a", "product-name": "product_name", "product-id": "1"},
+ host: "",
+ path: "/a/product_name/1",
+ pathTemplate: `/{product-category:a|(?:b/c)}/{product-name}/{product-id:[0-9]+}`,
+ pathRegexp: `^/(?Pa|(?:b/c))/(?P[^/]+)/(?P[0-9]+)$`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with multiple hyphenated names and patterns with pipe and case insensitive, match",
+ route: new(Route).Path("/{type:(?i:daily|mini|variety)}-{date:\\d{4,4}-\\d{2,2}-\\d{2,2}}"),
+ request: newRequest("GET", "http://localhost/daily-2016-01-01"),
+ vars: map[string]string{"type": "daily", "date": "2016-01-01"},
+ host: "",
+ path: "/daily-2016-01-01",
+ pathTemplate: `/{type:(?i:daily|mini|variety)}-{date:\d{4,4}-\d{2,2}-\d{2,2}}`,
+ pathRegexp: `^/(?P(?i:daily|mini|variety))-(?P\d{4,4}-\d{2,2}-\d{2,2})$`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with empty match right after other match",
+ route: new(Route).Path(`/{v1:[0-9]*}{v2:[a-z]*}/{v3:[0-9]*}`),
+ request: newRequest("GET", "http://localhost/111/222"),
+ vars: map[string]string{"v1": "111", "v2": "", "v3": "222"},
+ host: "",
+ path: "/111/222",
+ pathTemplate: `/{v1:[0-9]*}{v2:[a-z]*}/{v3:[0-9]*}`,
+ pathRegexp: `^/(?P[0-9]*)(?P[a-z]*)/(?P[0-9]*)$`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with single pattern with pipe, match",
+ route: new(Route).Path("/{category:a|b/c}"),
+ request: newRequest("GET", "http://localhost/a"),
+ vars: map[string]string{"category": "a"},
+ host: "",
+ path: "/a",
+ pathTemplate: `/{category:a|b/c}`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with single pattern with pipe, match",
+ route: new(Route).Path("/{category:a|b/c}"),
+ request: newRequest("GET", "http://localhost/b/c"),
+ vars: map[string]string{"category": "b/c"},
+ host: "",
+ path: "/b/c",
+ pathTemplate: `/{category:a|b/c}`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with multiple patterns with pipe, match",
+ route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"),
+ request: newRequest("GET", "http://localhost/a/product_name/1"),
+ vars: map[string]string{"category": "a", "product": "product_name", "id": "1"},
+ host: "",
+ path: "/a/product_name/1",
+ pathTemplate: `/{category:a|b/c}/{product}/{id:[0-9]+}`,
+ shouldMatch: true,
+ },
+ {
+ title: "Path route with multiple patterns with pipe, match",
+ route: new(Route).Path("/{category:a|b/c}/{product}/{id:[0-9]+}"),
+ request: newRequest("GET", "http://localhost/b/c/product_name/1"),
+ vars: map[string]string{"category": "b/c", "product": "product_name", "id": "1"},
+ host: "",
+ path: "/b/c/product_name/1",
+ pathTemplate: `/{category:a|b/c}/{product}/{id:[0-9]+}`,
+ shouldMatch: true,
},
}
for _, test := range tests {
testRoute(t, test)
+ testTemplate(t, test)
+ testUseEscapedRoute(t, test)
+ testRegexp(t, test)
}
}
@@ -288,108 +472,158 @@ func TestPathPrefix(t *testing.T) {
shouldMatch: false,
},
{
- title: "PathPrefix route with pattern, match",
- route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"),
- request: newRequest("GET", "http://localhost/111/222/333"),
- vars: map[string]string{"v1": "222"},
- host: "",
- path: "/111/222",
- shouldMatch: true,
+ title: "PathPrefix route with pattern, match",
+ route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"),
+ request: newRequest("GET", "http://localhost/111/222/333"),
+ vars: map[string]string{"v1": "222"},
+ host: "",
+ path: "/111/222",
+ pathTemplate: `/111/{v1:[0-9]{3}}`,
+ shouldMatch: true,
},
{
- title: "PathPrefix route with pattern, URL prefix in request does not match",
- route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"),
- request: newRequest("GET", "http://localhost/111/aaa/333"),
- vars: map[string]string{"v1": "222"},
- host: "",
- path: "/111/222",
- shouldMatch: false,
+ title: "PathPrefix route with pattern, URL prefix in request does not match",
+ route: new(Route).PathPrefix("/111/{v1:[0-9]{3}}"),
+ request: newRequest("GET", "http://localhost/111/aaa/333"),
+ vars: map[string]string{"v1": "222"},
+ host: "",
+ path: "/111/222",
+ pathTemplate: `/111/{v1:[0-9]{3}}`,
+ shouldMatch: false,
},
{
- title: "PathPrefix route with multiple patterns, match",
- route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"),
- request: newRequest("GET", "http://localhost/111/222/333"),
- vars: map[string]string{"v1": "111", "v2": "222"},
- host: "",
- path: "/111/222",
- shouldMatch: true,
+ title: "PathPrefix route with multiple patterns, match",
+ route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"),
+ request: newRequest("GET", "http://localhost/111/222/333"),
+ vars: map[string]string{"v1": "111", "v2": "222"},
+ host: "",
+ path: "/111/222",
+ pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}`,
+ shouldMatch: true,
},
{
- title: "PathPrefix route with multiple patterns, URL prefix in request does not match",
- route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"),
- request: newRequest("GET", "http://localhost/111/aaa/333"),
- vars: map[string]string{"v1": "111", "v2": "222"},
- host: "",
- path: "/111/222",
- shouldMatch: false,
+ title: "PathPrefix route with multiple patterns, URL prefix in request does not match",
+ route: new(Route).PathPrefix("/{v1:[0-9]{3}}/{v2:[0-9]{3}}"),
+ request: newRequest("GET", "http://localhost/111/aaa/333"),
+ vars: map[string]string{"v1": "111", "v2": "222"},
+ host: "",
+ path: "/111/222",
+ pathTemplate: `/{v1:[0-9]{3}}/{v2:[0-9]{3}}`,
+ shouldMatch: false,
},
}
for _, test := range tests {
testRoute(t, test)
+ testTemplate(t, test)
+ testUseEscapedRoute(t, test)
}
}
-func TestHostPath(t *testing.T) {
+func TestSchemeHostPath(t *testing.T) {
tests := []routeTest{
{
- title: "Host and Path route, match",
- route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"),
- request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: true,
+ title: "Host and Path route, match",
+ route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"),
+ request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{},
+ scheme: "http",
+ host: "aaa.bbb.ccc",
+ path: "/111/222/333",
+ pathTemplate: `/111/222/333`,
+ hostTemplate: `aaa.bbb.ccc`,
+ shouldMatch: true,
},
{
- title: "Host and Path route, wrong host in request URL",
- route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"),
- request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: false,
+ title: "Scheme, Host, and Path route, match",
+ route: new(Route).Schemes("https").Host("aaa.bbb.ccc").Path("/111/222/333"),
+ request: newRequest("GET", "https://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{},
+ scheme: "https",
+ host: "aaa.bbb.ccc",
+ path: "/111/222/333",
+ pathTemplate: `/111/222/333`,
+ hostTemplate: `aaa.bbb.ccc`,
+ shouldMatch: true,
},
{
- title: "Host and Path route with pattern, match",
- route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),
- request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
- vars: map[string]string{"v1": "bbb", "v2": "222"},
- host: "aaa.bbb.ccc",
- path: "/111/222/333",
- shouldMatch: true,
+ title: "Host and Path route, wrong host in request URL",
+ route: new(Route).Host("aaa.bbb.ccc").Path("/111/222/333"),
+ request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
+ vars: map[string]string{},
+ scheme: "http",
+ host: "aaa.bbb.ccc",
+ path: "/111/222/333",
+ pathTemplate: `/111/222/333`,
+ hostTemplate: `aaa.bbb.ccc`,
+ shouldMatch: false,
},
{
- title: "Host and Path route with pattern, URL in request does not match",
- route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),
- request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
- vars: map[string]string{"v1": "bbb", "v2": "222"},
- host: "aaa.bbb.ccc",
- path: "/111/222/333",
- shouldMatch: false,
+ title: "Host and Path route with pattern, match",
+ route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),
+ request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v1": "bbb", "v2": "222"},
+ scheme: "http",
+ host: "aaa.bbb.ccc",
+ path: "/111/222/333",
+ pathTemplate: `/111/{v2:[0-9]{3}}/333`,
+ hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`,
+ shouldMatch: true,
},
{
- title: "Host and Path route with multiple patterns, match",
- route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"),
- request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
- vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"},
- host: "aaa.bbb.ccc",
- path: "/111/222/333",
- shouldMatch: true,
+ title: "Scheme, Host, and Path route with host and path patterns, match",
+ route: new(Route).Schemes("ftp", "ssss").Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),
+ request: newRequest("GET", "ssss://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v1": "bbb", "v2": "222"},
+ scheme: "ftp",
+ host: "aaa.bbb.ccc",
+ path: "/111/222/333",
+ pathTemplate: `/111/{v2:[0-9]{3}}/333`,
+ hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`,
+ shouldMatch: true,
},
{
- title: "Host and Path route with multiple patterns, URL in request does not match",
- route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"),
- request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
- vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"},
- host: "aaa.bbb.ccc",
- path: "/111/222/333",
- shouldMatch: false,
+ title: "Host and Path route with pattern, URL in request does not match",
+ route: new(Route).Host("aaa.{v1:[a-z]{3}}.ccc").Path("/111/{v2:[0-9]{3}}/333"),
+ request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
+ vars: map[string]string{"v1": "bbb", "v2": "222"},
+ scheme: "http",
+ host: "aaa.bbb.ccc",
+ path: "/111/222/333",
+ pathTemplate: `/111/{v2:[0-9]{3}}/333`,
+ hostTemplate: `aaa.{v1:[a-z]{3}}.ccc`,
+ shouldMatch: false,
+ },
+ {
+ title: "Host and Path route with multiple patterns, match",
+ route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"),
+ request: newRequest("GET", "http://aaa.bbb.ccc/111/222/333"),
+ vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"},
+ scheme: "http",
+ host: "aaa.bbb.ccc",
+ path: "/111/222/333",
+ pathTemplate: `/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}`,
+ hostTemplate: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`,
+ shouldMatch: true,
+ },
+ {
+ title: "Host and Path route with multiple patterns, URL in request does not match",
+ route: new(Route).Host("{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}").Path("/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}"),
+ request: newRequest("GET", "http://aaa.222.ccc/111/222/333"),
+ vars: map[string]string{"v1": "aaa", "v2": "bbb", "v3": "ccc", "v4": "111", "v5": "222", "v6": "333"},
+ scheme: "http",
+ host: "aaa.bbb.ccc",
+ path: "/111/222/333",
+ pathTemplate: `/{v4:[0-9]{3}}/{v5:[0-9]{3}}/{v6:[0-9]{3}}`,
+ hostTemplate: `{v1:[a-z]{3}}.{v2:[a-z]{3}}.{v3:[a-z]{3}}`,
+ shouldMatch: false,
},
}
for _, test := range tests {
testRoute(t, test)
+ testTemplate(t, test)
+ testUseEscapedRoute(t, test)
}
}
@@ -425,12 +659,30 @@ func TestHeaders(t *testing.T) {
path: "",
shouldMatch: false,
},
+ {
+ title: "Headers route, regex header values to match",
+ route: new(Route).Headers("foo", "ba[zr]"),
+ request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "bar"}),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
+ {
+ title: "Headers route, regex header values to match",
+ route: new(Route).HeadersRegexp("foo", "ba[zr]"),
+ request: newRequestHeaders("GET", "http://localhost", map[string]string{"foo": "baz"}),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: true,
+ },
}
for _, test := range tests {
testRoute(t, test)
+ testTemplate(t, test)
}
-
}
func TestMethods(t *testing.T) {
@@ -442,6 +694,7 @@ func TestMethods(t *testing.T) {
vars: map[string]string{},
host: "",
path: "",
+ methods: []string{"GET", "POST"},
shouldMatch: true,
},
{
@@ -451,6 +704,7 @@ func TestMethods(t *testing.T) {
vars: map[string]string{},
host: "",
path: "",
+ methods: []string{"GET", "POST"},
shouldMatch: true,
},
{
@@ -460,12 +714,25 @@ func TestMethods(t *testing.T) {
vars: map[string]string{},
host: "",
path: "",
+ methods: []string{"GET", "POST"},
shouldMatch: false,
},
+ {
+ title: "Route without methods",
+ route: new(Route),
+ request: newRequest("PUT", "http://localhost"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ methods: []string{},
+ shouldMatch: true,
+ },
}
for _, test := range tests {
testRoute(t, test)
+ testTemplate(t, test)
+ testMethods(t, test)
}
}
@@ -478,25 +745,32 @@ func TestQueries(t *testing.T) {
vars: map[string]string{},
host: "",
path: "",
+ query: "foo=bar&baz=ding",
shouldMatch: true,
},
{
- title: "Queries route, match with a query string",
- route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"),
- request: newRequest("GET", "http://www.example.com/api?foo=bar&baz=ding"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: true,
+ title: "Queries route, match with a query string",
+ route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"),
+ request: newRequest("GET", "http://www.example.com/api?foo=bar&baz=ding"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ query: "foo=bar&baz=ding",
+ pathTemplate: `/api`,
+ hostTemplate: `www.example.com`,
+ shouldMatch: true,
},
{
- title: "Queries route, match with a query string out of order",
- route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"),
- request: newRequest("GET", "http://www.example.com/api?baz=ding&foo=bar"),
- vars: map[string]string{},
- host: "",
- path: "",
- shouldMatch: true,
+ title: "Queries route, match with a query string out of order",
+ route: new(Route).Host("www.example.com").Path("/api").Queries("foo", "bar", "baz", "ding"),
+ request: newRequest("GET", "http://www.example.com/api?baz=ding&foo=bar"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ query: "foo=bar&baz=ding",
+ pathTemplate: `/api`,
+ hostTemplate: `www.example.com`,
+ shouldMatch: true,
},
{
title: "Queries route, bad query",
@@ -514,6 +788,7 @@ func TestQueries(t *testing.T) {
vars: map[string]string{"v1": "bar"},
host: "",
path: "",
+ query: "foo=bar",
shouldMatch: true,
},
{
@@ -523,6 +798,7 @@ func TestQueries(t *testing.T) {
vars: map[string]string{"v1": "bar", "v2": "ding"},
host: "",
path: "",
+ query: "foo=bar&baz=ding",
shouldMatch: true,
},
{
@@ -532,6 +808,7 @@ func TestQueries(t *testing.T) {
vars: map[string]string{"v1": "10"},
host: "",
path: "",
+ query: "foo=10",
shouldMatch: true,
},
{
@@ -543,10 +820,176 @@ func TestQueries(t *testing.T) {
path: "",
shouldMatch: false,
},
+ {
+ title: "Queries route with regexp pattern with quantifier, match",
+ route: new(Route).Queries("foo", "{v1:[0-9]{1}}"),
+ request: newRequest("GET", "http://localhost?foo=1"),
+ vars: map[string]string{"v1": "1"},
+ host: "",
+ path: "",
+ query: "foo=1",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with regexp pattern with quantifier, additional variable in query string, match",
+ route: new(Route).Queries("foo", "{v1:[0-9]{1}}"),
+ request: newRequest("GET", "http://localhost?bar=2&foo=1"),
+ vars: map[string]string{"v1": "1"},
+ host: "",
+ path: "",
+ query: "foo=1",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with regexp pattern with quantifier, regexp does not match",
+ route: new(Route).Queries("foo", "{v1:[0-9]{1}}"),
+ request: newRequest("GET", "http://localhost?foo=12"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
+ {
+ title: "Queries route with regexp pattern with quantifier, additional capturing group",
+ route: new(Route).Queries("foo", "{v1:[0-9]{1}(?:a|b)}"),
+ request: newRequest("GET", "http://localhost?foo=1a"),
+ vars: map[string]string{"v1": "1a"},
+ host: "",
+ path: "",
+ query: "foo=1a",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with regexp pattern with quantifier, additional variable in query string, regexp does not match",
+ route: new(Route).Queries("foo", "{v1:[0-9]{1}}"),
+ request: newRequest("GET", "http://localhost?foo=12"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
+ {
+ title: "Queries route with hyphenated name, match",
+ route: new(Route).Queries("foo", "{v-1}"),
+ request: newRequest("GET", "http://localhost?foo=bar"),
+ vars: map[string]string{"v-1": "bar"},
+ host: "",
+ path: "",
+ query: "foo=bar",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with multiple hyphenated names, match",
+ route: new(Route).Queries("foo", "{v-1}", "baz", "{v-2}"),
+ request: newRequest("GET", "http://localhost?foo=bar&baz=ding"),
+ vars: map[string]string{"v-1": "bar", "v-2": "ding"},
+ host: "",
+ path: "",
+ query: "foo=bar&baz=ding",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with hyphenate name and pattern, match",
+ route: new(Route).Queries("foo", "{v-1:[0-9]+}"),
+ request: newRequest("GET", "http://localhost?foo=10"),
+ vars: map[string]string{"v-1": "10"},
+ host: "",
+ path: "",
+ query: "foo=10",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with hyphenated name and pattern with quantifier, additional capturing group",
+ route: new(Route).Queries("foo", "{v-1:[0-9]{1}(?:a|b)}"),
+ request: newRequest("GET", "http://localhost?foo=1a"),
+ vars: map[string]string{"v-1": "1a"},
+ host: "",
+ path: "",
+ query: "foo=1a",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with empty value, should match",
+ route: new(Route).Queries("foo", ""),
+ request: newRequest("GET", "http://localhost?foo=bar"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ query: "foo=",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with empty value and no parameter in request, should not match",
+ route: new(Route).Queries("foo", ""),
+ request: newRequest("GET", "http://localhost"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
+ {
+ title: "Queries route with empty value and empty parameter in request, should match",
+ route: new(Route).Queries("foo", ""),
+ request: newRequest("GET", "http://localhost?foo="),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ query: "foo=",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route with overlapping value, should not match",
+ route: new(Route).Queries("foo", "bar"),
+ request: newRequest("GET", "http://localhost?foo=barfoo"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
+ {
+ title: "Queries route with no parameter in request, should not match",
+ route: new(Route).Queries("foo", "{bar}"),
+ request: newRequest("GET", "http://localhost"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
+ {
+ title: "Queries route with empty parameter in request, should match",
+ route: new(Route).Queries("foo", "{bar}"),
+ request: newRequest("GET", "http://localhost?foo="),
+ vars: map[string]string{"foo": ""},
+ host: "",
+ path: "",
+ query: "foo=",
+ shouldMatch: true,
+ },
+ {
+ title: "Queries route, bad submatch",
+ route: new(Route).Queries("foo", "bar", "baz", "ding"),
+ request: newRequest("GET", "http://localhost?fffoo=bar&baz=dingggg"),
+ vars: map[string]string{},
+ host: "",
+ path: "",
+ shouldMatch: false,
+ },
+ {
+ title: "Queries route with pattern, match, escaped value",
+ route: new(Route).Queries("foo", "{v1}"),
+ request: newRequest("GET", "http://localhost?foo=%25bar%26%20%2F%3D%3F"),
+ vars: map[string]string{"v1": "%bar& /=?"},
+ host: "",
+ path: "",
+ query: "foo=%25bar%26+%2F%3D%3F",
+ shouldMatch: true,
+ },
}
for _, test := range tests {
testRoute(t, test)
+ testTemplate(t, test)
+ testUseEscapedRoute(t, test)
}
}
@@ -554,35 +997,49 @@ func TestSchemes(t *testing.T) {
tests := []routeTest{
// Schemes
{
- title: "Schemes route, match https",
- route: new(Route).Schemes("https", "ftp"),
- request: newRequest("GET", "https://localhost"),
- vars: map[string]string{},
- host: "",
- path: "",
+ title: "Schemes route, default scheme, match http, build http",
+ route: new(Route).Host("localhost"),
+ request: newRequest("GET", "http://localhost"),
+ scheme: "http",
+ host: "localhost",
shouldMatch: true,
},
{
- title: "Schemes route, match ftp",
- route: new(Route).Schemes("https", "ftp"),
+ title: "Schemes route, match https, build https",
+ route: new(Route).Schemes("https", "ftp").Host("localhost"),
+ request: newRequest("GET", "https://localhost"),
+ scheme: "https",
+ host: "localhost",
+ shouldMatch: true,
+ },
+ {
+ title: "Schemes route, match ftp, build https",
+ route: new(Route).Schemes("https", "ftp").Host("localhost"),
request: newRequest("GET", "ftp://localhost"),
- vars: map[string]string{},
- host: "",
- path: "",
+ scheme: "https",
+ host: "localhost",
+ shouldMatch: true,
+ },
+ {
+ title: "Schemes route, match ftp, build ftp",
+ route: new(Route).Schemes("ftp", "https").Host("localhost"),
+ request: newRequest("GET", "ftp://localhost"),
+ scheme: "ftp",
+ host: "localhost",
shouldMatch: true,
},
{
title: "Schemes route, bad scheme",
- route: new(Route).Schemes("https", "ftp"),
+ route: new(Route).Schemes("https", "ftp").Host("localhost"),
request: newRequest("GET", "http://localhost"),
- vars: map[string]string{},
- host: "",
- path: "",
+ scheme: "https",
+ host: "localhost",
shouldMatch: false,
},
}
for _, test := range tests {
testRoute(t, test)
+ testTemplate(t, test)
}
}
@@ -617,6 +1074,7 @@ func TestMatcherFunc(t *testing.T) {
for _, test := range tests {
testRoute(t, test)
+ testTemplate(t, test)
}
}
@@ -629,9 +1087,10 @@ func TestBuildVarsFunc(t *testing.T) {
vars["v2"] = "a"
return vars
}),
- request: newRequest("GET", "http://localhost/111/2"),
- path: "/111/3a",
- shouldMatch: true,
+ request: newRequest("GET", "http://localhost/111/2"),
+ path: "/111/3a",
+ pathTemplate: `/111/{v1:\d}{v2:.*}`,
+ shouldMatch: true,
},
{
title: "BuildVarsFunc set on route and parent route",
@@ -642,58 +1101,148 @@ func TestBuildVarsFunc(t *testing.T) {
vars["v2"] = "b"
return vars
}),
- request: newRequest("GET", "http://localhost/1/a"),
- path: "/2/b",
- shouldMatch: true,
+ request: newRequest("GET", "http://localhost/1/a"),
+ path: "/2/b",
+ pathTemplate: `/{v1:\d}/{v2:\w}`,
+ shouldMatch: true,
},
}
for _, test := range tests {
testRoute(t, test)
+ testTemplate(t, test)
}
}
func TestSubRouter(t *testing.T) {
subrouter1 := new(Route).Host("{v1:[a-z]+}.google.com").Subrouter()
subrouter2 := new(Route).PathPrefix("/foo/{v1}").Subrouter()
+ subrouter3 := new(Route).PathPrefix("/foo").Subrouter()
+ subrouter4 := new(Route).PathPrefix("/foo/bar").Subrouter()
+ subrouter5 := new(Route).PathPrefix("/{category}").Subrouter()
tests := []routeTest{
{
- route: subrouter1.Path("/{v2:[a-z]+}"),
- request: newRequest("GET", "http://aaa.google.com/bbb"),
- vars: map[string]string{"v1": "aaa", "v2": "bbb"},
- host: "aaa.google.com",
- path: "/bbb",
- shouldMatch: true,
+ route: subrouter1.Path("/{v2:[a-z]+}"),
+ request: newRequest("GET", "http://aaa.google.com/bbb"),
+ vars: map[string]string{"v1": "aaa", "v2": "bbb"},
+ host: "aaa.google.com",
+ path: "/bbb",
+ pathTemplate: `/{v2:[a-z]+}`,
+ hostTemplate: `{v1:[a-z]+}.google.com`,
+ shouldMatch: true,
},
{
- route: subrouter1.Path("/{v2:[a-z]+}"),
- request: newRequest("GET", "http://111.google.com/111"),
- vars: map[string]string{"v1": "aaa", "v2": "bbb"},
- host: "aaa.google.com",
- path: "/bbb",
- shouldMatch: false,
+ route: subrouter1.Path("/{v2:[a-z]+}"),
+ request: newRequest("GET", "http://111.google.com/111"),
+ vars: map[string]string{"v1": "aaa", "v2": "bbb"},
+ host: "aaa.google.com",
+ path: "/bbb",
+ pathTemplate: `/{v2:[a-z]+}`,
+ hostTemplate: `{v1:[a-z]+}.google.com`,
+ shouldMatch: false,
},
{
- route: subrouter2.Path("/baz/{v2}"),
- request: newRequest("GET", "http://localhost/foo/bar/baz/ding"),
- vars: map[string]string{"v1": "bar", "v2": "ding"},
- host: "",
- path: "/foo/bar/baz/ding",
- shouldMatch: true,
+ route: subrouter2.Path("/baz/{v2}"),
+ request: newRequest("GET", "http://localhost/foo/bar/baz/ding"),
+ vars: map[string]string{"v1": "bar", "v2": "ding"},
+ host: "",
+ path: "/foo/bar/baz/ding",
+ pathTemplate: `/foo/{v1}/baz/{v2}`,
+ shouldMatch: true,
},
{
- route: subrouter2.Path("/baz/{v2}"),
- request: newRequest("GET", "http://localhost/foo/bar"),
- vars: map[string]string{"v1": "bar", "v2": "ding"},
- host: "",
- path: "/foo/bar/baz/ding",
- shouldMatch: false,
+ route: subrouter2.Path("/baz/{v2}"),
+ request: newRequest("GET", "http://localhost/foo/bar"),
+ vars: map[string]string{"v1": "bar", "v2": "ding"},
+ host: "",
+ path: "/foo/bar/baz/ding",
+ pathTemplate: `/foo/{v1}/baz/{v2}`,
+ shouldMatch: false,
+ },
+ {
+ route: subrouter3.Path("/"),
+ request: newRequest("GET", "http://localhost/foo/"),
+ vars: map[string]string{},
+ host: "",
+ path: "/foo/",
+ pathTemplate: `/foo/`,
+ shouldMatch: true,
+ },
+ {
+ route: subrouter3.Path(""),
+ request: newRequest("GET", "http://localhost/foo"),
+ vars: map[string]string{},
+ host: "",
+ path: "/foo",
+ pathTemplate: `/foo`,
+ shouldMatch: true,
+ },
+
+ {
+ route: subrouter4.Path("/"),
+ request: newRequest("GET", "http://localhost/foo/bar/"),
+ vars: map[string]string{},
+ host: "",
+ path: "/foo/bar/",
+ pathTemplate: `/foo/bar/`,
+ shouldMatch: true,
+ },
+ {
+ route: subrouter4.Path(""),
+ request: newRequest("GET", "http://localhost/foo/bar"),
+ vars: map[string]string{},
+ host: "",
+ path: "/foo/bar",
+ pathTemplate: `/foo/bar`,
+ shouldMatch: true,
+ },
+ {
+ route: subrouter5.Path("/"),
+ request: newRequest("GET", "http://localhost/baz/"),
+ vars: map[string]string{"category": "baz"},
+ host: "",
+ path: "/baz/",
+ pathTemplate: `/{category}/`,
+ shouldMatch: true,
+ },
+ {
+ route: subrouter5.Path(""),
+ request: newRequest("GET", "http://localhost/baz"),
+ vars: map[string]string{"category": "baz"},
+ host: "",
+ path: "/baz",
+ pathTemplate: `/{category}`,
+ shouldMatch: true,
+ },
+ {
+ title: "Build with scheme on parent router",
+ route: new(Route).Schemes("ftp").Host("google.com").Subrouter().Path("/"),
+ request: newRequest("GET", "ftp://google.com/"),
+ scheme: "ftp",
+ host: "google.com",
+ path: "/",
+ pathTemplate: `/`,
+ hostTemplate: `google.com`,
+ shouldMatch: true,
+ },
+ {
+ title: "Prefer scheme on child route when building URLs",
+ route: new(Route).Schemes("https", "ftp").Host("google.com").Subrouter().Schemes("ftp").Path("/"),
+ request: newRequest("GET", "ftp://google.com/"),
+ scheme: "ftp",
+ host: "google.com",
+ path: "/",
+ pathTemplate: `/`,
+ hostTemplate: `google.com`,
+ shouldMatch: true,
},
}
for _, test := range tests {
testRoute(t, test)
+ testTemplate(t, test)
+ testUseEscapedRoute(t, test)
}
}
@@ -789,22 +1338,245 @@ func TestStrictSlash(t *testing.T) {
for _, test := range tests {
testRoute(t, test)
+ testTemplate(t, test)
+ testUseEscapedRoute(t, test)
}
}
+func TestUseEncodedPath(t *testing.T) {
+ r := NewRouter()
+ r.UseEncodedPath()
+
+ tests := []routeTest{
+ {
+ title: "Router with useEncodedPath, URL with encoded slash does match",
+ route: r.NewRoute().Path("/v1/{v1}/v2"),
+ request: newRequest("GET", "http://localhost/v1/1%2F2/v2"),
+ vars: map[string]string{"v1": "1%2F2"},
+ host: "",
+ path: "/v1/1%2F2/v2",
+ pathTemplate: `/v1/{v1}/v2`,
+ shouldMatch: true,
+ },
+ {
+ title: "Router with useEncodedPath, URL with encoded slash doesn't match",
+ route: r.NewRoute().Path("/v1/1/2/v2"),
+ request: newRequest("GET", "http://localhost/v1/1%2F2/v2"),
+ vars: map[string]string{"v1": "1%2F2"},
+ host: "",
+ path: "/v1/1%2F2/v2",
+ pathTemplate: `/v1/1/2/v2`,
+ shouldMatch: false,
+ },
+ }
+
+ for _, test := range tests {
+ testRoute(t, test)
+ testTemplate(t, test)
+ }
+}
+
+func TestWalkSingleDepth(t *testing.T) {
+ r0 := NewRouter()
+ r1 := NewRouter()
+ r2 := NewRouter()
+
+ r0.Path("/g")
+ r0.Path("/o")
+ r0.Path("/d").Handler(r1)
+ r0.Path("/r").Handler(r2)
+ r0.Path("/a")
+
+ r1.Path("/z")
+ r1.Path("/i")
+ r1.Path("/l")
+ r1.Path("/l")
+
+ r2.Path("/i")
+ r2.Path("/l")
+ r2.Path("/l")
+
+ paths := []string{"g", "o", "r", "i", "l", "l", "a"}
+ depths := []int{0, 0, 0, 1, 1, 1, 0}
+ i := 0
+ err := r0.Walk(func(route *Route, router *Router, ancestors []*Route) error {
+ matcher := route.matchers[0].(*routeRegexp)
+ if matcher.template == "/d" {
+ return SkipRouter
+ }
+ if len(ancestors) != depths[i] {
+ t.Errorf(`Expected depth of %d at i = %d; got "%d"`, depths[i], i, len(ancestors))
+ }
+ if matcher.template != "/"+paths[i] {
+ t.Errorf(`Expected "/%s" at i = %d; got "%s"`, paths[i], i, matcher.template)
+ }
+ i++
+ return nil
+ })
+ if err != nil {
+ panic(err)
+ }
+ if i != len(paths) {
+ t.Errorf("Expected %d routes, found %d", len(paths), i)
+ }
+}
+
+func TestWalkNested(t *testing.T) {
+ router := NewRouter()
+
+ g := router.Path("/g").Subrouter()
+ o := g.PathPrefix("/o").Subrouter()
+ r := o.PathPrefix("/r").Subrouter()
+ i := r.PathPrefix("/i").Subrouter()
+ l1 := i.PathPrefix("/l").Subrouter()
+ l2 := l1.PathPrefix("/l").Subrouter()
+ l2.Path("/a")
+
+ testCases := []struct {
+ path string
+ ancestors []*Route
+ }{
+ {"/g", []*Route{}},
+ {"/g/o", []*Route{g.parent.(*Route)}},
+ {"/g/o/r", []*Route{g.parent.(*Route), o.parent.(*Route)}},
+ {"/g/o/r/i", []*Route{g.parent.(*Route), o.parent.(*Route), r.parent.(*Route)}},
+ {"/g/o/r/i/l", []*Route{g.parent.(*Route), o.parent.(*Route), r.parent.(*Route), i.parent.(*Route)}},
+ {"/g/o/r/i/l/l", []*Route{g.parent.(*Route), o.parent.(*Route), r.parent.(*Route), i.parent.(*Route), l1.parent.(*Route)}},
+ {"/g/o/r/i/l/l/a", []*Route{g.parent.(*Route), o.parent.(*Route), r.parent.(*Route), i.parent.(*Route), l1.parent.(*Route), l2.parent.(*Route)}},
+ }
+
+ idx := 0
+ err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error {
+ path := testCases[idx].path
+ tpl := route.regexp.path.template
+ if tpl != path {
+ t.Errorf(`Expected %s got %s`, path, tpl)
+ }
+ currWantAncestors := testCases[idx].ancestors
+ if !reflect.DeepEqual(currWantAncestors, ancestors) {
+ t.Errorf(`Expected %+v got %+v`, currWantAncestors, ancestors)
+ }
+ idx++
+ return nil
+ })
+ if err != nil {
+ panic(err)
+ }
+ if idx != len(testCases) {
+ t.Errorf("Expected %d routes, found %d", len(testCases), idx)
+ }
+}
+
+func TestWalkSubrouters(t *testing.T) {
+ router := NewRouter()
+
+ g := router.Path("/g").Subrouter()
+ o := g.PathPrefix("/o").Subrouter()
+ o.Methods("GET")
+ o.Methods("PUT")
+
+ // all 4 routes should be matched, but final 2 routes do not have path templates
+ paths := []string{"/g", "/g/o", "", ""}
+ idx := 0
+ err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error {
+ path := paths[idx]
+ tpl, _ := route.GetPathTemplate()
+ if tpl != path {
+ t.Errorf(`Expected %s got %s`, path, tpl)
+ }
+ idx++
+ return nil
+ })
+ if err != nil {
+ panic(err)
+ }
+ if idx != len(paths) {
+ t.Errorf("Expected %d routes, found %d", len(paths), idx)
+ }
+}
+
+func TestWalkErrorRoute(t *testing.T) {
+ router := NewRouter()
+ router.Path("/g")
+ expectedError := errors.New("error")
+ err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error {
+ return expectedError
+ })
+ if err != expectedError {
+ t.Errorf("Expected %v routes, found %v", expectedError, err)
+ }
+}
+
+func TestWalkErrorMatcher(t *testing.T) {
+ router := NewRouter()
+ expectedError := router.Path("/g").Subrouter().Path("").GetError()
+ err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error {
+ return route.GetError()
+ })
+ if err != expectedError {
+ t.Errorf("Expected %v routes, found %v", expectedError, err)
+ }
+}
+
+func TestWalkErrorHandler(t *testing.T) {
+ handler := NewRouter()
+ expectedError := handler.Path("/path").Subrouter().Path("").GetError()
+ router := NewRouter()
+ router.Path("/g").Handler(handler)
+ err := router.Walk(func(route *Route, router *Router, ancestors []*Route) error {
+ return route.GetError()
+ })
+ if err != expectedError {
+ t.Errorf("Expected %v routes, found %v", expectedError, err)
+ }
+}
+
+func TestSubrouterErrorHandling(t *testing.T) {
+ superRouterCalled := false
+ subRouterCalled := false
+
+ router := NewRouter()
+ router.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ superRouterCalled = true
+ })
+ subRouter := router.PathPrefix("/bign8").Subrouter()
+ subRouter.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ subRouterCalled = true
+ })
+
+ req, _ := http.NewRequest("GET", "http://localhost/bign8/was/here", nil)
+ router.ServeHTTP(NewRecorder(), req)
+
+ if superRouterCalled {
+ t.Error("Super router 404 handler called when sub-router 404 handler is available.")
+ }
+ if !subRouterCalled {
+ t.Error("Sub-router 404 handler was not called.")
+ }
+}
+
+// See: https://github.com/gorilla/mux/issues/200
+func TestPanicOnCapturingGroups(t *testing.T) {
+ defer func() {
+ if recover() == nil {
+ t.Errorf("(Test that capturing groups now fail fast) Expected panic, however test completed successfully.\n")
+ }
+ }()
+ NewRouter().NewRoute().Path("/{type:(promo|special)}/{promoId}.json")
+}
+
// ----------------------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------------------
func getRouteTemplate(route *Route) string {
- host, path := "none", "none"
- if route.regexp != nil {
- if route.regexp.host != nil {
- host = route.regexp.host.template
- }
- if route.regexp.path != nil {
- path = route.regexp.path.template
- }
+ host, err := route.GetHostTemplate()
+ if err != nil {
+ host = "none"
+ }
+ path, err := route.GetPathTemplate()
+ if err != nil {
+ path = "none"
}
return fmt.Sprintf("Host: %v, Path: %v", host, path)
}
@@ -814,10 +1586,16 @@ func testRoute(t *testing.T, test routeTest) {
route := test.route
vars := test.vars
shouldMatch := test.shouldMatch
- host := test.host
- path := test.path
- url := test.host + test.path
+ query := test.query
shouldRedirect := test.shouldRedirect
+ uri := url.URL{
+ Scheme: test.scheme,
+ Host: test.host,
+ Path: test.path,
+ }
+ if uri.Scheme == "" {
+ uri.Scheme = "http"
+ }
var match RouteMatch
ok := route.Match(request, &match)
@@ -830,28 +1608,58 @@ func testRoute(t *testing.T, test routeTest) {
return
}
if shouldMatch {
- if test.vars != nil && !stringMapEqual(test.vars, match.Vars) {
+ if vars != nil && !stringMapEqual(vars, match.Vars) {
t.Errorf("(%v) Vars not equal: expected %v, got %v", test.title, vars, match.Vars)
return
}
- if host != "" {
- u, _ := test.route.URLHost(mapToPairs(match.Vars)...)
- if host != u.Host {
- t.Errorf("(%v) URLHost not equal: expected %v, got %v -- %v", test.title, host, u.Host, getRouteTemplate(route))
+ if test.scheme != "" {
+ u, err := route.URL(mapToPairs(match.Vars)...)
+ if err != nil {
+ t.Fatalf("(%v) URL error: %v -- %v", test.title, err, getRouteTemplate(route))
+ }
+ if uri.Scheme != u.Scheme {
+ t.Errorf("(%v) URLScheme not equal: expected %v, got %v", test.title, uri.Scheme, u.Scheme)
return
}
}
- if path != "" {
- u, _ := route.URLPath(mapToPairs(match.Vars)...)
- if path != u.Path {
- t.Errorf("(%v) URLPath not equal: expected %v, got %v -- %v", test.title, path, u.Path, getRouteTemplate(route))
+ if test.host != "" {
+ u, err := test.route.URLHost(mapToPairs(match.Vars)...)
+ if err != nil {
+ t.Fatalf("(%v) URLHost error: %v -- %v", test.title, err, getRouteTemplate(route))
+ }
+ if uri.Scheme != u.Scheme {
+ t.Errorf("(%v) URLHost scheme not equal: expected %v, got %v -- %v", test.title, uri.Scheme, u.Scheme, getRouteTemplate(route))
+ return
+ }
+ if uri.Host != u.Host {
+ t.Errorf("(%v) URLHost host not equal: expected %v, got %v -- %v", test.title, uri.Host, u.Host, getRouteTemplate(route))
return
}
}
- if url != "" {
+ if test.path != "" {
+ u, err := route.URLPath(mapToPairs(match.Vars)...)
+ if err != nil {
+ t.Fatalf("(%v) URLPath error: %v -- %v", test.title, err, getRouteTemplate(route))
+ }
+ if uri.Path != u.Path {
+ t.Errorf("(%v) URLPath not equal: expected %v, got %v -- %v", test.title, uri.Path, u.Path, getRouteTemplate(route))
+ return
+ }
+ }
+ if test.host != "" && test.path != "" {
+ u, err := route.URL(mapToPairs(match.Vars)...)
+ if err != nil {
+ t.Fatalf("(%v) URL error: %v -- %v", test.title, err, getRouteTemplate(route))
+ }
+ if expected, got := uri.String(), u.String(); expected != got {
+ t.Errorf("(%v) URL not equal: expected %v, got %v -- %v", test.title, expected, got, getRouteTemplate(route))
+ return
+ }
+ }
+ if query != "" {
u, _ := route.URL(mapToPairs(match.Vars)...)
- if url != u.Host+u.Path {
- t.Errorf("(%v) URL not equal: expected %v, got %v -- %v", test.title, url, u.Host+u.Path, getRouteTemplate(route))
+ if query != u.RawQuery {
+ t.Errorf("(%v) URL query not equal: expected %v, got %v", test.title, query, u.RawQuery)
return
}
}
@@ -866,34 +1674,47 @@ func testRoute(t *testing.T, test routeTest) {
}
}
-// Tests that the context is cleared or not cleared properly depending on
-// the configuration of the router
-func TestKeepContext(t *testing.T) {
- func1 := func(w http.ResponseWriter, r *http.Request) {}
+func testUseEscapedRoute(t *testing.T, test routeTest) {
+ test.route.useEncodedPath = true
+ testRoute(t, test)
+}
- r := NewRouter()
- r.HandleFunc("/", func1).Name("func1")
-
- req, _ := http.NewRequest("GET", "http://localhost/", nil)
- context.Set(req, "t", 1)
-
- res := new(http.ResponseWriter)
- r.ServeHTTP(*res, req)
-
- if _, ok := context.GetOk(req, "t"); ok {
- t.Error("Context should have been cleared at end of request")
+func testTemplate(t *testing.T, test routeTest) {
+ route := test.route
+ pathTemplate := test.pathTemplate
+ if len(pathTemplate) == 0 {
+ pathTemplate = test.path
+ }
+ hostTemplate := test.hostTemplate
+ if len(hostTemplate) == 0 {
+ hostTemplate = test.host
}
- r.KeepContext = true
-
- req, _ = http.NewRequest("GET", "http://localhost/", nil)
- context.Set(req, "t", 1)
-
- r.ServeHTTP(*res, req)
- if _, ok := context.GetOk(req, "t"); !ok {
- t.Error("Context should NOT have been cleared at end of request")
+ routePathTemplate, pathErr := route.GetPathTemplate()
+ if pathErr == nil && routePathTemplate != pathTemplate {
+ t.Errorf("(%v) GetPathTemplate not equal: expected %v, got %v", test.title, pathTemplate, routePathTemplate)
}
+ routeHostTemplate, hostErr := route.GetHostTemplate()
+ if hostErr == nil && routeHostTemplate != hostTemplate {
+ t.Errorf("(%v) GetHostTemplate not equal: expected %v, got %v", test.title, hostTemplate, routeHostTemplate)
+ }
+}
+
+func testMethods(t *testing.T, test routeTest) {
+ route := test.route
+ methods, _ := route.GetMethods()
+ if strings.Join(methods, ",") != strings.Join(test.methods, ",") {
+ t.Errorf("(%v) GetMethods not equal: expected %v, got %v", test.title, test.methods, methods)
+ }
+}
+
+func testRegexp(t *testing.T, test routeTest) {
+ route := test.route
+ routePathRegexp, regexpErr := route.GetPathRegexp()
+ if test.pathRegexp != "" && regexpErr == nil && routePathRegexp != test.pathRegexp {
+ t.Errorf("(%v) GetPathRegexp not equal: expected %v, got %v", test.title, test.pathRegexp, routePathRegexp)
+ }
}
type TestA301ResponseWriter struct {
@@ -936,6 +1757,24 @@ func Test301Redirect(t *testing.T) {
}
}
+func TestSkipClean(t *testing.T) {
+ func1 := func(w http.ResponseWriter, r *http.Request) {}
+ func2 := func(w http.ResponseWriter, r *http.Request) {}
+
+ r := NewRouter()
+ r.SkipClean(true)
+ r.HandleFunc("/api/", func2).Name("func2")
+ r.HandleFunc("/", func1).Name("func1")
+
+ req, _ := http.NewRequest("GET", "http://localhost//api/?abc=def", nil)
+ res := NewRecorder()
+ r.ServeHTTP(res, req)
+
+ if len(res.HeaderMap["Location"]) != 0 {
+ t.Errorf("Shouldn't redirect since skip clean is disabled")
+ }
+}
+
// https://plus.google.com/101022900381697718949/posts/eWy6DjFJ6uW
func TestSubrouterHeader(t *testing.T) {
expected := "func1 response"
@@ -993,11 +1832,81 @@ func stringMapEqual(m1, m2 map[string]string) bool {
return true
}
-// newRequest is a helper function to create a new request with a method and url
+// newRequest is a helper function to create a new request with a method and url.
+// The request returned is a 'server' request as opposed to a 'client' one through
+// simulated write onto the wire and read off of the wire.
+// The differences between requests are detailed in the net/http package.
func newRequest(method, url string) *http.Request {
req, err := http.NewRequest(method, url, nil)
if err != nil {
panic(err)
}
+ // extract the escaped original host+path from url
+ // http://localhost/path/here?v=1#frag -> //localhost/path/here
+ opaque := ""
+ if i := len(req.URL.Scheme); i > 0 {
+ opaque = url[i+1:]
+ }
+
+ if i := strings.LastIndex(opaque, "?"); i > -1 {
+ opaque = opaque[:i]
+ }
+ if i := strings.LastIndex(opaque, "#"); i > -1 {
+ opaque = opaque[:i]
+ }
+
+ // Escaped host+path workaround as detailed in https://golang.org/pkg/net/url/#URL
+ // for < 1.5 client side workaround
+ req.URL.Opaque = opaque
+
+ // Simulate writing to wire
+ var buff bytes.Buffer
+ req.Write(&buff)
+ ioreader := bufio.NewReader(&buff)
+
+ // Parse request off of 'wire'
+ req, err = http.ReadRequest(ioreader)
+ if err != nil {
+ panic(err)
+ }
return req
}
+
+func TestNoMatchMethodErrorHandler(t *testing.T) {
+ func1 := func(w http.ResponseWriter, r *http.Request) {}
+
+ r := NewRouter()
+ r.HandleFunc("/", func1).Methods("GET", "POST")
+
+ req, _ := http.NewRequest("PUT", "http://localhost/", nil)
+ match := new(RouteMatch)
+ matched := r.Match(req, match)
+
+ if matched {
+ t.Error("Should not have matched route for methods")
+ }
+
+ if match.MatchErr != ErrMethodMismatch {
+ t.Error("Should get ErrMethodMismatch error")
+ }
+
+ resp := NewRecorder()
+ r.ServeHTTP(resp, req)
+ if resp.Code != 405 {
+ t.Errorf("Expecting code %v", 405)
+ }
+
+ // Add matching route
+ r.HandleFunc("/", func1).Methods("PUT")
+
+ match = new(RouteMatch)
+ matched = r.Match(req, match)
+
+ if !matched {
+ t.Error("Should have matched route for methods")
+ }
+
+ if match.MatchErr != nil {
+ t.Error("Should not have any matching error. Found:", match.MatchErr)
+ }
+}
diff --git a/vendor/github.com/gorilla/mux/old_test.go b/vendor/github.com/gorilla/mux/old_test.go
index 1f7c190..3751e47 100644
--- a/vendor/github.com/gorilla/mux/old_test.go
+++ b/vendor/github.com/gorilla/mux/old_test.go
@@ -36,10 +36,6 @@ func NewRecorder() *ResponseRecorder {
}
}
-// DefaultRemoteAddr is the default remote address to return in RemoteAddr if
-// an explicit DefaultRemoteAddr isn't set on ResponseRecorder.
-const DefaultRemoteAddr = "1.2.3.4"
-
// Header returns the response headers.
func (rw *ResponseRecorder) Header() http.Header {
return rw.HeaderMap
@@ -125,12 +121,7 @@ func TestRouteMatchers(t *testing.T) {
var routeMatch RouteMatch
matched := router.Match(request, &routeMatch)
if matched != shouldMatch {
- // Need better messages. :)
- if matched {
- t.Errorf("Should match.")
- } else {
- t.Errorf("Should not match.")
- }
+ t.Errorf("Expected: %v\nGot: %v\nRequest: %v %v", shouldMatch, matched, request.Method, url)
}
if matched {
@@ -192,7 +183,6 @@ func TestRouteMatchers(t *testing.T) {
match(true)
// 2nd route --------------------------------------------------------------
-
// Everything match.
reset2()
match(true)
@@ -545,7 +535,7 @@ func TestMatchedRouteName(t *testing.T) {
router := NewRouter()
route := router.NewRoute().Path("/products/").Name(routeName)
- url := "http://www.domain.com/products/"
+ url := "http://www.example.com/products/"
request, _ := http.NewRequest("GET", url, nil)
var rv RouteMatch
ok := router.Match(request, &rv)
@@ -563,10 +553,10 @@ func TestMatchedRouteName(t *testing.T) {
func TestSubRouting(t *testing.T) {
// Example from docs.
router := NewRouter()
- subrouter := router.NewRoute().Host("www.domain.com").Subrouter()
+ subrouter := router.NewRoute().Host("www.example.com").Subrouter()
route := subrouter.NewRoute().Path("/products/").Name("products")
- url := "http://www.domain.com/products/"
+ url := "http://www.example.com/products/"
request, _ := http.NewRequest("GET", url, nil)
var rv RouteMatch
ok := router.Match(request, &rv)
@@ -576,10 +566,10 @@ func TestSubRouting(t *testing.T) {
}
u, _ := router.Get("products").URL()
- builtUrl := u.String()
+ builtURL := u.String()
// Yay, subroute aware of the domain when building!
- if builtUrl != url {
- t.Errorf("Expected %q, got %q.", url, builtUrl)
+ if builtURL != url {
+ t.Errorf("Expected %q, got %q.", url, builtURL)
}
}
@@ -691,7 +681,7 @@ func TestNewRegexp(t *testing.T) {
}
for pattern, paths := range tests {
- p, _ = newRouteRegexp(pattern, false, false, false, false)
+ p, _ = newRouteRegexp(pattern, false, false, false, false, false)
for path, result := range paths {
matches = p.regexp.FindStringSubmatch(path)
if result == nil {
diff --git a/vendor/github.com/gorilla/mux/regexp.go b/vendor/github.com/gorilla/mux/regexp.go
index aa30679..80d1f78 100644
--- a/vendor/github.com/gorilla/mux/regexp.go
+++ b/vendor/github.com/gorilla/mux/regexp.go
@@ -10,6 +10,7 @@ import (
"net/http"
"net/url"
"regexp"
+ "strconv"
"strings"
)
@@ -23,7 +24,7 @@ import (
// Previously we accepted only Python-like identifiers for variable
// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that
// name and pattern can't be empty, and names can't contain a colon.
-func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash bool) (*routeRegexp, error) {
+func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash, useEncodedPath bool) (*routeRegexp, error) {
// Check if it is well-formed.
idxs, errBraces := braceIndices(tpl)
if errBraces != nil {
@@ -34,8 +35,7 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash
// Now let's parse it.
defaultPattern := "[^/]+"
if matchQuery {
- defaultPattern = "[^?&]+"
- matchPrefix = true
+ defaultPattern = ".*"
} else if matchHost {
defaultPattern = "[^.]+"
matchPrefix = false
@@ -53,9 +53,7 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash
varsN := make([]string, len(idxs)/2)
varsR := make([]*regexp.Regexp, len(idxs)/2)
pattern := bytes.NewBufferString("")
- if !matchQuery {
- pattern.WriteByte('^')
- }
+ pattern.WriteByte('^')
reverse := bytes.NewBufferString("")
var end int
var err error
@@ -75,9 +73,11 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash
tpl[idxs[i]:end])
}
// Build the regexp pattern.
- fmt.Fprintf(pattern, "%s(%s)", regexp.QuoteMeta(raw), patt)
+ fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(i/2), patt)
+
// Build the reverse template.
fmt.Fprintf(reverse, "%s%%s", raw)
+
// Append variable name and compiled pattern.
varsN[i/2] = name
varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt))
@@ -91,6 +91,12 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash
if strictSlash {
pattern.WriteString("[/]?")
}
+ if matchQuery {
+ // Add the default pattern if the query value is empty
+ if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" {
+ pattern.WriteString(defaultPattern)
+ }
+ }
if !matchPrefix {
pattern.WriteByte('$')
}
@@ -103,16 +109,24 @@ func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash
if errCompile != nil {
return nil, errCompile
}
+
+ // Check for capturing groups which used to work in older versions
+ if reg.NumSubexp() != len(idxs)/2 {
+ panic(fmt.Sprintf("route %s contains capture groups in its regexp. ", template) +
+ "Only non-capturing groups are accepted: e.g. (?:pattern) instead of (pattern)")
+ }
+
// Done!
return &routeRegexp{
- template: template,
- matchHost: matchHost,
- matchQuery: matchQuery,
- strictSlash: strictSlash,
- regexp: reg,
- reverse: reverse.String(),
- varsN: varsN,
- varsR: varsR,
+ template: template,
+ matchHost: matchHost,
+ matchQuery: matchQuery,
+ strictSlash: strictSlash,
+ useEncodedPath: useEncodedPath,
+ regexp: reg,
+ reverse: reverse.String(),
+ varsN: varsN,
+ varsR: varsR,
}, nil
}
@@ -127,6 +141,9 @@ type routeRegexp struct {
matchQuery bool
// The strictSlash value defined on the route, but disabled if PathPrefix was used.
strictSlash bool
+ // Determines whether to use encoded path from getPath function or unencoded
+ // req.URL.Path for path matching
+ useEncodedPath bool
// Expanded regexp.
regexp *regexp.Regexp
// Reverse template.
@@ -141,11 +158,15 @@ type routeRegexp struct {
func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool {
if !r.matchHost {
if r.matchQuery {
- return r.regexp.MatchString(req.URL.RawQuery)
- } else {
- return r.regexp.MatchString(req.URL.Path)
+ return r.matchQueryString(req)
}
+ path := req.URL.Path
+ if r.useEncodedPath {
+ path = getPath(req)
+ }
+ return r.regexp.MatchString(path)
}
+
return r.regexp.MatchString(getHost(req))
}
@@ -157,6 +178,9 @@ func (r *routeRegexp) url(values map[string]string) (string, error) {
if !ok {
return "", fmt.Errorf("mux: missing route variable %q", v)
}
+ if r.matchQuery {
+ value = url.QueryEscape(value)
+ }
urlValues[k] = value
}
rv := fmt.Sprintf(r.reverse, urlValues...)
@@ -175,11 +199,31 @@ func (r *routeRegexp) url(values map[string]string) (string, error) {
return rv, nil
}
+// getURLQuery returns a single query parameter from a request URL.
+// For a URL with foo=bar&baz=ding, we return only the relevant key
+// value pair for the routeRegexp.
+func (r *routeRegexp) getURLQuery(req *http.Request) string {
+ if !r.matchQuery {
+ return ""
+ }
+ templateKey := strings.SplitN(r.template, "=", 2)[0]
+ for key, vals := range req.URL.Query() {
+ if key == templateKey && len(vals) > 0 {
+ return key + "=" + vals[0]
+ }
+ }
+ return ""
+}
+
+func (r *routeRegexp) matchQueryString(req *http.Request) bool {
+ return r.regexp.MatchString(r.getURLQuery(req))
+}
+
// braceIndices returns the first level curly brace indices from a string.
// It returns an error in case of unbalanced braces.
func braceIndices(s string) ([]int, error) {
var level, idx int
- idxs := make([]int, 0)
+ var idxs []int
for i := 0; i < len(s); i++ {
switch s[i] {
case '{':
@@ -200,6 +244,11 @@ func braceIndices(s string) ([]int, error) {
return idxs, nil
}
+// varGroupName builds a capturing group name for the indexed variable.
+func varGroupName(idx int) string {
+ return "v" + strconv.Itoa(idx)
+}
+
// ----------------------------------------------------------------------------
// routeRegexpGroup
// ----------------------------------------------------------------------------
@@ -215,23 +264,24 @@ type routeRegexpGroup struct {
func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) {
// Store host variables.
if v.host != nil {
- hostVars := v.host.regexp.FindStringSubmatch(getHost(req))
- if hostVars != nil {
- for k, v := range v.host.varsN {
- m.Vars[v] = hostVars[k+1]
- }
+ host := getHost(req)
+ matches := v.host.regexp.FindStringSubmatchIndex(host)
+ if len(matches) > 0 {
+ extractVars(host, matches, v.host.varsN, m.Vars)
}
}
+ path := req.URL.Path
+ if r.useEncodedPath {
+ path = getPath(req)
+ }
// Store path variables.
if v.path != nil {
- pathVars := v.path.regexp.FindStringSubmatch(req.URL.Path)
- if pathVars != nil {
- for k, v := range v.path.varsN {
- m.Vars[v] = pathVars[k+1]
- }
+ matches := v.path.regexp.FindStringSubmatchIndex(path)
+ if len(matches) > 0 {
+ extractVars(path, matches, v.path.varsN, m.Vars)
// Check if we should redirect.
if v.path.strictSlash {
- p1 := strings.HasSuffix(req.URL.Path, "/")
+ p1 := strings.HasSuffix(path, "/")
p2 := strings.HasSuffix(v.path.template, "/")
if p1 != p2 {
u, _ := url.Parse(req.URL.String())
@@ -246,13 +296,11 @@ func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route)
}
}
// Store query string variables.
- rawQuery := req.URL.RawQuery
for _, q := range v.queries {
- queryVars := q.regexp.FindStringSubmatch(rawQuery)
- if queryVars != nil {
- for k, v := range q.varsN {
- m.Vars[v] = queryVars[k+1]
- }
+ queryURL := q.getURLQuery(req)
+ matches := q.regexp.FindStringSubmatchIndex(queryURL)
+ if len(matches) > 0 {
+ extractVars(queryURL, matches, q.varsN, m.Vars)
}
}
}
@@ -270,3 +318,9 @@ func getHost(r *http.Request) string {
return host
}
+
+func extractVars(input string, matches []int, names []string, output map[string]string) {
+ for i, name := range names {
+ output[name] = input[matches[2*i+2]:matches[2*i+3]]
+ }
+}
diff --git a/vendor/github.com/gorilla/mux/route.go b/vendor/github.com/gorilla/mux/route.go
index d4f0146..6863adb 100644
--- a/vendor/github.com/gorilla/mux/route.go
+++ b/vendor/github.com/gorilla/mux/route.go
@@ -9,6 +9,7 @@ import (
"fmt"
"net/http"
"net/url"
+ "regexp"
"strings"
)
@@ -25,6 +26,13 @@ type Route struct {
// If true, when the path pattern is "/path/", accessing "/path" will
// redirect to the former and vice versa.
strictSlash bool
+ // If true, when the path pattern is "/path//to", accessing "/path//to"
+ // will not redirect
+ skipClean bool
+ // If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to"
+ useEncodedPath bool
+ // The scheme used when building URLs.
+ buildScheme string
// If true, this route never matches: it is only used to build URLs.
buildOnly bool
// The name used to build URLs.
@@ -35,17 +43,36 @@ type Route struct {
buildVarsFunc BuildVarsFunc
}
+func (r *Route) SkipClean() bool {
+ return r.skipClean
+}
+
// Match matches the route against the request.
func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
if r.buildOnly || r.err != nil {
return false
}
+
+ var matchErr error
+
// Match everything.
for _, m := range r.matchers {
if matched := m.Match(req, match); !matched {
+ if _, ok := m.(methodMatcher); ok {
+ matchErr = ErrMethodMismatch
+ continue
+ }
+ matchErr = nil
return false
}
}
+
+ if matchErr != nil {
+ match.MatchErr = matchErr
+ return false
+ }
+
+ match.MatchErr = nil
// Yay, we have a match. Let's collect some info about it.
if match.Route == nil {
match.Route = r
@@ -56,6 +83,7 @@ func (r *Route) Match(req *http.Request, match *RouteMatch) bool {
if match.Vars == nil {
match.Vars = make(map[string]string)
}
+
// Set variables.
if r.regexp != nil {
r.regexp.setMatch(req, match, r)
@@ -143,14 +171,14 @@ func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery
}
r.regexp = r.getRegexpGroup()
if !matchHost && !matchQuery {
- if len(tpl) == 0 || tpl[0] != '/' {
+ if len(tpl) > 0 && tpl[0] != '/' {
return fmt.Errorf("mux: path must start with a slash, got %q", tpl)
}
if r.regexp.path != nil {
tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl
}
}
- rr, err := newRouteRegexp(tpl, matchHost, matchPrefix, matchQuery, r.strictSlash)
+ rr, err := newRouteRegexp(tpl, matchHost, matchPrefix, matchQuery, r.strictSlash, r.useEncodedPath)
if err != nil {
return err
}
@@ -188,7 +216,7 @@ func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery
type headerMatcher map[string]string
func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool {
- return matchMap(m, r.Header, true)
+ return matchMapWithString(m, r.Header, true)
}
// Headers adds a matcher for request header values.
@@ -199,22 +227,46 @@ func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool {
// "X-Requested-With", "XMLHttpRequest")
//
// The above route will only match if both request header values match.
-//
-// It the value is an empty string, it will match any value if the key is set.
+// If the value is an empty string, it will match any value if the key is set.
func (r *Route) Headers(pairs ...string) *Route {
if r.err == nil {
var headers map[string]string
- headers, r.err = mapFromPairs(pairs...)
+ headers, r.err = mapFromPairsToString(pairs...)
return r.addMatcher(headerMatcher(headers))
}
return r
}
+// headerRegexMatcher matches the request against the route given a regex for the header
+type headerRegexMatcher map[string]*regexp.Regexp
+
+func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool {
+ return matchMapWithRegex(m, r.Header, true)
+}
+
+// HeadersRegexp accepts a sequence of key/value pairs, where the value has regex
+// support. For example:
+//
+// r := mux.NewRouter()
+// r.HeadersRegexp("Content-Type", "application/(text|json)",
+// "X-Requested-With", "XMLHttpRequest")
+//
+// The above route will only match if both the request header matches both regular expressions.
+// It the value is an empty string, it will match any value if the key is set.
+func (r *Route) HeadersRegexp(pairs ...string) *Route {
+ if r.err == nil {
+ var headers map[string]*regexp.Regexp
+ headers, r.err = mapFromPairsToRegex(pairs...)
+ return r.addMatcher(headerRegexMatcher(headers))
+ }
+ return r
+}
+
// Host -----------------------------------------------------------------------
// Host adds a matcher for the URL host.
// It accepts a template with zero or more URL variables enclosed by {}.
-// Variables can define an optional regexp pattern to me matched:
+// Variables can define an optional regexp pattern to be matched:
//
// - {name} matches anything until the next dot.
//
@@ -223,7 +275,7 @@ func (r *Route) Headers(pairs ...string) *Route {
// For example:
//
// r := mux.NewRouter()
-// r.Host("www.domain.com")
+// r.Host("www.example.com")
// r.Host("{subdomain}.domain.com")
// r.Host("{subdomain:[a-z]+}.domain.com")
//
@@ -239,6 +291,7 @@ func (r *Route) Host(tpl string) *Route {
// MatcherFunc is the function signature used by custom matchers.
type MatcherFunc func(*http.Request, *RouteMatch) bool
+// Match returns the match for a given request.
func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool {
return m(r, match)
}
@@ -272,7 +325,7 @@ func (r *Route) Methods(methods ...string) *Route {
// Path adds a matcher for the URL path.
// It accepts a template with zero or more URL variables enclosed by {}. The
// template must start with a "/".
-// Variables can define an optional regexp pattern to me matched:
+// Variables can define an optional regexp pattern to be matched:
//
// - {name} matches anything until the next slash.
//
@@ -323,7 +376,7 @@ func (r *Route) PathPrefix(tpl string) *Route {
//
// It the value is an empty string, it will match any value if the key is set.
//
-// Variables can define an optional regexp pattern to me matched:
+// Variables can define an optional regexp pattern to be matched:
//
// - {name} matches anything until the next slash.
//
@@ -336,7 +389,7 @@ func (r *Route) Queries(pairs ...string) *Route {
return nil
}
for i := 0; i < length; i += 2 {
- if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, true, true); r.err != nil {
+ if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, false, true); r.err != nil {
return r
}
}
@@ -359,6 +412,9 @@ func (r *Route) Schemes(schemes ...string) *Route {
for k, v := range schemes {
schemes[k] = strings.ToLower(v)
}
+ if r.buildScheme == "" && len(schemes) > 0 {
+ r.buildScheme = schemes[0]
+ }
return r.addMatcher(schemeMatcher(schemes))
}
@@ -382,7 +438,7 @@ func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route {
// It will test the inner routes only if the parent route matched. For example:
//
// r := mux.NewRouter()
-// s := r.Host("www.domain.com").Subrouter()
+// s := r.Host("www.example.com").Subrouter()
// s.HandleFunc("/products/", ProductsHandler)
// s.HandleFunc("/products/{key}", ProductHandler)
// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler)
@@ -442,22 +498,33 @@ func (r *Route) URL(pairs ...string) (*url.URL, error) {
return nil, err
}
var scheme, host, path string
+ queries := make([]string, 0, len(r.regexp.queries))
if r.regexp.host != nil {
- // Set a default scheme.
- scheme = "http"
if host, err = r.regexp.host.url(values); err != nil {
return nil, err
}
+ scheme = "http"
+ if s := r.getBuildScheme(); s != "" {
+ scheme = s
+ }
}
if r.regexp.path != nil {
if path, err = r.regexp.path.url(values); err != nil {
return nil, err
}
}
+ for _, q := range r.regexp.queries {
+ var query string
+ if query, err = q.url(values); err != nil {
+ return nil, err
+ }
+ queries = append(queries, query)
+ }
return &url.URL{
- Scheme: scheme,
- Host: host,
- Path: path,
+ Scheme: scheme,
+ Host: host,
+ Path: path,
+ RawQuery: strings.Join(queries, "&"),
}, nil
}
@@ -479,10 +546,14 @@ func (r *Route) URLHost(pairs ...string) (*url.URL, error) {
if err != nil {
return nil, err
}
- return &url.URL{
+ u := &url.URL{
Scheme: "http",
Host: host,
- }, nil
+ }
+ if s := r.getBuildScheme(); s != "" {
+ u.Scheme = s
+ }
+ return u, nil
}
// URLPath builds the path part of the URL for a route. See Route.URL().
@@ -508,10 +579,70 @@ func (r *Route) URLPath(pairs ...string) (*url.URL, error) {
}, nil
}
+// GetPathTemplate returns the template used to build the
+// route match.
+// This is useful for building simple REST API documentation and for instrumentation
+// against third-party services.
+// An error will be returned if the route does not define a path.
+func (r *Route) GetPathTemplate() (string, error) {
+ if r.err != nil {
+ return "", r.err
+ }
+ if r.regexp == nil || r.regexp.path == nil {
+ return "", errors.New("mux: route doesn't have a path")
+ }
+ return r.regexp.path.template, nil
+}
+
+// GetPathRegexp returns the expanded regular expression used to match route path.
+// This is useful for building simple REST API documentation and for instrumentation
+// against third-party services.
+// An error will be returned if the route does not define a path.
+func (r *Route) GetPathRegexp() (string, error) {
+ if r.err != nil {
+ return "", r.err
+ }
+ if r.regexp == nil || r.regexp.path == nil {
+ return "", errors.New("mux: route does not have a path")
+ }
+ return r.regexp.path.regexp.String(), nil
+}
+
+// GetMethods returns the methods the route matches against
+// This is useful for building simple REST API documentation and for instrumentation
+// against third-party services.
+// An empty list will be returned if route does not have methods.
+func (r *Route) GetMethods() ([]string, error) {
+ if r.err != nil {
+ return nil, r.err
+ }
+ for _, m := range r.matchers {
+ if methods, ok := m.(methodMatcher); ok {
+ return []string(methods), nil
+ }
+ }
+ return nil, nil
+}
+
+// GetHostTemplate returns the template used to build the
+// route match.
+// This is useful for building simple REST API documentation and for instrumentation
+// against third-party services.
+// An error will be returned if the route does not define a host.
+func (r *Route) GetHostTemplate() (string, error) {
+ if r.err != nil {
+ return "", r.err
+ }
+ if r.regexp == nil || r.regexp.host == nil {
+ return "", errors.New("mux: route doesn't have a host")
+ }
+ return r.regexp.host.template, nil
+}
+
// prepareVars converts the route variable pairs into a map. If the route has a
// BuildVarsFunc, it is invoked.
func (r *Route) prepareVars(pairs ...string) (map[string]string, error) {
- m, err := mapFromPairs(pairs...)
+ m, err := mapFromPairsToString(pairs...)
if err != nil {
return nil, err
}
@@ -534,11 +665,22 @@ func (r *Route) buildVars(m map[string]string) map[string]string {
// parentRoute allows routes to know about parent host and path definitions.
type parentRoute interface {
+ getBuildScheme() string
getNamedRoutes() map[string]*Route
getRegexpGroup() *routeRegexpGroup
buildVars(map[string]string) map[string]string
}
+func (r *Route) getBuildScheme() string {
+ if r.buildScheme != "" {
+ return r.buildScheme
+ }
+ if r.parent != nil {
+ return r.parent.getBuildScheme()
+ }
+ return ""
+}
+
// getNamedRoutes returns the map where named routes are registered.
func (r *Route) getNamedRoutes() map[string]*Route {
if r.parent == nil {
diff --git a/vendor/github.com/robfig/cron/.travis.yml b/vendor/github.com/matttproud/golang_protobuf_extensions/.travis.yml
similarity index 92%
rename from vendor/github.com/robfig/cron/.travis.yml
rename to vendor/github.com/matttproud/golang_protobuf_extensions/.travis.yml
index 4f2ee4d..f1309c9 100644
--- a/vendor/github.com/robfig/cron/.travis.yml
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/.travis.yml
@@ -1 +1,2 @@
language: go
+
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE b/vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE
new file mode 100644
index 0000000..8dada3e
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright {yyyy} {name of copyright owner}
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE b/vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE
new file mode 100644
index 0000000..5d8cb5b
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE
@@ -0,0 +1 @@
+Copyright 2012 Matt T. Proud (matt.proud@gmail.com)
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/README.md b/vendor/github.com/matttproud/golang_protobuf_extensions/README.md
new file mode 100644
index 0000000..751ee69
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/README.md
@@ -0,0 +1,20 @@
+# Overview
+This repository provides various Protocol Buffer extensions for the Go
+language (golang), namely support for record length-delimited message
+streaming.
+
+| Java | Go |
+| ------------------------------ | --------------------- |
+| MessageLite#parseDelimitedFrom | pbutil.ReadDelimited |
+| MessageLite#writeDelimitedTo | pbutil.WriteDelimited |
+
+Because [Code Review 9102043](https://codereview.appspot.com/9102043/) is
+destined to never be merged into mainline (i.e., never be promoted to formal
+[goprotobuf features](https://github.com/golang/protobuf)), this repository
+will live here in the wild.
+
+# Documentation
+We have [generated Go Doc documentation](http://godoc.org/github.com/matttproud/golang_protobuf_extensions/pbutil) here.
+
+# Testing
+[![Build Status](https://travis-ci.org/matttproud/golang_protobuf_extensions.png?branch=master)](https://travis-ci.org/matttproud/golang_protobuf_extensions)
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/ext/moved.go b/vendor/github.com/matttproud/golang_protobuf_extensions/ext/moved.go
new file mode 100644
index 0000000..f31a0f0
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/ext/moved.go
@@ -0,0 +1,2 @@
+// Package ext moved to a new location: github.com/matttproud/golang_protobuf_extensions/pbutil.
+package ext
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbtest/deleted.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbtest/deleted.go
new file mode 100644
index 0000000..73efcb1
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/pbtest/deleted.go
@@ -0,0 +1,2 @@
+// Package pbtest is deleted for the time being, because upstream Protocol Buffer 3 may have rendered quick.Value-based blackbox generation impossible.
+package pbtest
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go
index 094156e..5c46372 100644
--- a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go
@@ -16,18 +16,14 @@ package pbutil
import (
"bytes"
- "math/rand"
- "reflect"
"testing"
- "testing/quick"
-
- "github.com/matttproud/golang_protobuf_extensions/pbtest"
. "github.com/golang/protobuf/proto"
. "github.com/golang/protobuf/proto/testdata"
)
func TestWriteDelimited(t *testing.T) {
+ t.Parallel()
for _, test := range []struct {
msg Message
buf []byte
@@ -83,6 +79,7 @@ I expect it may. Let's hope you enjoy testing as much as we do.`),
}
func TestReadDelimited(t *testing.T) {
+ t.Parallel()
for _, test := range []struct {
buf []byte
msg Message
@@ -139,6 +136,7 @@ I expect it may. Let's hope you enjoy testing as much as we do.`),
}
func TestEndToEndValid(t *testing.T) {
+ t.Parallel()
for _, test := range [][]Message{
{&Empty{}},
{&GoEnum{Foo: FOO_FOO1.Enum()}, &Empty{}, &GoEnum{Foo: FOO_FOO1.Enum()}},
@@ -177,144 +175,3 @@ I expect it may. Let's hope you enjoy testing as much as we do.`),
}
}
}
-
-// rndMessage generates a random valid Protocol Buffer message.
-func rndMessage(r *rand.Rand) Message {
- var t reflect.Type
- switch v := rand.Intn(23); v {
- // TODO(br): Uncomment the elements below once fix is incorporated, except
- // for the elements marked as patently incompatible.
- // case 0:
- // t = reflect.TypeOf(&GoEnum{})
- // break
- // case 1:
- // t = reflect.TypeOf(&GoTestField{})
- // break
- case 2:
- t = reflect.TypeOf(&GoTest{})
- break
- // case 3:
- // t = reflect.TypeOf(&GoSkipTest{})
- // break
- // case 4:
- // t = reflect.TypeOf(&NonPackedTest{})
- // break
- // case 5:
- // t = reflect.TypeOf(&PackedTest{})
- // break
- case 6:
- t = reflect.TypeOf(&MaxTag{})
- break
- case 7:
- t = reflect.TypeOf(&OldMessage{})
- break
- case 8:
- t = reflect.TypeOf(&NewMessage{})
- break
- case 9:
- t = reflect.TypeOf(&InnerMessage{})
- break
- case 10:
- t = reflect.TypeOf(&OtherMessage{})
- break
- case 11:
- // PATENTLY INVALID FOR FUZZ GENERATION
- // t = reflect.TypeOf(&MyMessage{})
- break
- // case 12:
- // t = reflect.TypeOf(&Ext{})
- // break
- case 13:
- // PATENTLY INVALID FOR FUZZ GENERATION
- // t = reflect.TypeOf(&MyMessageSet{})
- break
- // case 14:
- // t = reflect.TypeOf(&Empty{})
- // break
- // case 15:
- // t = reflect.TypeOf(&MessageList{})
- // break
- // case 16:
- // t = reflect.TypeOf(&Strings{})
- // break
- // case 17:
- // t = reflect.TypeOf(&Defaults{})
- // break
- // case 17:
- // t = reflect.TypeOf(&SubDefaults{})
- // break
- // case 18:
- // t = reflect.TypeOf(&RepeatedEnum{})
- // break
- case 19:
- t = reflect.TypeOf(&MoreRepeated{})
- break
- // case 20:
- // t = reflect.TypeOf(&GroupOld{})
- // break
- // case 21:
- // t = reflect.TypeOf(&GroupNew{})
- // break
- case 22:
- t = reflect.TypeOf(&FloatingPoint{})
- break
- default:
- // TODO(br): Replace with an unreachable once fixed.
- t = reflect.TypeOf(&GoTest{})
- break
- }
- if t == nil {
- t = reflect.TypeOf(&GoTest{})
- }
- v, ok := quick.Value(t, r)
- if !ok {
- panic("attempt to generate illegal item; consult item 11")
- }
- if err := pbtest.SanitizeGenerated(v.Interface().(Message)); err != nil {
- panic(err)
- }
- return v.Interface().(Message)
-}
-
-// rndMessages generates several random Protocol Buffer messages.
-func rndMessages(r *rand.Rand) []Message {
- n := r.Intn(128)
- out := make([]Message, 0, n)
- for i := 0; i < n; i++ {
- out = append(out, rndMessage(r))
- }
- return out
-}
-
-func TestFuzz(t *testing.T) {
- rnd := rand.New(rand.NewSource(42))
- check := func() bool {
- messages := rndMessages(rnd)
- var buf bytes.Buffer
- var written int
- for i, msg := range messages {
- n, err := WriteDelimited(&buf, msg)
- if err != nil {
- t.Fatalf("WriteDelimited(buf, %v[%d]) = ?, %v; wanted ?, nil", messages, i, err)
- }
- written += n
- }
- var read int
- for i, msg := range messages {
- out := Clone(msg)
- out.Reset()
- n, _ := ReadDelimited(&buf, out)
- read += n
- if !Equal(out, msg) {
- t.Fatalf("out = %v; want %v[%d] = %#v", out, messages, i, msg)
- }
- }
- if read != written {
- t.Fatalf("%v read = %d; want %d", messages, read, written)
- }
- return true
- }
- if err := quick.Check(check, nil); err != nil {
- t.Fatal(err)
- }
-}
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go
index 66d9b54..258c063 100644
--- a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go
@@ -38,7 +38,7 @@ var errInvalidVarint = errors.New("invalid varint32 encountered")
func ReadDelimited(r io.Reader, m proto.Message) (n int, err error) {
// Per AbstractParser#parsePartialDelimitedFrom with
// CodedInputStream#readRawVarint32.
- headerBuf := make([]byte, binary.MaxVarintLen32)
+ var headerBuf [binary.MaxVarintLen32]byte
var bytesRead, varIntBytes int
var messageLength uint64
for varIntBytes == 0 { // i.e. no varint has been decoded yet.
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode_test.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode_test.go
new file mode 100644
index 0000000..364a7b7
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode_test.go
@@ -0,0 +1,99 @@
+// Copyright 2016 Matt T. Proud
+//
+// 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 pbutil
+
+import (
+ "bytes"
+ "io"
+ "testing"
+ "testing/iotest"
+)
+
+func TestReadDelimitedIllegalVarint(t *testing.T) {
+ t.Parallel()
+ var tests = []struct {
+ in []byte
+ n int
+ err error
+ }{
+ {
+ in: []byte{255, 255, 255, 255, 255},
+ n: 5,
+ err: errInvalidVarint,
+ },
+ {
+ in: []byte{255, 255, 255, 255, 255, 255},
+ n: 5,
+ err: errInvalidVarint,
+ },
+ }
+ for _, test := range tests {
+ n, err := ReadDelimited(bytes.NewReader(test.in), nil)
+ if got, want := n, test.n; got != want {
+ t.Errorf("ReadDelimited(%#v, nil) = %#v, ?; want = %v#, ?", test.in, got, want)
+ }
+ if got, want := err, test.err; got != want {
+ t.Errorf("ReadDelimited(%#v, nil) = ?, %#v; want = ?, %#v", test.in, got, want)
+ }
+ }
+}
+
+func TestReadDelimitedPrematureHeader(t *testing.T) {
+ t.Parallel()
+ var data = []byte{128, 5} // 256 + 256 + 128
+ n, err := ReadDelimited(bytes.NewReader(data[0:1]), nil)
+ if got, want := n, 1; got != want {
+ t.Errorf("ReadDelimited(%#v, nil) = %#v, ?; want = %v#, ?", data[0:1], got, want)
+ }
+ if got, want := err, io.EOF; got != want {
+ t.Errorf("ReadDelimited(%#v, nil) = ?, %#v; want = ?, %#v", data[0:1], got, want)
+ }
+}
+
+func TestReadDelimitedPrematureBody(t *testing.T) {
+ t.Parallel()
+ var data = []byte{128, 5, 0, 0, 0} // 256 + 256 + 128
+ n, err := ReadDelimited(bytes.NewReader(data[:]), nil)
+ if got, want := n, 5; got != want {
+ t.Errorf("ReadDelimited(%#v, nil) = %#v, ?; want = %v#, ?", data, got, want)
+ }
+ if got, want := err, io.ErrUnexpectedEOF; got != want {
+ t.Errorf("ReadDelimited(%#v, nil) = ?, %#v; want = ?, %#v", data, got, want)
+ }
+}
+
+func TestReadDelimitedPrematureHeaderIncremental(t *testing.T) {
+ t.Parallel()
+ var data = []byte{128, 5} // 256 + 256 + 128
+ n, err := ReadDelimited(iotest.OneByteReader(bytes.NewReader(data[0:1])), nil)
+ if got, want := n, 1; got != want {
+ t.Errorf("ReadDelimited(%#v, nil) = %#v, ?; want = %v#, ?", data[0:1], got, want)
+ }
+ if got, want := err, io.EOF; got != want {
+ t.Errorf("ReadDelimited(%#v, nil) = ?, %#v; want = ?, %#v", data[0:1], got, want)
+ }
+}
+
+func TestReadDelimitedPrematureBodyIncremental(t *testing.T) {
+ t.Parallel()
+ var data = []byte{128, 5, 0, 0, 0} // 256 + 256 + 128
+ n, err := ReadDelimited(iotest.OneByteReader(bytes.NewReader(data[:])), nil)
+ if got, want := n, 5; got != want {
+ t.Errorf("ReadDelimited(%#v, nil) = %#v, ?; want = %v#, ?", data, got, want)
+ }
+ if got, want := err, io.ErrUnexpectedEOF; got != want {
+ t.Errorf("ReadDelimited(%#v, nil) = ?, %#v; want = ?, %#v", data, got, want)
+ }
+}
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go
index 4b76ea9..8fb59ad 100644
--- a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go
@@ -33,8 +33,8 @@ func WriteDelimited(w io.Writer, m proto.Message) (n int, err error) {
return 0, err
}
- buf := make([]byte, binary.MaxVarintLen32)
- encodedLength := binary.PutUvarint(buf, uint64(len(buffer)))
+ var buf [binary.MaxVarintLen32]byte
+ encodedLength := binary.PutUvarint(buf[:], uint64(len(buffer)))
sync, err := w.Write(buf[:encodedLength])
if err != nil {
diff --git a/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode_test.go b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode_test.go
new file mode 100644
index 0000000..f92632b
--- /dev/null
+++ b/vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode_test.go
@@ -0,0 +1,67 @@
+// Copyright 2016 Matt T. Proud
+//
+// 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 pbutil
+
+import (
+ "bytes"
+ "errors"
+ "testing"
+
+ "github.com/golang/protobuf/proto"
+)
+
+var errMarshal = errors.New("pbutil: can't marshal")
+
+type cantMarshal struct{ proto.Message }
+
+func (cantMarshal) Marshal() ([]byte, error) { return nil, errMarshal }
+
+var _ proto.Message = cantMarshal{}
+
+func TestWriteDelimitedMarshalErr(t *testing.T) {
+ t.Parallel()
+ var data cantMarshal
+ var buf bytes.Buffer
+ n, err := WriteDelimited(&buf, data)
+ if got, want := n, 0; got != want {
+ t.Errorf("WriteDelimited(buf, %#v) = %#v, ?; want = %v#, ?", data, got, want)
+ }
+ if got, want := err, errMarshal; got != want {
+ t.Errorf("WriteDelimited(buf, %#v) = ?, %#v; want = ?, %#v", data, got, want)
+ }
+}
+
+type canMarshal struct{ proto.Message }
+
+func (canMarshal) Marshal() ([]byte, error) { return []byte{0, 1, 2, 3, 4, 5}, nil }
+
+var errWrite = errors.New("pbutil: can't write")
+
+type cantWrite struct{}
+
+func (cantWrite) Write([]byte) (int, error) { return 0, errWrite }
+
+func TestWriteDelimitedWriteErr(t *testing.T) {
+ t.Parallel()
+ var data canMarshal
+ var buf cantWrite
+ n, err := WriteDelimited(buf, data)
+ if got, want := n, 0; got != want {
+ t.Errorf("WriteDelimited(buf, %#v) = %#v, ?; want = %v#, ?", data, got, want)
+ }
+ if got, want := err, errWrite; got != want {
+ t.Errorf("WriteDelimited(buf, %#v) = ?, %#v; want = ?, %#v", data, got, want)
+ }
+}
diff --git a/vendor/github.com/prometheus/client_golang/.gitignore b/vendor/github.com/prometheus/client_golang/.gitignore
new file mode 100644
index 0000000..f6fc2e8
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/.gitignore
@@ -0,0 +1,26 @@
+# Compiled Object files, Static and Dynamic libs (Shared Objects)
+*.o
+*.a
+*.so
+
+# Folders
+_obj
+_test
+
+# Architecture specific extensions/prefixes
+*.[568vq]
+[568vq].out
+
+*.cgo1.go
+*.cgo2.c
+_cgo_defun.c
+_cgo_gotypes.go
+_cgo_export.*
+
+_testmain.go
+
+*.exe
+
+*~
+*#
+.build
diff --git a/vendor/github.com/prometheus/client_golang/.travis.yml b/vendor/github.com/prometheus/client_golang/.travis.yml
new file mode 100644
index 0000000..d83f31a
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/.travis.yml
@@ -0,0 +1,9 @@
+sudo: false
+language: go
+
+go:
+ - 1.5.4
+ - 1.6.2
+
+script:
+ - go test -short ./...
diff --git a/vendor/github.com/prometheus/client_golang/AUTHORS.md b/vendor/github.com/prometheus/client_golang/AUTHORS.md
new file mode 100644
index 0000000..c5275d5
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/AUTHORS.md
@@ -0,0 +1,18 @@
+The Prometheus project was started by Matt T. Proud (emeritus) and
+Julius Volz in 2012.
+
+Maintainers of this repository:
+
+* Björn Rabenstein
+
+The following individuals have contributed code to this repository
+(listed in alphabetical order):
+
+* Bernerd Schaefer
+* Björn Rabenstein
+* Daniel Bornkessel
+* Jeff Younker
+* Julius Volz
+* Matt T. Proud
+* Tobias Schmidt
+
diff --git a/vendor/github.com/prometheus/client_golang/CHANGELOG.md b/vendor/github.com/prometheus/client_golang/CHANGELOG.md
new file mode 100644
index 0000000..330788a
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/CHANGELOG.md
@@ -0,0 +1,109 @@
+## 0.8.0 / 2016-08-17
+* [CHANGE] Registry is doing more consistency checks. This might break
+ existing setups that used to export inconsistent metrics.
+* [CHANGE] Pushing to Pushgateway moved to package `push` and changed to allow
+ arbitrary grouping.
+* [CHANGE] Removed `SelfCollector`.
+* [CHANGE] Removed `PanicOnCollectError` and `EnableCollectChecks` methods.
+* [CHANGE] Moved packages to the prometheus/common repo: `text`, `model`,
+ `extraction`.
+* [CHANGE] Deprecated a number of functions.
+* [FEATURE] Allow custom registries. Added `Registerer` and `Gatherer`
+ interfaces.
+* [FEATURE] Separated HTTP exposition, allowing custom HTTP handlers (package
+ `promhttp`) and enabling the creation of other exposition mechanisms.
+* [FEATURE] `MustRegister` is variadic now, allowing registration of many
+ collectors in one call.
+* [FEATURE] Added HTTP API v1 package.
+* [ENHANCEMENT] Numerous documentation improvements.
+* [ENHANCEMENT] Improved metric sorting.
+* [ENHANCEMENT] Inlined fnv64a hashing for improved performance.
+* [ENHANCEMENT] Several test improvements.
+* [BUGFIX] Handle collisions in MetricVec.
+
+## 0.7.0 / 2015-07-27
+* [CHANGE] Rename ExporterLabelPrefix to ExportedLabelPrefix.
+* [BUGFIX] Closed gaps in metric consistency check.
+* [BUGFIX] Validate LabelName/LabelSet on JSON unmarshaling.
+* [ENHANCEMENT] Document the possibility to create "empty" metrics in
+ a metric vector.
+* [ENHANCEMENT] Fix and clarify various doc comments and the README.md.
+* [ENHANCEMENT] (Kind of) solve "The Proxy Problem" of http.InstrumentHandler.
+* [ENHANCEMENT] Change responseWriterDelegator.written to int64.
+
+## 0.6.0 / 2015-06-01
+* [CHANGE] Rename process_goroutines to go_goroutines.
+* [ENHANCEMENT] Validate label names during YAML decoding.
+* [ENHANCEMENT] Add LabelName regular expression.
+* [BUGFIX] Ensure alignment of struct members for 32-bit systems.
+
+## 0.5.0 / 2015-05-06
+* [BUGFIX] Removed a weakness in the fingerprinting aka signature code.
+ This makes fingerprinting slower and more allocation-heavy, but the
+ weakness was too severe to be tolerated.
+* [CHANGE] As a result of the above, Metric.Fingerprint is now returning
+ a different fingerprint. To keep the same fingerprint, the new method
+ Metric.FastFingerprint was introduced, which will be used by the
+ Prometheus server for storage purposes (implying that a collision
+ detection has to be added, too).
+* [ENHANCEMENT] The Metric.Equal and Metric.Before do not depend on
+ fingerprinting anymore, removing the possibility of an undetected
+ fingerprint collision.
+* [FEATURE] The Go collector in the exposition library includes garbage
+ collection stats.
+* [FEATURE] The exposition library allows to create constant "throw-away"
+ summaries and histograms.
+* [CHANGE] A number of new reserved labels and prefixes.
+
+## 0.4.0 / 2015-04-08
+* [CHANGE] Return NaN when Summaries have no observations yet.
+* [BUGFIX] Properly handle Summary decay upon Write().
+* [BUGFIX] Fix the documentation link to the consumption library.
+* [FEATURE] Allow the metric family injection hook to merge with existing
+ metric families.
+* [ENHANCEMENT] Removed cgo dependency and conditional compilation of procfs.
+* [MAINTENANCE] Adjusted to changes in matttproud/golang_protobuf_extensions.
+
+## 0.3.2 / 2015-03-11
+* [BUGFIX] Fixed the receiver type of COWMetric.Set(). This method is
+ only used by the Prometheus server internally.
+* [CLEANUP] Added licenses of vendored code left out by godep.
+
+## 0.3.1 / 2015-03-04
+* [ENHANCEMENT] Switched fingerprinting functions from own free list to
+ sync.Pool.
+* [CHANGE] Makefile uses Go 1.4.2 now (only relevant for examples and tests).
+
+## 0.3.0 / 2015-03-03
+* [CHANGE] Changed the fingerprinting for metrics. THIS WILL INVALIDATE ALL
+ PERSISTED FINGERPRINTS. IF YOU COMPILE THE PROMETHEUS SERVER WITH THIS
+ VERSION, YOU HAVE TO WIPE THE PREVIOUSLY CREATED STORAGE.
+* [CHANGE] LabelValuesToSignature removed. (Nobody had used it, and it was
+ arguably broken.)
+* [CHANGE] Vendored dependencies. Those are only used by the Makefile. If
+ client_golang is used as a library, the vendoring will stay out of your way.
+* [BUGFIX] Remove a weakness in the fingerprinting for metrics. (This made
+ the fingerprinting change above necessary.)
+* [FEATURE] Added new fingerprinting functions SignatureForLabels and
+ SignatureWithoutLabels to be used by the Prometheus server. These functions
+ require fewer allocations than the ones currently used by the server.
+
+## 0.2.0 / 2015-02-23
+* [FEATURE] Introduce new Histagram metric type.
+* [CHANGE] Ignore process collector errors for now (better error handling
+ pending).
+* [CHANGE] Use clear error interface for process pidFn.
+* [BUGFIX] Fix Go download links for several archs and OSes.
+* [ENHANCEMENT] Massively improve Gauge and Counter performance.
+* [ENHANCEMENT] Catch illegal label names for summaries in histograms.
+* [ENHANCEMENT] Reduce allocations during fingerprinting.
+* [ENHANCEMENT] Remove cgo dependency. procfs package will only be included if
+ both cgo is available and the build is for an OS with procfs.
+* [CLEANUP] Clean up code style issues.
+* [CLEANUP] Mark slow test as such and exclude them from travis.
+* [CLEANUP] Update protobuf library package name.
+* [CLEANUP] Updated vendoring of beorn7/perks.
+
+## 0.1.0 / 2015-02-02
+* [CLEANUP] Introduced semantic versioning and changelog. From now on,
+ changes will be reported in this file.
diff --git a/vendor/github.com/prometheus/client_golang/CONTRIBUTING.md b/vendor/github.com/prometheus/client_golang/CONTRIBUTING.md
new file mode 100644
index 0000000..5705f0f
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/CONTRIBUTING.md
@@ -0,0 +1,18 @@
+# Contributing
+
+Prometheus uses GitHub to manage reviews of pull requests.
+
+* If you have a trivial fix or improvement, go ahead and create a pull
+ request, addressing (with `@...`) one or more of the maintainers
+ (see [AUTHORS.md](AUTHORS.md)) in the description of the pull request.
+
+* If you plan to do something more involved, first discuss your ideas
+ on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers).
+ This will avoid unnecessary work and surely give you and us a good deal
+ of inspiration.
+
+* Relevant coding style guidelines are the [Go Code Review
+ Comments](https://code.google.com/p/go-wiki/wiki/CodeReviewComments)
+ and the _Formatting and style_ section of Peter Bourgon's [Go: Best
+ Practices for Production
+ Environments](http://peter.bourgon.org/go-in-production/#formatting-and-style).
diff --git a/vendor/github.com/prometheus/client_golang/LICENSE b/vendor/github.com/prometheus/client_golang/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/prometheus/client_golang/NOTICE b/vendor/github.com/prometheus/client_golang/NOTICE
new file mode 100644
index 0000000..dd878a3
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/NOTICE
@@ -0,0 +1,23 @@
+Prometheus instrumentation library for Go applications
+Copyright 2012-2015 The Prometheus Authors
+
+This product includes software developed at
+SoundCloud Ltd. (http://soundcloud.com/).
+
+
+The following components are included in this product:
+
+perks - a fork of https://github.com/bmizerany/perks
+https://github.com/beorn7/perks
+Copyright 2013-2015 Blake Mizerany, Björn Rabenstein
+See https://github.com/beorn7/perks/blob/master/README.md for license details.
+
+Go support for Protocol Buffers - Google's data interchange format
+http://github.com/golang/protobuf/
+Copyright 2010 The Go Authors
+See source code for license details.
+
+Support for streaming Protocol Buffer messages for the Go language (golang).
+https://github.com/matttproud/golang_protobuf_extensions
+Copyright 2013 Matt T. Proud
+Licensed under the Apache License, Version 2.0
diff --git a/vendor/github.com/prometheus/client_golang/README.md b/vendor/github.com/prometheus/client_golang/README.md
new file mode 100644
index 0000000..557eacf
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/README.md
@@ -0,0 +1,45 @@
+# Prometheus Go client library
+
+[![Build Status](https://travis-ci.org/prometheus/client_golang.svg?branch=master)](https://travis-ci.org/prometheus/client_golang)
+
+This is the [Go](http://golang.org) client library for
+[Prometheus](http://prometheus.io). It has two separate parts, one for
+instrumenting application code, and one for creating clients that talk to the
+Prometheus HTTP API.
+
+## Instrumenting applications
+
+[![code-coverage](http://gocover.io/_badge/github.com/prometheus/client_golang/prometheus)](http://gocover.io/github.com/prometheus/client_golang/prometheus) [![go-doc](https://godoc.org/github.com/prometheus/client_golang/prometheus?status.svg)](https://godoc.org/github.com/prometheus/client_golang/prometheus)
+
+The
+[`prometheus` directory](https://github.com/prometheus/client_golang/tree/master/prometheus)
+contains the instrumentation library. See the
+[best practices section](http://prometheus.io/docs/practices/naming/) of the
+Prometheus documentation to learn more about instrumenting applications.
+
+The
+[`examples` directory](https://github.com/prometheus/client_golang/tree/master/examples)
+contains simple examples of instrumented code.
+
+## Client for the Prometheus HTTP API
+
+[![code-coverage](http://gocover.io/_badge/github.com/prometheus/client_golang/api/prometheus)](http://gocover.io/github.com/prometheus/client_golang/api/prometheus) [![go-doc](https://godoc.org/github.com/prometheus/client_golang/api/prometheus?status.svg)](https://godoc.org/github.com/prometheus/client_golang/api/prometheus)
+
+The
+[`api/prometheus` directory](https://github.com/prometheus/client_golang/tree/master/api/prometheus)
+contains the client for the
+[Prometheus HTTP API](http://prometheus.io/docs/querying/api/). It allows you
+to write Go applications that query time series data from a Prometheus server.
+
+## Where is `model`, `extraction`, and `text`?
+
+The `model` packages has been moved to
+[`prometheus/common/model`](https://github.com/prometheus/common/tree/master/model).
+
+The `extraction` and `text` packages are now contained in
+[`prometheus/common/expfmt`](https://github.com/prometheus/common/tree/master/expfmt).
+
+## Contributing and community
+
+See the [contributing guidelines](CONTRIBUTING.md) and the
+[Community section](http://prometheus.io/community/) of the homepage.
diff --git a/vendor/github.com/prometheus/client_golang/VERSION b/vendor/github.com/prometheus/client_golang/VERSION
new file mode 100644
index 0000000..a3df0a6
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/VERSION
@@ -0,0 +1 @@
+0.8.0
diff --git a/vendor/github.com/prometheus/client_golang/api/prometheus/api.go b/vendor/github.com/prometheus/client_golang/api/prometheus/api.go
new file mode 100644
index 0000000..3028d74
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/api/prometheus/api.go
@@ -0,0 +1,345 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package prometheus provides bindings to the Prometheus HTTP API:
+// http://prometheus.io/docs/querying/api/
+package prometheus
+
+import (
+ "encoding/json"
+ "fmt"
+ "io/ioutil"
+ "net"
+ "net/http"
+ "net/url"
+ "path"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/prometheus/common/model"
+ "golang.org/x/net/context"
+ "golang.org/x/net/context/ctxhttp"
+)
+
+const (
+ statusAPIError = 422
+ apiPrefix = "/api/v1"
+
+ epQuery = "/query"
+ epQueryRange = "/query_range"
+ epLabelValues = "/label/:name/values"
+ epSeries = "/series"
+)
+
+type ErrorType string
+
+const (
+ // The different API error types.
+ ErrBadData ErrorType = "bad_data"
+ ErrTimeout = "timeout"
+ ErrCanceled = "canceled"
+ ErrExec = "execution"
+ ErrBadResponse = "bad_response"
+)
+
+// Error is an error returned by the API.
+type Error struct {
+ Type ErrorType
+ Msg string
+}
+
+func (e *Error) Error() string {
+ return fmt.Sprintf("%s: %s", e.Type, e.Msg)
+}
+
+// CancelableTransport is like net.Transport but provides
+// per-request cancelation functionality.
+type CancelableTransport interface {
+ http.RoundTripper
+ CancelRequest(req *http.Request)
+}
+
+var DefaultTransport CancelableTransport = &http.Transport{
+ Proxy: http.ProxyFromEnvironment,
+ Dial: (&net.Dialer{
+ Timeout: 30 * time.Second,
+ KeepAlive: 30 * time.Second,
+ }).Dial,
+ TLSHandshakeTimeout: 10 * time.Second,
+}
+
+// Config defines configuration parameters for a new client.
+type Config struct {
+ // The address of the Prometheus to connect to.
+ Address string
+
+ // Transport is used by the Client to drive HTTP requests. If not
+ // provided, DefaultTransport will be used.
+ Transport CancelableTransport
+}
+
+func (cfg *Config) transport() CancelableTransport {
+ if cfg.Transport == nil {
+ return DefaultTransport
+ }
+ return cfg.Transport
+}
+
+type Client interface {
+ url(ep string, args map[string]string) *url.URL
+ do(context.Context, *http.Request) (*http.Response, []byte, error)
+}
+
+// New returns a new Client.
+//
+// It is safe to use the returned Client from multiple goroutines.
+func New(cfg Config) (Client, error) {
+ u, err := url.Parse(cfg.Address)
+ if err != nil {
+ return nil, err
+ }
+ u.Path = strings.TrimRight(u.Path, "/") + apiPrefix
+
+ return &httpClient{
+ endpoint: u,
+ transport: cfg.transport(),
+ }, nil
+}
+
+type httpClient struct {
+ endpoint *url.URL
+ transport CancelableTransport
+}
+
+func (c *httpClient) url(ep string, args map[string]string) *url.URL {
+ p := path.Join(c.endpoint.Path, ep)
+
+ for arg, val := range args {
+ arg = ":" + arg
+ p = strings.Replace(p, arg, val, -1)
+ }
+
+ u := *c.endpoint
+ u.Path = p
+
+ return &u
+}
+
+func (c *httpClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
+ resp, err := ctxhttp.Do(ctx, &http.Client{Transport: c.transport}, req)
+
+ defer func() {
+ if resp != nil {
+ resp.Body.Close()
+ }
+ }()
+
+ if err != nil {
+ return nil, nil, err
+ }
+
+ var body []byte
+ done := make(chan struct{})
+ go func() {
+ body, err = ioutil.ReadAll(resp.Body)
+ close(done)
+ }()
+
+ select {
+ case <-ctx.Done():
+ err = resp.Body.Close()
+ <-done
+ if err == nil {
+ err = ctx.Err()
+ }
+ case <-done:
+ }
+
+ return resp, body, err
+}
+
+// apiClient wraps a regular client and processes successful API responses.
+// Successful also includes responses that errored at the API level.
+type apiClient struct {
+ Client
+}
+
+type apiResponse struct {
+ Status string `json:"status"`
+ Data json.RawMessage `json:"data"`
+ ErrorType ErrorType `json:"errorType"`
+ Error string `json:"error"`
+}
+
+func (c apiClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
+ resp, body, err := c.Client.do(ctx, req)
+ if err != nil {
+ return resp, body, err
+ }
+
+ code := resp.StatusCode
+
+ if code/100 != 2 && code != statusAPIError {
+ return resp, body, &Error{
+ Type: ErrBadResponse,
+ Msg: fmt.Sprintf("bad response code %d", resp.StatusCode),
+ }
+ }
+
+ var result apiResponse
+
+ if err = json.Unmarshal(body, &result); err != nil {
+ return resp, body, &Error{
+ Type: ErrBadResponse,
+ Msg: err.Error(),
+ }
+ }
+
+ if (code == statusAPIError) != (result.Status == "error") {
+ err = &Error{
+ Type: ErrBadResponse,
+ Msg: "inconsistent body for response code",
+ }
+ }
+
+ if code == statusAPIError && result.Status == "error" {
+ err = &Error{
+ Type: result.ErrorType,
+ Msg: result.Error,
+ }
+ }
+
+ return resp, []byte(result.Data), err
+}
+
+// Range represents a sliced time range.
+type Range struct {
+ // The boundaries of the time range.
+ Start, End time.Time
+ // The maximum time between two slices within the boundaries.
+ Step time.Duration
+}
+
+// queryResult contains result data for a query.
+type queryResult struct {
+ Type model.ValueType `json:"resultType"`
+ Result interface{} `json:"result"`
+
+ // The decoded value.
+ v model.Value
+}
+
+func (qr *queryResult) UnmarshalJSON(b []byte) error {
+ v := struct {
+ Type model.ValueType `json:"resultType"`
+ Result json.RawMessage `json:"result"`
+ }{}
+
+ err := json.Unmarshal(b, &v)
+ if err != nil {
+ return err
+ }
+
+ switch v.Type {
+ case model.ValScalar:
+ var sv model.Scalar
+ err = json.Unmarshal(v.Result, &sv)
+ qr.v = &sv
+
+ case model.ValVector:
+ var vv model.Vector
+ err = json.Unmarshal(v.Result, &vv)
+ qr.v = vv
+
+ case model.ValMatrix:
+ var mv model.Matrix
+ err = json.Unmarshal(v.Result, &mv)
+ qr.v = mv
+
+ default:
+ err = fmt.Errorf("unexpected value type %q", v.Type)
+ }
+ return err
+}
+
+// QueryAPI provides bindings the Prometheus's query API.
+type QueryAPI interface {
+ // Query performs a query for the given time.
+ Query(ctx context.Context, query string, ts time.Time) (model.Value, error)
+ // Query performs a query for the given range.
+ QueryRange(ctx context.Context, query string, r Range) (model.Value, error)
+}
+
+// NewQueryAPI returns a new QueryAPI for the client.
+//
+// It is safe to use the returned QueryAPI from multiple goroutines.
+func NewQueryAPI(c Client) QueryAPI {
+ return &httpQueryAPI{client: apiClient{c}}
+}
+
+type httpQueryAPI struct {
+ client Client
+}
+
+func (h *httpQueryAPI) Query(ctx context.Context, query string, ts time.Time) (model.Value, error) {
+ u := h.client.url(epQuery, nil)
+ q := u.Query()
+
+ q.Set("query", query)
+ q.Set("time", ts.Format(time.RFC3339Nano))
+
+ u.RawQuery = q.Encode()
+
+ req, _ := http.NewRequest("GET", u.String(), nil)
+
+ _, body, err := h.client.do(ctx, req)
+ if err != nil {
+ return nil, err
+ }
+
+ var qres queryResult
+ err = json.Unmarshal(body, &qres)
+
+ return model.Value(qres.v), err
+}
+
+func (h *httpQueryAPI) QueryRange(ctx context.Context, query string, r Range) (model.Value, error) {
+ u := h.client.url(epQueryRange, nil)
+ q := u.Query()
+
+ var (
+ start = r.Start.Format(time.RFC3339Nano)
+ end = r.End.Format(time.RFC3339Nano)
+ step = strconv.FormatFloat(r.Step.Seconds(), 'f', 3, 64)
+ )
+
+ q.Set("query", query)
+ q.Set("start", start)
+ q.Set("end", end)
+ q.Set("step", step)
+
+ u.RawQuery = q.Encode()
+
+ req, _ := http.NewRequest("GET", u.String(), nil)
+
+ _, body, err := h.client.do(ctx, req)
+ if err != nil {
+ return nil, err
+ }
+
+ var qres queryResult
+ err = json.Unmarshal(body, &qres)
+
+ return model.Value(qres.v), err
+}
diff --git a/vendor/github.com/prometheus/client_golang/api/prometheus/api_test.go b/vendor/github.com/prometheus/client_golang/api/prometheus/api_test.go
new file mode 100644
index 0000000..87d3e40
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/api/prometheus/api_test.go
@@ -0,0 +1,453 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/url"
+ "reflect"
+ "testing"
+ "time"
+
+ "github.com/prometheus/common/model"
+ "golang.org/x/net/context"
+)
+
+func TestConfig(t *testing.T) {
+ c := Config{}
+ if c.transport() != DefaultTransport {
+ t.Fatalf("expected default transport for nil Transport field")
+ }
+}
+
+func TestClientURL(t *testing.T) {
+ tests := []struct {
+ address string
+ endpoint string
+ args map[string]string
+ expected string
+ }{
+ {
+ address: "http://localhost:9090",
+ endpoint: "/test",
+ expected: "http://localhost:9090/test",
+ },
+ {
+ address: "http://localhost",
+ endpoint: "/test",
+ expected: "http://localhost/test",
+ },
+ {
+ address: "http://localhost:9090",
+ endpoint: "test",
+ expected: "http://localhost:9090/test",
+ },
+ {
+ address: "http://localhost:9090/prefix",
+ endpoint: "/test",
+ expected: "http://localhost:9090/prefix/test",
+ },
+ {
+ address: "https://localhost:9090/",
+ endpoint: "/test/",
+ expected: "https://localhost:9090/test",
+ },
+ {
+ address: "http://localhost:9090",
+ endpoint: "/test/:param",
+ args: map[string]string{
+ "param": "content",
+ },
+ expected: "http://localhost:9090/test/content",
+ },
+ {
+ address: "http://localhost:9090",
+ endpoint: "/test/:param/more/:param",
+ args: map[string]string{
+ "param": "content",
+ },
+ expected: "http://localhost:9090/test/content/more/content",
+ },
+ {
+ address: "http://localhost:9090",
+ endpoint: "/test/:param/more/:foo",
+ args: map[string]string{
+ "param": "content",
+ "foo": "bar",
+ },
+ expected: "http://localhost:9090/test/content/more/bar",
+ },
+ {
+ address: "http://localhost:9090",
+ endpoint: "/test/:param",
+ args: map[string]string{
+ "nonexistant": "content",
+ },
+ expected: "http://localhost:9090/test/:param",
+ },
+ }
+
+ for _, test := range tests {
+ ep, err := url.Parse(test.address)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ hclient := &httpClient{
+ endpoint: ep,
+ transport: DefaultTransport,
+ }
+
+ u := hclient.url(test.endpoint, test.args)
+ if u.String() != test.expected {
+ t.Errorf("unexpected result: got %s, want %s", u, test.expected)
+ continue
+ }
+
+ // The apiClient must return exactly the same result as the httpClient.
+ aclient := &apiClient{hclient}
+
+ u = aclient.url(test.endpoint, test.args)
+ if u.String() != test.expected {
+ t.Errorf("unexpected result: got %s, want %s", u, test.expected)
+ }
+ }
+}
+
+type testClient struct {
+ *testing.T
+
+ ch chan apiClientTest
+ req *http.Request
+}
+
+type apiClientTest struct {
+ code int
+ response interface{}
+ expected string
+ err *Error
+}
+
+func (c *testClient) url(ep string, args map[string]string) *url.URL {
+ return nil
+}
+
+func (c *testClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
+ if ctx == nil {
+ c.Fatalf("context was not passed down")
+ }
+ if req != c.req {
+ c.Fatalf("request was not passed down")
+ }
+
+ test := <-c.ch
+
+ var b []byte
+ var err error
+
+ switch v := test.response.(type) {
+ case string:
+ b = []byte(v)
+ default:
+ b, err = json.Marshal(v)
+ if err != nil {
+ c.Fatal(err)
+ }
+ }
+
+ resp := &http.Response{
+ StatusCode: test.code,
+ }
+
+ return resp, b, nil
+}
+
+func TestAPIClientDo(t *testing.T) {
+ tests := []apiClientTest{
+ {
+ response: &apiResponse{
+ Status: "error",
+ Data: json.RawMessage(`null`),
+ ErrorType: ErrBadData,
+ Error: "failed",
+ },
+ err: &Error{
+ Type: ErrBadData,
+ Msg: "failed",
+ },
+ code: statusAPIError,
+ expected: `null`,
+ },
+ {
+ response: &apiResponse{
+ Status: "error",
+ Data: json.RawMessage(`"test"`),
+ ErrorType: ErrTimeout,
+ Error: "timed out",
+ },
+ err: &Error{
+ Type: ErrTimeout,
+ Msg: "timed out",
+ },
+ code: statusAPIError,
+ expected: `test`,
+ },
+ {
+ response: "bad json",
+ err: &Error{
+ Type: ErrBadResponse,
+ Msg: "bad response code 400",
+ },
+ code: http.StatusBadRequest,
+ },
+ {
+ response: "bad json",
+ err: &Error{
+ Type: ErrBadResponse,
+ Msg: "invalid character 'b' looking for beginning of value",
+ },
+ code: statusAPIError,
+ },
+ {
+ response: &apiResponse{
+ Status: "success",
+ Data: json.RawMessage(`"test"`),
+ },
+ err: &Error{
+ Type: ErrBadResponse,
+ Msg: "inconsistent body for response code",
+ },
+ code: statusAPIError,
+ },
+ {
+ response: &apiResponse{
+ Status: "success",
+ Data: json.RawMessage(`"test"`),
+ ErrorType: ErrTimeout,
+ Error: "timed out",
+ },
+ err: &Error{
+ Type: ErrBadResponse,
+ Msg: "inconsistent body for response code",
+ },
+ code: statusAPIError,
+ },
+ {
+ response: &apiResponse{
+ Status: "error",
+ Data: json.RawMessage(`"test"`),
+ ErrorType: ErrTimeout,
+ Error: "timed out",
+ },
+ err: &Error{
+ Type: ErrBadResponse,
+ Msg: "inconsistent body for response code",
+ },
+ code: http.StatusOK,
+ },
+ }
+
+ tc := &testClient{
+ T: t,
+ ch: make(chan apiClientTest, 1),
+ req: &http.Request{},
+ }
+ client := &apiClient{tc}
+
+ for _, test := range tests {
+
+ tc.ch <- test
+
+ _, body, err := client.do(context.Background(), tc.req)
+
+ if test.err != nil {
+ if err == nil {
+ t.Errorf("expected error %q but got none", test.err)
+ continue
+ }
+ if test.err.Error() != err.Error() {
+ t.Errorf("unexpected error: want %q, got %q", test.err, err)
+ }
+ continue
+ }
+ if err != nil {
+ t.Errorf("unexpeceted error %s", err)
+ continue
+ }
+
+ want, got := test.expected, string(body)
+ if want != got {
+ t.Errorf("unexpected body: want %q, got %q", want, got)
+ }
+ }
+}
+
+type apiTestClient struct {
+ *testing.T
+ curTest apiTest
+}
+
+type apiTest struct {
+ do func() (interface{}, error)
+ inErr error
+ inRes interface{}
+
+ reqPath string
+ reqParam url.Values
+ reqMethod string
+ res interface{}
+ err error
+}
+
+func (c *apiTestClient) url(ep string, args map[string]string) *url.URL {
+ u := &url.URL{
+ Host: "test:9090",
+ Path: apiPrefix + ep,
+ }
+ return u
+}
+
+func (c *apiTestClient) do(ctx context.Context, req *http.Request) (*http.Response, []byte, error) {
+
+ test := c.curTest
+
+ if req.URL.Path != test.reqPath {
+ c.Errorf("unexpected request path: want %s, got %s", test.reqPath, req.URL.Path)
+ }
+ if req.Method != test.reqMethod {
+ c.Errorf("unexpected request method: want %s, got %s", test.reqMethod, req.Method)
+ }
+
+ b, err := json.Marshal(test.inRes)
+ if err != nil {
+ c.Fatal(err)
+ }
+
+ resp := &http.Response{}
+ if test.inErr != nil {
+ resp.StatusCode = statusAPIError
+ } else {
+ resp.StatusCode = http.StatusOK
+ }
+
+ return resp, b, test.inErr
+}
+
+func TestAPIs(t *testing.T) {
+
+ testTime := time.Now()
+
+ client := &apiTestClient{T: t}
+
+ queryApi := &httpQueryAPI{
+ client: client,
+ }
+
+ doQuery := func(q string, ts time.Time) func() (interface{}, error) {
+ return func() (interface{}, error) {
+ return queryApi.Query(context.Background(), q, ts)
+ }
+ }
+
+ doQueryRange := func(q string, rng Range) func() (interface{}, error) {
+ return func() (interface{}, error) {
+ return queryApi.QueryRange(context.Background(), q, rng)
+ }
+ }
+
+ queryTests := []apiTest{
+ {
+ do: doQuery("2", testTime),
+ inRes: &queryResult{
+ Type: model.ValScalar,
+ Result: &model.Scalar{
+ Value: 2,
+ Timestamp: model.TimeFromUnix(testTime.Unix()),
+ },
+ },
+
+ reqMethod: "GET",
+ reqPath: "/api/v1/query",
+ reqParam: url.Values{
+ "query": []string{"2"},
+ "time": []string{testTime.Format(time.RFC3339Nano)},
+ },
+ res: &model.Scalar{
+ Value: 2,
+ Timestamp: model.TimeFromUnix(testTime.Unix()),
+ },
+ },
+ {
+ do: doQuery("2", testTime),
+ inErr: fmt.Errorf("some error"),
+
+ reqMethod: "GET",
+ reqPath: "/api/v1/query",
+ reqParam: url.Values{
+ "query": []string{"2"},
+ "time": []string{testTime.Format(time.RFC3339Nano)},
+ },
+ err: fmt.Errorf("some error"),
+ },
+
+ {
+ do: doQueryRange("2", Range{
+ Start: testTime.Add(-time.Minute),
+ End: testTime,
+ Step: time.Minute,
+ }),
+ inErr: fmt.Errorf("some error"),
+
+ reqMethod: "GET",
+ reqPath: "/api/v1/query_range",
+ reqParam: url.Values{
+ "query": []string{"2"},
+ "start": []string{testTime.Add(-time.Minute).Format(time.RFC3339Nano)},
+ "end": []string{testTime.Format(time.RFC3339Nano)},
+ "step": []string{time.Minute.String()},
+ },
+ err: fmt.Errorf("some error"),
+ },
+ }
+
+ var tests []apiTest
+ tests = append(tests, queryTests...)
+
+ for _, test := range tests {
+ client.curTest = test
+
+ res, err := test.do()
+
+ if test.err != nil {
+ if err == nil {
+ t.Errorf("expected error %q but got none", test.err)
+ continue
+ }
+ if err.Error() != test.err.Error() {
+ t.Errorf("unexpected error: want %s, got %s", test.err, err)
+ }
+ continue
+ }
+ if err != nil {
+ t.Errorf("unexpected error: %s", err)
+ continue
+ }
+
+ if !reflect.DeepEqual(res, test.res) {
+ t.Errorf("unexpected result: want %v, got %v", test.res, res)
+ }
+ }
+}
diff --git a/vendor/github.com/prometheus/client_golang/examples/random/main.go b/vendor/github.com/prometheus/client_golang/examples/random/main.go
new file mode 100644
index 0000000..5639571
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/examples/random/main.go
@@ -0,0 +1,103 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// A simple example exposing fictional RPC latencies with different types of
+// random distributions (uniform, normal, and exponential) as Prometheus
+// metrics.
+package main
+
+import (
+ "flag"
+ "math"
+ "math/rand"
+ "net/http"
+ "time"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+var (
+ addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.")
+ uniformDomain = flag.Float64("uniform.domain", 200, "The domain for the uniform distribution.")
+ normDomain = flag.Float64("normal.domain", 200, "The domain for the normal distribution.")
+ normMean = flag.Float64("normal.mean", 10, "The mean for the normal distribution.")
+ oscillationPeriod = flag.Duration("oscillation-period", 10*time.Minute, "The duration of the rate oscillation period.")
+)
+
+var (
+ // Create a summary to track fictional interservice RPC latencies for three
+ // distinct services with different latency distributions. These services are
+ // differentiated via a "service" label.
+ rpcDurations = prometheus.NewSummaryVec(
+ prometheus.SummaryOpts{
+ Name: "rpc_durations_microseconds",
+ Help: "RPC latency distributions.",
+ },
+ []string{"service"},
+ )
+ // The same as above, but now as a histogram, and only for the normal
+ // distribution. The buckets are targeted to the parameters of the
+ // normal distribution, with 20 buckets centered on the mean, each
+ // half-sigma wide.
+ rpcDurationsHistogram = prometheus.NewHistogram(prometheus.HistogramOpts{
+ Name: "rpc_durations_histogram_microseconds",
+ Help: "RPC latency distributions.",
+ Buckets: prometheus.LinearBuckets(*normMean-5**normDomain, .5**normDomain, 20),
+ })
+)
+
+func init() {
+ // Register the summary and the histogram with Prometheus's default registry.
+ prometheus.MustRegister(rpcDurations)
+ prometheus.MustRegister(rpcDurationsHistogram)
+}
+
+func main() {
+ flag.Parse()
+
+ start := time.Now()
+
+ oscillationFactor := func() float64 {
+ return 2 + math.Sin(math.Sin(2*math.Pi*float64(time.Since(start))/float64(*oscillationPeriod)))
+ }
+
+ // Periodically record some sample latencies for the three services.
+ go func() {
+ for {
+ v := rand.Float64() * *uniformDomain
+ rpcDurations.WithLabelValues("uniform").Observe(v)
+ time.Sleep(time.Duration(100*oscillationFactor()) * time.Millisecond)
+ }
+ }()
+
+ go func() {
+ for {
+ v := (rand.NormFloat64() * *normDomain) + *normMean
+ rpcDurations.WithLabelValues("normal").Observe(v)
+ rpcDurationsHistogram.Observe(v)
+ time.Sleep(time.Duration(75*oscillationFactor()) * time.Millisecond)
+ }
+ }()
+
+ go func() {
+ for {
+ v := rand.ExpFloat64()
+ rpcDurations.WithLabelValues("exponential").Observe(v)
+ time.Sleep(time.Duration(50*oscillationFactor()) * time.Millisecond)
+ }
+ }()
+
+ // Expose the registered metrics via HTTP.
+ http.Handle("/metrics", prometheus.Handler())
+ http.ListenAndServe(*addr, nil)
+}
diff --git a/vendor/github.com/prometheus/client_golang/model/labelvalue.go b/vendor/github.com/prometheus/client_golang/examples/simple/main.go
similarity index 54%
rename from vendor/github.com/prometheus/client_golang/model/labelvalue.go
rename to vendor/github.com/prometheus/client_golang/examples/simple/main.go
index df2d14c..19620d2 100644
--- a/vendor/github.com/prometheus/client_golang/model/labelvalue.go
+++ b/vendor/github.com/prometheus/client_golang/examples/simple/main.go
@@ -1,4 +1,4 @@
-// Copyright 2013 The Prometheus Authors
+// Copyright 2015 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -11,26 +11,20 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-package model
+// A minimal example of how to include Prometheus instrumentation.
+package main
import (
- "sort"
+ "flag"
+ "net/http"
+
+ "github.com/prometheus/client_golang/prometheus"
)
-// A LabelValue is an associated value for a LabelName.
-type LabelValue string
+var addr = flag.String("listen-address", ":8080", "The address to listen on for HTTP requests.")
-// LabelValues is a sortable LabelValue slice. It implements sort.Interface.
-type LabelValues []LabelValue
-
-func (l LabelValues) Len() int {
- return len(l)
-}
-
-func (l LabelValues) Less(i, j int) bool {
- return sort.StringsAreSorted([]string{string(l[i]), string(l[j])})
-}
-
-func (l LabelValues) Swap(i, j int) {
- l[i], l[j] = l[j], l[i]
+func main() {
+ flag.Parse()
+ http.Handle("/metrics", prometheus.Handler())
+ http.ListenAndServe(*addr, nil)
}
diff --git a/vendor/github.com/prometheus/client_golang/model/labelname_test.go b/vendor/github.com/prometheus/client_golang/model/labelname_test.go
deleted file mode 100644
index 693228d..0000000
--- a/vendor/github.com/prometheus/client_golang/model/labelname_test.go
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2013 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package model
-
-import (
- "sort"
- "testing"
-)
-
-func testLabelNames(t testing.TB) {
- var scenarios = []struct {
- in LabelNames
- out LabelNames
- }{
- {
- in: LabelNames{"ZZZ", "zzz"},
- out: LabelNames{"ZZZ", "zzz"},
- },
- {
- in: LabelNames{"aaa", "AAA"},
- out: LabelNames{"AAA", "aaa"},
- },
- }
-
- for i, scenario := range scenarios {
- sort.Sort(scenario.in)
-
- for j, expected := range scenario.out {
- if expected != scenario.in[j] {
- t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j])
- }
- }
- }
-}
-
-func TestLabelNames(t *testing.T) {
- testLabelNames(t)
-}
-
-func BenchmarkLabelNames(b *testing.B) {
- for i := 0; i < b.N; i++ {
- testLabelNames(b)
- }
-}
diff --git a/vendor/github.com/prometheus/client_golang/model/labelset.go b/vendor/github.com/prometheus/client_golang/model/labelset.go
deleted file mode 100644
index 382ab62..0000000
--- a/vendor/github.com/prometheus/client_golang/model/labelset.go
+++ /dev/null
@@ -1,83 +0,0 @@
-// Copyright 2013 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package model
-
-import (
- "encoding/json"
- "fmt"
- "sort"
- "strings"
-)
-
-// A LabelSet is a collection of LabelName and LabelValue pairs. The LabelSet
-// may be fully-qualified down to the point where it may resolve to a single
-// Metric in the data store or not. All operations that occur within the realm
-// of a LabelSet can emit a vector of Metric entities to which the LabelSet may
-// match.
-type LabelSet map[LabelName]LabelValue
-
-// Merge is a helper function to non-destructively merge two label sets.
-func (l LabelSet) Merge(other LabelSet) LabelSet {
- result := make(LabelSet, len(l))
-
- for k, v := range l {
- result[k] = v
- }
-
- for k, v := range other {
- result[k] = v
- }
-
- return result
-}
-
-func (l LabelSet) String() string {
- labelStrings := make([]string, 0, len(l))
- for label, value := range l {
- labelStrings = append(labelStrings, fmt.Sprintf("%s=%q", label, value))
- }
-
- switch len(labelStrings) {
- case 0:
- return ""
- default:
- sort.Strings(labelStrings)
- return fmt.Sprintf("{%s}", strings.Join(labelStrings, ", "))
- }
-}
-
-// MergeFromMetric merges Metric into this LabelSet.
-func (l LabelSet) MergeFromMetric(m Metric) {
- for k, v := range m {
- l[k] = v
- }
-}
-
-// UnmarshalJSON implements the json.Unmarshaler interface.
-func (l *LabelSet) UnmarshalJSON(b []byte) error {
- var m map[LabelName]LabelValue
- if err := json.Unmarshal(b, &m); err != nil {
- return err
- }
- // encoding/json only unmarshals maps of the form map[string]T. It treats
- // LabelName as a string and does not call its UnmarshalJSON method.
- // Thus, we have to replicate the behavior here.
- for ln := range m {
- if !LabelNameRE.MatchString(string(ln)) {
- return fmt.Errorf("%q is not a valid label name", ln)
- }
- }
- *l = LabelSet(m)
- return nil
-}
diff --git a/vendor/github.com/prometheus/client_golang/model/labelvalue_test.go b/vendor/github.com/prometheus/client_golang/model/labelvalue_test.go
deleted file mode 100644
index 15904ed..0000000
--- a/vendor/github.com/prometheus/client_golang/model/labelvalue_test.go
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2013 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package model
-
-import (
- "sort"
- "testing"
-)
-
-func testLabelValues(t testing.TB) {
- var scenarios = []struct {
- in LabelValues
- out LabelValues
- }{
- {
- in: LabelValues{"ZZZ", "zzz"},
- out: LabelValues{"ZZZ", "zzz"},
- },
- {
- in: LabelValues{"aaa", "AAA"},
- out: LabelValues{"AAA", "aaa"},
- },
- }
-
- for i, scenario := range scenarios {
- sort.Sort(scenario.in)
-
- for j, expected := range scenario.out {
- if expected != scenario.in[j] {
- t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j])
- }
- }
- }
-}
-
-func TestLabelValues(t *testing.T) {
- testLabelValues(t)
-}
-
-func BenchmarkLabelValues(b *testing.B) {
- for i := 0; i < b.N; i++ {
- testLabelValues(b)
- }
-}
diff --git a/vendor/github.com/prometheus/client_golang/model/metric.go b/vendor/github.com/prometheus/client_golang/model/metric.go
deleted file mode 100644
index 864c012..0000000
--- a/vendor/github.com/prometheus/client_golang/model/metric.go
+++ /dev/null
@@ -1,192 +0,0 @@
-// Copyright 2013 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package model
-
-import (
- "encoding/json"
- "fmt"
- "sort"
- "strings"
-)
-
-var separator = []byte{0}
-
-// A Metric is similar to a LabelSet, but the key difference is that a Metric is
-// a singleton and refers to one and only one stream of samples.
-type Metric map[LabelName]LabelValue
-
-// Equal compares the metrics.
-func (m Metric) Equal(o Metric) bool {
- if len(m) != len(o) {
- return false
- }
- for ln, lv := range m {
- olv, ok := o[ln]
- if !ok {
- return false
- }
- if olv != lv {
- return false
- }
- }
- return true
-}
-
-// Before compares the metrics, using the following criteria:
-//
-// If m has fewer labels than o, it is before o. If it has more, it is not.
-//
-// If the number of labels is the same, the superset of all label names is
-// sorted alphanumerically. The first differing label pair found in that order
-// determines the outcome: If the label does not exist at all in m, then m is
-// before o, and vice versa. Otherwise the label value is compared
-// alphanumerically.
-//
-// If m and o are equal, the method returns false.
-func (m Metric) Before(o Metric) bool {
- if len(m) < len(o) {
- return true
- }
- if len(m) > len(o) {
- return false
- }
-
- lns := make(LabelNames, 0, len(m)+len(o))
- for ln := range m {
- lns = append(lns, ln)
- }
- for ln := range o {
- lns = append(lns, ln)
- }
- // It's probably not worth it to de-dup lns.
- sort.Sort(lns)
- for _, ln := range lns {
- mlv, ok := m[ln]
- if !ok {
- return true
- }
- olv, ok := o[ln]
- if !ok {
- return false
- }
- if mlv < olv {
- return true
- }
- if mlv > olv {
- return false
- }
- }
- return false
-}
-
-// String implements Stringer.
-func (m Metric) String() string {
- metricName, hasName := m[MetricNameLabel]
- numLabels := len(m) - 1
- if !hasName {
- numLabels = len(m)
- }
- labelStrings := make([]string, 0, numLabels)
- for label, value := range m {
- if label != MetricNameLabel {
- labelStrings = append(labelStrings, fmt.Sprintf("%s=%q", label, value))
- }
- }
-
- switch numLabels {
- case 0:
- if hasName {
- return string(metricName)
- }
- return "{}"
- default:
- sort.Strings(labelStrings)
- return fmt.Sprintf("%s{%s}", metricName, strings.Join(labelStrings, ", "))
- }
-}
-
-// Fingerprint returns a Metric's Fingerprint.
-func (m Metric) Fingerprint() Fingerprint {
- return metricToFingerprint(m)
-}
-
-// FastFingerprint returns a Metric's Fingerprint calculated by a faster hashing
-// algorithm, which is, however, more susceptible to hash collisions.
-func (m Metric) FastFingerprint() Fingerprint {
- return metricToFastFingerprint(m)
-}
-
-// Clone returns a copy of the Metric.
-func (m Metric) Clone() Metric {
- clone := Metric{}
- for k, v := range m {
- clone[k] = v
- }
- return clone
-}
-
-// MergeFromLabelSet merges a label set into this Metric, prefixing a collision
-// prefix to the label names merged from the label set where required.
-func (m Metric) MergeFromLabelSet(labels LabelSet, collisionPrefix LabelName) {
- for k, v := range labels {
- if collisionPrefix != "" {
- for {
- if _, exists := m[k]; !exists {
- break
- }
- k = collisionPrefix + k
- }
- }
-
- m[k] = v
- }
-}
-
-// COWMetric wraps a Metric to enable copy-on-write access patterns.
-type COWMetric struct {
- Copied bool
- Metric Metric
-}
-
-// Set sets a label name in the wrapped Metric to a given value and copies the
-// Metric initially, if it is not already a copy.
-func (m *COWMetric) Set(ln LabelName, lv LabelValue) {
- m.doCOW()
- m.Metric[ln] = lv
-}
-
-// Delete deletes a given label name from the wrapped Metric and copies the
-// Metric initially, if it is not already a copy.
-func (m *COWMetric) Delete(ln LabelName) {
- m.doCOW()
- delete(m.Metric, ln)
-}
-
-// doCOW copies the underlying Metric if it is not already a copy.
-func (m *COWMetric) doCOW() {
- if !m.Copied {
- m.Metric = m.Metric.Clone()
- m.Copied = true
- }
-}
-
-// String implements fmt.Stringer.
-func (m COWMetric) String() string {
- return m.Metric.String()
-}
-
-// MarshalJSON implements json.Marshaler.
-func (m COWMetric) MarshalJSON() ([]byte, error) {
- return json.Marshal(m.Metric)
-}
diff --git a/vendor/github.com/prometheus/client_golang/model/sample.go b/vendor/github.com/prometheus/client_golang/model/sample.go
deleted file mode 100644
index c13a44d..0000000
--- a/vendor/github.com/prometheus/client_golang/model/sample.go
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright 2013 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package model
-
-// Sample is a sample value with a timestamp and a metric.
-type Sample struct {
- Metric Metric
- Value SampleValue
- Timestamp Timestamp
-}
-
-// Equal compares first the metrics, then the timestamp, then the value.
-func (s *Sample) Equal(o *Sample) bool {
- if s == o {
- return true
- }
-
- if !s.Metric.Equal(o.Metric) {
- return false
- }
- if !s.Timestamp.Equal(o.Timestamp) {
- return false
- }
- if !s.Value.Equal(o.Value) {
- return false
- }
-
- return true
-}
-
-// Samples is a sortable Sample slice. It implements sort.Interface.
-type Samples []*Sample
-
-func (s Samples) Len() int {
- return len(s)
-}
-
-// Less compares first the metrics, then the timestamp.
-func (s Samples) Less(i, j int) bool {
- switch {
- case s[i].Metric.Before(s[j].Metric):
- return true
- case s[j].Metric.Before(s[i].Metric):
- return false
- case s[i].Timestamp.Before(s[j].Timestamp):
- return true
- default:
- return false
- }
-}
-
-func (s Samples) Swap(i, j int) {
- s[i], s[j] = s[j], s[i]
-}
-
-// Equal compares two sets of samples and returns true if they are equal.
-func (s Samples) Equal(o Samples) bool {
- if len(s) != len(o) {
- return false
- }
-
- for i, sample := range s {
- if !sample.Equal(o[i]) {
- return false
- }
- }
- return true
-}
diff --git a/vendor/github.com/prometheus/client_golang/model/sample_test.go b/vendor/github.com/prometheus/client_golang/model/sample_test.go
deleted file mode 100644
index d5e065d..0000000
--- a/vendor/github.com/prometheus/client_golang/model/sample_test.go
+++ /dev/null
@@ -1,114 +0,0 @@
-// Copyright 2013 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package model
-
-import (
- "sort"
- "testing"
-)
-
-func TestSamplesSort(t *testing.T) {
- input := Samples{
- &Sample{
- Metric: Metric{
- MetricNameLabel: "A",
- },
- Timestamp: 1,
- },
- &Sample{
- Metric: Metric{
- MetricNameLabel: "A",
- },
- Timestamp: 2,
- },
- &Sample{
- Metric: Metric{
- MetricNameLabel: "C",
- },
- Timestamp: 1,
- },
- &Sample{
- Metric: Metric{
- MetricNameLabel: "C",
- },
- Timestamp: 2,
- },
- &Sample{
- Metric: Metric{
- MetricNameLabel: "B",
- },
- Timestamp: 1,
- },
- &Sample{
- Metric: Metric{
- MetricNameLabel: "B",
- },
- Timestamp: 2,
- },
- }
-
- expected := Samples{
- &Sample{
- Metric: Metric{
- MetricNameLabel: "A",
- },
- Timestamp: 1,
- },
- &Sample{
- Metric: Metric{
- MetricNameLabel: "A",
- },
- Timestamp: 2,
- },
- &Sample{
- Metric: Metric{
- MetricNameLabel: "B",
- },
- Timestamp: 1,
- },
- &Sample{
- Metric: Metric{
- MetricNameLabel: "B",
- },
- Timestamp: 2,
- },
- &Sample{
- Metric: Metric{
- MetricNameLabel: "C",
- },
- Timestamp: 1,
- },
- &Sample{
- Metric: Metric{
- MetricNameLabel: "C",
- },
- Timestamp: 2,
- },
- }
-
- sort.Sort(input)
-
- for i, actual := range input {
- actualFp := actual.Metric.Fingerprint()
- expectedFp := expected[i].Metric.Fingerprint()
-
- if !actualFp.Equal(expectedFp) {
- t.Fatalf("%d. Incorrect fingerprint. Got %s; want %s", i, actualFp.String(), expectedFp.String())
- }
-
- if actual.Timestamp != expected[i].Timestamp {
- t.Fatalf("%d. Incorrect timestamp. Got %s; want %s", i, actual.Timestamp, expected[i].Timestamp)
- }
- }
-}
diff --git a/vendor/github.com/prometheus/client_golang/model/timestamp.go b/vendor/github.com/prometheus/client_golang/model/timestamp.go
deleted file mode 100644
index afffdcf..0000000
--- a/vendor/github.com/prometheus/client_golang/model/timestamp.go
+++ /dev/null
@@ -1,116 +0,0 @@
-// Copyright 2013 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package model
-
-import (
- "math"
- "strconv"
-
- native_time "time"
-)
-
-// Timestamp is the number of milliseconds since the epoch
-// (1970-01-01 00:00 UTC) excluding leap seconds.
-type Timestamp int64
-
-const (
- // MinimumTick is the minimum supported time resolution. This has to be
- // at least native_time.Second in order for the code below to work.
- MinimumTick = native_time.Millisecond
- // second is the timestamp duration equivalent to one second.
- second = int64(native_time.Second / MinimumTick)
- // The number of nanoseconds per minimum tick.
- nanosPerTick = int64(MinimumTick / native_time.Nanosecond)
-
- // Earliest is the earliest timestamp representable. Handy for
- // initializing a high watermark.
- Earliest = Timestamp(math.MinInt64)
- // Latest is the latest timestamp representable. Handy for initializing
- // a low watermark.
- Latest = Timestamp(math.MaxInt64)
-)
-
-// Equal reports whether two timestamps represent the same instant.
-func (t Timestamp) Equal(o Timestamp) bool {
- return t == o
-}
-
-// Before reports whether the timestamp t is before o.
-func (t Timestamp) Before(o Timestamp) bool {
- return t < o
-}
-
-// After reports whether the timestamp t is after o.
-func (t Timestamp) After(o Timestamp) bool {
- return t > o
-}
-
-// Add returns the Timestamp t + d.
-func (t Timestamp) Add(d native_time.Duration) Timestamp {
- return t + Timestamp(d/MinimumTick)
-}
-
-// Sub returns the Duration t - o.
-func (t Timestamp) Sub(o Timestamp) native_time.Duration {
- return native_time.Duration(t-o) * MinimumTick
-}
-
-// Time returns the time.Time representation of t.
-func (t Timestamp) Time() native_time.Time {
- return native_time.Unix(int64(t)/second, (int64(t)%second)*nanosPerTick)
-}
-
-// Unix returns t as a Unix time, the number of seconds elapsed
-// since January 1, 1970 UTC.
-func (t Timestamp) Unix() int64 {
- return int64(t) / second
-}
-
-// UnixNano returns t as a Unix time, the number of nanoseconds elapsed
-// since January 1, 1970 UTC.
-func (t Timestamp) UnixNano() int64 {
- return int64(t) * nanosPerTick
-}
-
-// String returns a string representation of the timestamp.
-func (t Timestamp) String() string {
- return strconv.FormatFloat(float64(t)/float64(second), 'f', -1, 64)
-}
-
-// MarshalJSON implements the json.Marshaler interface.
-func (t Timestamp) MarshalJSON() ([]byte, error) {
- return []byte(t.String()), nil
-}
-
-// Now returns the current time as a Timestamp.
-func Now() Timestamp {
- return TimestampFromTime(native_time.Now())
-}
-
-// TimestampFromTime returns the Timestamp equivalent to the time.Time t.
-func TimestampFromTime(t native_time.Time) Timestamp {
- return TimestampFromUnixNano(t.UnixNano())
-}
-
-// TimestampFromUnix returns the Timestamp equivalent to the Unix timestamp t
-// provided in seconds.
-func TimestampFromUnix(t int64) Timestamp {
- return Timestamp(t * second)
-}
-
-// TimestampFromUnixNano returns the Timestamp equivalent to the Unix timestamp
-// t provided in nanoseconds.
-func TimestampFromUnixNano(t int64) Timestamp {
- return Timestamp(t / nanosPerTick)
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/README.md b/vendor/github.com/prometheus/client_golang/prometheus/README.md
index 81032be..44986bf 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/README.md
+++ b/vendor/github.com/prometheus/client_golang/prometheus/README.md
@@ -1,53 +1 @@
-# Overview
-This is the [Prometheus](http://www.prometheus.io) telemetric
-instrumentation client [Go](http://golang.org) client library. It
-enable authors to define process-space metrics for their servers and
-expose them through a web service interface for extraction,
-aggregation, and a whole slew of other post processing techniques.
-
-# Installing
- $ go get github.com/prometheus/client_golang/prometheus
-
-# Example
-```go
-package main
-
-import (
- "net/http"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-var (
- indexed = prometheus.NewCounter(prometheus.CounterOpts{
- Namespace: "my_company",
- Subsystem: "indexer",
- Name: "documents_indexed",
- Help: "The number of documents indexed.",
- })
- size = prometheus.NewGauge(prometheus.GaugeOpts{
- Namespace: "my_company",
- Subsystem: "storage",
- Name: "documents_total_size_bytes",
- Help: "The total size of all documents in the storage.",
- })
-)
-
-func main() {
- http.Handle("/metrics", prometheus.Handler())
-
- indexed.Inc()
- size.Set(5)
-
- http.ListenAndServe(":8080", nil)
-}
-
-func init() {
- prometheus.MustRegister(indexed)
- prometheus.MustRegister(size)
-}
-```
-
-# Documentation
-
-[![GoDoc](https://godoc.org/github.com/prometheus/client_golang?status.png)](https://godoc.org/github.com/prometheus/client_golang)
+See [![go-doc](https://godoc.org/github.com/prometheus/client_golang/prometheus?status.svg)](https://godoc.org/github.com/prometheus/client_golang/prometheus).
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go b/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go
index 6ae7333..a3d8669 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/benchmark_test.go
@@ -14,6 +14,7 @@
package prometheus
import (
+ "sync"
"testing"
)
@@ -32,6 +33,29 @@ func BenchmarkCounterWithLabelValues(b *testing.B) {
}
}
+func BenchmarkCounterWithLabelValuesConcurrent(b *testing.B) {
+ m := NewCounterVec(
+ CounterOpts{
+ Name: "benchmark_counter",
+ Help: "A counter to benchmark it.",
+ },
+ []string{"one", "two", "three"},
+ )
+ b.ReportAllocs()
+ b.ResetTimer()
+ wg := sync.WaitGroup{}
+ for i := 0; i < 10; i++ {
+ wg.Add(1)
+ go func() {
+ for j := 0; j < b.N/10; j++ {
+ m.WithLabelValues("eins", "zwei", "drei").Inc()
+ }
+ wg.Done()
+ }()
+ }
+ wg.Wait()
+}
+
func BenchmarkCounterWithMappedLabels(b *testing.B) {
m := NewCounterVec(
CounterOpts{
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/collector.go b/vendor/github.com/prometheus/client_golang/prometheus/collector.go
index c046880..623d3d8 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/collector.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/collector.go
@@ -15,15 +15,15 @@ package prometheus
// Collector is the interface implemented by anything that can be used by
// Prometheus to collect metrics. A Collector has to be registered for
-// collection. See Register, MustRegister, RegisterOrGet, and MustRegisterOrGet.
+// collection. See Registerer.Register.
//
-// The stock metrics provided by this package (like Gauge, Counter, Summary) are
-// also Collectors (which only ever collect one metric, namely itself). An
-// implementer of Collector may, however, collect multiple metrics in a
-// coordinated fashion and/or create metrics on the fly. Examples for collectors
-// already implemented in this library are the metric vectors (i.e. collection
-// of multiple instances of the same Metric but with different label values)
-// like GaugeVec or SummaryVec, and the ExpvarCollector.
+// The stock metrics provided by this package (Gauge, Counter, Summary,
+// Histogram, Untyped) are also Collectors (which only ever collect one metric,
+// namely itself). An implementer of Collector may, however, collect multiple
+// metrics in a coordinated fashion and/or create metrics on the fly. Examples
+// for collectors already implemented in this library are the metric vectors
+// (i.e. collection of multiple instances of the same Metric but with different
+// label values) like GaugeVec or SummaryVec, and the ExpvarCollector.
type Collector interface {
// Describe sends the super-set of all possible descriptors of metrics
// collected by this Collector to the provided channel and returns once
@@ -37,39 +37,39 @@ type Collector interface {
// executing this method, it must send an invalid descriptor (created
// with NewInvalidDesc) to signal the error to the registry.
Describe(chan<- *Desc)
- // Collect is called by Prometheus when collecting metrics. The
- // implementation sends each collected metric via the provided channel
- // and returns once the last metric has been sent. The descriptor of
- // each sent metric is one of those returned by Describe. Returned
- // metrics that share the same descriptor must differ in their variable
- // label values. This method may be called concurrently and must
- // therefore be implemented in a concurrency safe way. Blocking occurs
- // at the expense of total performance of rendering all registered
- // metrics. Ideally, Collector implementations support concurrent
- // readers.
+ // Collect is called by the Prometheus registry when collecting
+ // metrics. The implementation sends each collected metric via the
+ // provided channel and returns once the last metric has been sent. The
+ // descriptor of each sent metric is one of those returned by
+ // Describe. Returned metrics that share the same descriptor must differ
+ // in their variable label values. This method may be called
+ // concurrently and must therefore be implemented in a concurrency safe
+ // way. Blocking occurs at the expense of total performance of rendering
+ // all registered metrics. Ideally, Collector implementations support
+ // concurrent readers.
Collect(chan<- Metric)
}
-// SelfCollector implements Collector for a single Metric so that that the
-// Metric collects itself. Add it as an anonymous field to a struct that
-// implements Metric, and call Init with the Metric itself as an argument.
-type SelfCollector struct {
+// selfCollector implements Collector for a single Metric so that the Metric
+// collects itself. Add it as an anonymous field to a struct that implements
+// Metric, and call init with the Metric itself as an argument.
+type selfCollector struct {
self Metric
}
-// Init provides the SelfCollector with a reference to the metric it is supposed
+// init provides the selfCollector with a reference to the metric it is supposed
// to collect. It is usually called within the factory function to create a
// metric. See example.
-func (c *SelfCollector) Init(self Metric) {
+func (c *selfCollector) init(self Metric) {
c.self = self
}
// Describe implements Collector.
-func (c *SelfCollector) Describe(ch chan<- *Desc) {
+func (c *selfCollector) Describe(ch chan<- *Desc) {
ch <- c.self.Desc()
}
// Collect implements Collector.
-func (c *SelfCollector) Collect(ch chan<- Metric) {
+func (c *selfCollector) Collect(ch chan<- Metric) {
ch <- c.self
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/counter.go b/vendor/github.com/prometheus/client_golang/prometheus/counter.go
index a2952d1..ee37949 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/counter.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/counter.go
@@ -15,7 +15,6 @@ package prometheus
import (
"errors"
- "hash/fnv"
)
// Counter is a Metric that represents a single numerical value that only ever
@@ -36,6 +35,9 @@ type Counter interface {
// Prometheus metric. Do not use it for regular handling of a
// Prometheus counter (as it can be used to break the contract of
// monotonically increasing values).
+ //
+ // Deprecated: Use NewConstMetric to create a counter for an external
+ // value. A Counter should never be set.
Set(float64)
// Inc increments the counter by 1.
Inc()
@@ -56,7 +58,7 @@ func NewCounter(opts CounterOpts) Counter {
opts.ConstLabels,
)
result := &counter{value: value{desc: desc, valType: CounterValue, labelPairs: desc.constLabelPairs}}
- result.Init(result) // Init self-collection.
+ result.init(result) // Init self-collection.
return result
}
@@ -80,7 +82,7 @@ func (c *counter) Add(v float64) {
// CounterVec embeds MetricVec. See there for a full list of methods with
// detailed documentation.
type CounterVec struct {
- MetricVec
+ *MetricVec
}
// NewCounterVec creates a new CounterVec based on the provided CounterOpts and
@@ -94,20 +96,15 @@ func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec {
opts.ConstLabels,
)
return &CounterVec{
- MetricVec: MetricVec{
- children: map[uint64]Metric{},
- desc: desc,
- hash: fnv.New64a(),
- newMetric: func(lvs ...string) Metric {
- result := &counter{value: value{
- desc: desc,
- valType: CounterValue,
- labelPairs: makeLabelPairs(desc, lvs),
- }}
- result.Init(result) // Init self-collection.
- return result
- },
- },
+ MetricVec: newMetricVec(desc, func(lvs ...string) Metric {
+ result := &counter{value: value{
+ desc: desc,
+ valType: CounterValue,
+ labelPairs: makeLabelPairs(desc, lvs),
+ }}
+ result.init(result) // Init self-collection.
+ return result
+ }),
}
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/desc.go b/vendor/github.com/prometheus/client_golang/prometheus/desc.go
index 1fe10bc..77f4b30 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/desc.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/desc.go
@@ -1,10 +1,21 @@
+// Copyright 2016 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
package prometheus
import (
- "bytes"
"errors"
"fmt"
- "hash/fnv"
"regexp"
"sort"
"strings"
@@ -12,14 +23,17 @@ import (
"github.com/golang/protobuf/proto"
dto "github.com/prometheus/client_model/go"
-
- "github.com/prometheus/client_golang/model"
)
var (
metricNameRE = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_:]*$`)
+ labelNameRE = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
)
+// reservedLabelPrefix is a prefix which is not legal in user-supplied
+// label names.
+const reservedLabelPrefix = "__"
+
// Labels represents a collection of label name -> value mappings. This type is
// commonly used with the With(Labels) and GetMetricWith(Labels) methods of
// metric vector Collectors, e.g.:
@@ -128,31 +142,24 @@ func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *
d.err = errors.New("duplicate label names")
return d
}
- h := fnv.New64a()
- var b bytes.Buffer // To copy string contents into, avoiding []byte allocations.
+ vh := hashNew()
for _, val := range labelValues {
- b.Reset()
- b.WriteString(val)
- b.WriteByte(model.SeparatorByte)
- h.Write(b.Bytes())
+ vh = hashAdd(vh, val)
+ vh = hashAddByte(vh, separatorByte)
}
- d.id = h.Sum64()
+ d.id = vh
// Sort labelNames so that order doesn't matter for the hash.
sort.Strings(labelNames)
// Now hash together (in this order) the help string and the sorted
// label names.
- h.Reset()
- b.Reset()
- b.WriteString(help)
- b.WriteByte(model.SeparatorByte)
- h.Write(b.Bytes())
+ lh := hashNew()
+ lh = hashAdd(lh, help)
+ lh = hashAddByte(lh, separatorByte)
for _, labelName := range labelNames {
- b.Reset()
- b.WriteString(labelName)
- b.WriteByte(model.SeparatorByte)
- h.Write(b.Bytes())
+ lh = hashAdd(lh, labelName)
+ lh = hashAddByte(lh, separatorByte)
}
- d.dimHash = h.Sum64()
+ d.dimHash = lh
d.constLabelPairs = make([]*dto.LabelPair, 0, len(constLabels))
for n, v := range constLabels {
@@ -193,6 +200,6 @@ func (d *Desc) String() string {
}
func checkLabelName(l string) bool {
- return model.LabelNameRE.MatchString(l) &&
- !strings.HasPrefix(l, model.ReservedLabelPrefix)
+ return labelNameRE.MatchString(l) &&
+ !strings.HasPrefix(l, reservedLabelPrefix)
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/doc.go b/vendor/github.com/prometheus/client_golang/prometheus/doc.go
index 425fe87..b15a2d3 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/doc.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/doc.go
@@ -11,18 +11,17 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-// Package prometheus provides embeddable metric primitives for servers and
-// standardized exposition of telemetry through a web services interface.
+// Package prometheus provides metrics primitives to instrument code for
+// monitoring. It also offers a registry for metrics. Sub-packages allow to
+// expose the registered metrics via HTTP (package promhttp) or push them to a
+// Pushgateway (package push).
//
// All exported functions and methods are safe to be used concurrently unless
-// specified otherwise.
+//specified otherwise.
//
-// To expose metrics registered with the Prometheus registry, an HTTP server
-// needs to know about the Prometheus handler. The usual endpoint is "/metrics".
+// A Basic Example
//
-// http.Handle("/metrics", prometheus.Handler())
-//
-// As a starting point a very basic usage example:
+// As a starting point, a very basic usage example:
//
// package main
//
@@ -30,6 +29,7 @@
// "net/http"
//
// "github.com/prometheus/client_golang/prometheus"
+// "github.com/prometheus/client_golang/prometheus/promhttp"
// )
//
// var (
@@ -37,73 +37,145 @@
// Name: "cpu_temperature_celsius",
// Help: "Current temperature of the CPU.",
// })
-// hdFailures = prometheus.NewCounter(prometheus.CounterOpts{
-// Name: "hd_errors_total",
-// Help: "Number of hard-disk errors.",
-// })
+// hdFailures = prometheus.NewCounterVec(
+// prometheus.CounterOpts{
+// Name: "hd_errors_total",
+// Help: "Number of hard-disk errors.",
+// },
+// []string{"device"},
+// )
// )
//
// func init() {
+// // Metrics have to be registered to be exposed:
// prometheus.MustRegister(cpuTemp)
// prometheus.MustRegister(hdFailures)
// }
//
// func main() {
// cpuTemp.Set(65.3)
-// hdFailures.Inc()
+// hdFailures.With(prometheus.Labels{"device":"/dev/sda"}).Inc()
//
-// http.Handle("/metrics", prometheus.Handler())
+// // The Handler function provides a default handler to expose metrics
+// // via an HTTP server. "/metrics" is the usual endpoint for that.
+// http.Handle("/metrics", promhttp.Handler())
// http.ListenAndServe(":8080", nil)
// }
//
//
-// This is a complete program that exports two metrics, a Gauge and a Counter.
-// It also exports some stats about the HTTP usage of the /metrics
-// endpoint. (See the Handler function for more detail.)
+// This is a complete program that exports two metrics, a Gauge and a Counter,
+// the latter with a label attached to turn it into a (one-dimensional) vector.
//
-// Two more advanced metric types are the Summary and Histogram.
+// Metrics
//
-// In addition to the fundamental metric types Gauge, Counter, Summary, and
-// Histogram, a very important part of the Prometheus data model is the
-// partitioning of samples along dimensions called labels, which results in
+// The number of exported identifiers in this package might appear a bit
+// overwhelming. Hovever, in addition to the basic plumbing shown in the example
+// above, you only need to understand the different metric types and their
+// vector versions for basic usage.
+//
+// Above, you have already touched the Counter and the Gauge. There are two more
+// advanced metric types: the Summary and Histogram. A more thorough description
+// of those four metric types can be found in the Prometheus docs:
+// https://prometheus.io/docs/concepts/metric_types/
+//
+// A fifth "type" of metric is Untyped. It behaves like a Gauge, but signals the
+// Prometheus server not to assume anything about its type.
+//
+// In addition to the fundamental metric types Gauge, Counter, Summary,
+// Histogram, and Untyped, a very important part of the Prometheus data model is
+// the partitioning of samples along dimensions called labels, which results in
// metric vectors. The fundamental types are GaugeVec, CounterVec, SummaryVec,
-// and HistogramVec.
+// HistogramVec, and UntypedVec.
//
-// Those are all the parts needed for basic usage. Detailed documentation and
-// examples are provided below.
+// While only the fundamental metric types implement the Metric interface, both
+// the metrics and their vector versions implement the Collector interface. A
+// Collector manages the collection of a number of Metrics, but for convenience,
+// a Metric can also “collect itself”. Note that Gauge, Counter, Summary,
+// Histogram, and Untyped are interfaces themselves while GaugeVec, CounterVec,
+// SummaryVec, HistogramVec, and UntypedVec are not.
//
-// Everything else this package offers is essentially for "power users" only. A
-// few pointers to "power user features":
+// To create instances of Metrics and their vector versions, you need a suitable
+// …Opts struct, i.e. GaugeOpts, CounterOpts, SummaryOpts,
+// HistogramOpts, or UntypedOpts.
//
-// All the various ...Opts structs have a ConstLabels field for labels that
-// never change their value (which is only useful under special circumstances,
-// see documentation of the Opts type).
+// Custom Collectors and constant Metrics
//
-// The Untyped metric behaves like a Gauge, but signals the Prometheus server
-// not to assume anything about its type.
+// While you could create your own implementations of Metric, most likely you
+// will only ever implement the Collector interface on your own. At a first
+// glance, a custom Collector seems handy to bundle Metrics for common
+// registration (with the prime example of the different metric vectors above,
+// which bundle all the metrics of the same name but with different labels).
//
-// Functions to fine-tune how the metric registry works: EnableCollectChecks,
-// PanicOnCollectError, Register, Unregister, SetMetricFamilyInjectionHook.
+// There is a more involved use case, too: If you already have metrics
+// available, created outside of the Prometheus context, you don't need the
+// interface of the various Metric types. You essentially want to mirror the
+// existing numbers into Prometheus Metrics during collection. An own
+// implementation of the Collector interface is perfect for that. You can create
+// Metric instances “on the fly” using NewConstMetric, NewConstHistogram, and
+// NewConstSummary (and their respective Must… versions). That will happen in
+// the Collect method. The Describe method has to return separate Desc
+// instances, representative of the “throw-away” metrics to be created
+// later. NewDesc comes in handy to create those Desc instances.
//
-// For custom metric collection, there are two entry points: Custom Metric
-// implementations and custom Collector implementations. A Metric is the
-// fundamental unit in the Prometheus data model: a sample at a point in time
-// together with its meta-data (like its fully-qualified name and any number of
-// pairs of label name and label value) that knows how to marshal itself into a
-// data transfer object (aka DTO, implemented as a protocol buffer). A Collector
-// gets registered with the Prometheus registry and manages the collection of
-// one or more Metrics. Many parts of this package are building blocks for
-// Metrics and Collectors. Desc is the metric descriptor, actually used by all
-// metrics under the hood, and by Collectors to describe the Metrics to be
-// collected, but only to be dealt with by users if they implement their own
-// Metrics or Collectors. To create a Desc, the BuildFQName function will come
-// in handy. Other useful components for Metric and Collector implementation
-// include: LabelPairSorter to sort the DTO version of label pairs,
-// NewConstMetric and MustNewConstMetric to create "throw away" Metrics at
-// collection time, MetricVec to bundle custom Metrics into a metric vector
-// Collector, SelfCollector to make a custom Metric collect itself.
+// The Collector example illustrates the use case. You can also look at the
+// source code of the processCollector (mirroring process metrics), the
+// goCollector (mirroring Go metrics), or the expvarCollector (mirroring expvar
+// metrics) as examples that are used in this package itself.
//
-// A good example for a custom Collector is the ExpVarCollector included in this
-// package, which exports variables exported via the "expvar" package as
-// Prometheus metrics.
+// If you just need to call a function to get a single float value to collect as
+// a metric, GaugeFunc, CounterFunc, or UntypedFunc might be interesting
+// shortcuts.
+//
+// Advanced Uses of the Registry
+//
+// While MustRegister is the by far most common way of registering a Collector,
+// sometimes you might want to handle the errors the registration might
+// cause. As suggested by the name, MustRegister panics if an error occurs. With
+// the Register function, the error is returned and can be handled.
+//
+// An error is returned if the registered Collector is incompatible or
+// inconsistent with already registered metrics. The registry aims for
+// consistency of the collected metrics according to the Prometheus data
+// model. Inconsistencies are ideally detected at registration time, not at
+// collect time. The former will usually be detected at start-up time of a
+// program, while the latter will only happen at scrape time, possibly not even
+// on the first scrape if the inconsistency only becomes relevant later. That is
+// the main reason why a Collector and a Metric have to describe themselves to
+// the registry.
+//
+// So far, everything we did operated on the so-called default registry, as it
+// can be found in the global DefaultRegistry variable. With NewRegistry, you
+// can create a custom registry, or you can even implement the Registerer or
+// Gatherer interfaces yourself. The methods Register and Unregister work in
+// the same way on a custom registry as the global functions Register and
+// Unregister on the default registry.
+//
+// There are a number of uses for custom registries: You can use registries
+// with special properties, see NewPedanticRegistry. You can avoid global state,
+// as it is imposed by the DefaultRegistry. You can use multiple registries at
+// the same time to expose different metrics in different ways. You can use
+// separate registries for testing purposes.
+//
+// Also note that the DefaultRegistry comes registered with a Collector for Go
+// runtime metrics (via NewGoCollector) and a Collector for process metrics (via
+// NewProcessCollector). With a custom registry, you are in control and decide
+// yourself about the Collectors to register.
+//
+// HTTP Exposition
+//
+// The Registry implements the Gatherer interface. The caller of the Gather
+// method can then expose the gathered metrics in some way. Usually, the metrics
+// are served via HTTP on the /metrics endpoint. That's happening in the example
+// above. The tools to expose metrics via HTTP are in the promhttp
+// sub-package. (The top-level functions in the prometheus package are
+// deprecated.)
+//
+// Pushing to the Pushgateway
+//
+// Function for pushing to the Pushgateway can be found in the push sub-package.
+//
+// Other Means of Exposition
+//
+// More ways of exposing metrics can easily be added. Sending metrics to
+// Graphite would be an example that will soon be implemented.
package prometheus
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go b/vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go
index 6f3e215..260c1b5 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/example_clustermanager_test.go
@@ -13,11 +13,7 @@
package prometheus_test
-import (
- "sync"
-
- "github.com/prometheus/client_golang/prometheus"
-)
+import "github.com/prometheus/client_golang/prometheus"
// ClusterManager is an example for a system that might have been built without
// Prometheus in mind. It models a central manager of jobs running in a
@@ -29,10 +25,9 @@ import (
// make use of ConstLabels to be able to register each ClusterManager instance
// with Prometheus.
type ClusterManager struct {
- Zone string
- OOMCount *prometheus.CounterVec
- RAMUsage *prometheus.GaugeVec
- mtx sync.Mutex // Protects OOMCount and RAMUsage.
+ Zone string
+ OOMCountDesc *prometheus.Desc
+ RAMUsageDesc *prometheus.Desc
// ... many more fields
}
@@ -55,76 +50,69 @@ func (c *ClusterManager) ReallyExpensiveAssessmentOfTheSystemState() (
return
}
-// Describe faces the interesting challenge that the two metric vectors that are
-// used in this example are already Collectors themselves. However, thanks to
-// the use of channels, it is really easy to "chain" Collectors. Here we simply
-// call the Describe methods of the two metric vectors.
+// Describe simply sends the two Descs in the struct to the channel.
func (c *ClusterManager) Describe(ch chan<- *prometheus.Desc) {
- c.OOMCount.Describe(ch)
- c.RAMUsage.Describe(ch)
+ ch <- c.OOMCountDesc
+ ch <- c.RAMUsageDesc
}
// Collect first triggers the ReallyExpensiveAssessmentOfTheSystemState. Then it
-// sets the retrieved values in the two metric vectors and then sends all their
-// metrics to the channel (again using a chaining technique as in the Describe
-// method). Since Collect could be called multiple times concurrently, that part
-// is protected by a mutex.
+// creates constant metrics for each host on the fly based on the returned data.
+//
+// Note that Collect could be called concurrently, so we depend on
+// ReallyExpensiveAssessmentOfTheSystemState to be concurrency-safe.
func (c *ClusterManager) Collect(ch chan<- prometheus.Metric) {
oomCountByHost, ramUsageByHost := c.ReallyExpensiveAssessmentOfTheSystemState()
- c.mtx.Lock()
- defer c.mtx.Unlock()
for host, oomCount := range oomCountByHost {
- c.OOMCount.WithLabelValues(host).Set(float64(oomCount))
+ ch <- prometheus.MustNewConstMetric(
+ c.OOMCountDesc,
+ prometheus.CounterValue,
+ float64(oomCount),
+ host,
+ )
}
for host, ramUsage := range ramUsageByHost {
- c.RAMUsage.WithLabelValues(host).Set(ramUsage)
+ ch <- prometheus.MustNewConstMetric(
+ c.RAMUsageDesc,
+ prometheus.GaugeValue,
+ ramUsage,
+ host,
+ )
}
- c.OOMCount.Collect(ch)
- c.RAMUsage.Collect(ch)
- // All metrics in OOMCount and RAMUsage are sent to the channel now. We
- // can safely reset the two metric vectors now, so that we can start
- // fresh in the next Collect cycle. (Imagine a host disappears from the
- // cluster. If we did not reset here, its Metric would stay in the
- // metric vectors forever.)
- c.OOMCount.Reset()
- c.RAMUsage.Reset()
}
-// NewClusterManager creates the two metric vectors OOMCount and RAMUsage. Note
+// NewClusterManager creates the two Descs OOMCountDesc and RAMUsageDesc. Note
// that the zone is set as a ConstLabel. (It's different in each instance of the
-// ClusterManager, but constant over the lifetime of an instance.) The reported
-// values are partitioned by host, which is therefore a variable label.
+// ClusterManager, but constant over the lifetime of an instance.) Then there is
+// a variable label "host", since we want to partition the collected metrics by
+// host. Since all Descs created in this way are consistent across instances,
+// with a guaranteed distinction by the "zone" label, we can register different
+// ClusterManager instances with the same registry.
func NewClusterManager(zone string) *ClusterManager {
return &ClusterManager{
Zone: zone,
- OOMCount: prometheus.NewCounterVec(
- prometheus.CounterOpts{
- Subsystem: "clustermanager",
- Name: "oom_count",
- Help: "number of OOM crashes",
- ConstLabels: prometheus.Labels{"zone": zone},
- },
+ OOMCountDesc: prometheus.NewDesc(
+ "clustermanager_oom_crashes_total",
+ "Number of OOM crashes.",
[]string{"host"},
+ prometheus.Labels{"zone": zone},
),
- RAMUsage: prometheus.NewGaugeVec(
- prometheus.GaugeOpts{
- Subsystem: "clustermanager",
- Name: "ram_usage_bytes",
- Help: "RAM usage as reported to the cluster manager",
- ConstLabels: prometheus.Labels{"zone": zone},
- },
+ RAMUsageDesc: prometheus.NewDesc(
+ "clustermanager_ram_usage_bytes",
+ "RAM usage as reported to the cluster manager.",
[]string{"host"},
+ prometheus.Labels{"zone": zone},
),
}
}
-func ExampleCollector_clustermanager() {
+func ExampleCollector() {
workerDB := NewClusterManager("db")
workerCA := NewClusterManager("ca")
- prometheus.MustRegister(workerDB)
- prometheus.MustRegister(workerCA)
// Since we are dealing with custom Collector implementations, it might
- // be a good idea to enable the collect checks in the registry.
- prometheus.EnableCollectChecks(true)
+ // be a good idea to try it out with a pedantic registry.
+ reg := prometheus.NewPedanticRegistry()
+ reg.MustRegister(workerDB)
+ reg.MustRegister(workerCA)
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/example_memstats_test.go b/vendor/github.com/prometheus/client_golang/prometheus/example_memstats_test.go
deleted file mode 100644
index a84d072..0000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/example_memstats_test.go
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright 2014 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package prometheus_test
-
-import (
- "runtime"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-var (
- allocDesc = prometheus.NewDesc(
- prometheus.BuildFQName("", "memstats", "alloc_bytes"),
- "bytes allocated and still in use",
- nil, nil,
- )
- totalAllocDesc = prometheus.NewDesc(
- prometheus.BuildFQName("", "memstats", "total_alloc_bytes"),
- "bytes allocated (even if freed)",
- nil, nil,
- )
- numGCDesc = prometheus.NewDesc(
- prometheus.BuildFQName("", "memstats", "num_gc_total"),
- "number of GCs run",
- nil, nil,
- )
-)
-
-// MemStatsCollector is an example for a custom Collector that solves the
-// problem of feeding into multiple metrics at the same time. The
-// runtime.ReadMemStats should happen only once, and then the results need to be
-// fed into a number of separate Metrics. In this example, only a few of the
-// values reported by ReadMemStats are used. For each, there is a Desc provided
-// as a var, so the MemStatsCollector itself needs nothing else in the
-// struct. Only the methods need to be implemented.
-type MemStatsCollector struct{}
-
-// Describe just sends the three Desc objects for the Metrics we intend to
-// collect.
-func (_ MemStatsCollector) Describe(ch chan<- *prometheus.Desc) {
- ch <- allocDesc
- ch <- totalAllocDesc
- ch <- numGCDesc
-}
-
-// Collect does the trick by calling ReadMemStats once and then constructing
-// three different Metrics on the fly.
-func (_ MemStatsCollector) Collect(ch chan<- prometheus.Metric) {
- var ms runtime.MemStats
- runtime.ReadMemStats(&ms)
- ch <- prometheus.MustNewConstMetric(
- allocDesc,
- prometheus.GaugeValue,
- float64(ms.Alloc),
- )
- ch <- prometheus.MustNewConstMetric(
- totalAllocDesc,
- prometheus.GaugeValue,
- float64(ms.TotalAlloc),
- )
- ch <- prometheus.MustNewConstMetric(
- numGCDesc,
- prometheus.CounterValue,
- float64(ms.NumGC),
- )
- // To avoid new allocations on each collection, you could also keep
- // metric objects around and return the same objects each time, just
- // with new values set.
-}
-
-func ExampleCollector_memstats() {
- prometheus.MustRegister(&MemStatsCollector{})
- // Since we are dealing with custom Collector implementations, it might
- // be a good idea to enable the collect checks in the registry.
- prometheus.EnableCollectChecks(true)
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/example_selfcollector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/example_selfcollector_test.go
deleted file mode 100644
index 608deeb..0000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/example_selfcollector_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2014 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package prometheus_test
-
-import (
- "runtime"
-
- "github.com/golang/protobuf/proto"
-
- dto "github.com/prometheus/client_model/go"
-
- "github.com/prometheus/client_golang/prometheus"
-)
-
-func NewCallbackMetric(desc *prometheus.Desc, callback func() float64) *CallbackMetric {
- result := &CallbackMetric{desc: desc, callback: callback}
- result.Init(result) // Initialize the SelfCollector.
- return result
-}
-
-// TODO: Come up with a better example.
-
-// CallbackMetric is an example for a user-defined Metric that exports the
-// result of a function call as a metric of type "untyped" without any
-// labels. It uses SelfCollector to turn the Metric into a Collector so that it
-// can be registered with Prometheus.
-//
-// Note that this example is pretty much academic as the prometheus package
-// already provides an UntypedFunc type.
-type CallbackMetric struct {
- prometheus.SelfCollector
-
- desc *prometheus.Desc
- callback func() float64
-}
-
-func (cm *CallbackMetric) Desc() *prometheus.Desc {
- return cm.desc
-}
-
-func (cm *CallbackMetric) Write(m *dto.Metric) error {
- m.Untyped = &dto.Untyped{Value: proto.Float64(cm.callback())}
- return nil
-}
-
-func ExampleSelfCollector() {
- m := NewCallbackMetric(
- prometheus.NewDesc(
- "runtime_goroutines_count",
- "Total number of goroutines that currently exist.",
- nil, nil, // No labels, these must be nil.
- ),
- func() float64 {
- return float64(runtime.NumGoroutine())
- },
- )
- prometheus.MustRegister(m)
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go b/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go
index a28a801..f87f21a 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/examples_test.go
@@ -14,16 +14,16 @@
package prometheus_test
import (
- "flag"
+ "bytes"
"fmt"
"math"
"net/http"
- "os"
"runtime"
"sort"
- "time"
+ "strings"
dto "github.com/prometheus/client_model/go"
+ "github.com/prometheus/common/expfmt"
"github.com/golang/protobuf/proto"
@@ -48,16 +48,12 @@ func ExampleGauge() {
}
func ExampleGaugeVec() {
- binaryVersion := flag.String("binary_version", "debug", "Version of the binary: debug, canary, production.")
- flag.Parse()
-
opsQueued := prometheus.NewGaugeVec(
prometheus.GaugeOpts{
- Namespace: "our_company",
- Subsystem: "blob_storage",
- Name: "ops_queued",
- Help: "Number of blob storage operations waiting to be processed, partitioned by user and type.",
- ConstLabels: prometheus.Labels{"binary_version": *binaryVersion},
+ Namespace: "our_company",
+ Subsystem: "blob_storage",
+ Name: "ops_queued",
+ Help: "Number of blob storage operations waiting to be processed, partitioned by user and type.",
},
[]string{
// Which user has requested the operation?
@@ -125,14 +121,10 @@ func ExampleCounter() {
}
func ExampleCounterVec() {
- binaryVersion := flag.String("environment", "test", "Execution environment: test, staging, production.")
- flag.Parse()
-
httpReqs := prometheus.NewCounterVec(
prometheus.CounterOpts{
- Name: "http_requests_total",
- Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
- ConstLabels: prometheus.Labels{"env": *binaryVersion},
+ Name: "http_requests_total",
+ Help: "How many HTTP requests processed, partitioned by status code and HTTP method.",
},
[]string{"code", "method"},
)
@@ -392,70 +384,94 @@ func ExampleSummaryVec() {
temps.WithLabelValues("lithobates-catesbeianus").Observe(32 + math.Floor(100*math.Cos(float64(i)*0.11))/10)
}
- // Just for demonstration, let's check the state of the summary vector
- // by (ab)using its Collect method and the Write method of its elements
- // (which is usually only used by Prometheus internally - code like the
- // following will never appear in your own code).
- metricChan := make(chan prometheus.Metric)
- go func() {
- defer close(metricChan)
- temps.Collect(metricChan)
- }()
+ // Create a Summary without any observations.
+ temps.WithLabelValues("leiopelma-hochstetteri")
- metricStrings := []string{}
- for metric := range metricChan {
- dtoMetric := &dto.Metric{}
- metric.Write(dtoMetric)
- metricStrings = append(metricStrings, proto.MarshalTextString(dtoMetric))
+ // Just for demonstration, let's check the state of the summary vector
+ // by registering it with a custom registry and then let it collect the
+ // metrics.
+ reg := prometheus.NewRegistry()
+ reg.MustRegister(temps)
+
+ metricFamilies, err := reg.Gather()
+ if err != nil || len(metricFamilies) != 1 {
+ panic("unexpected behavior of custom test registry")
}
- sort.Strings(metricStrings) // For reproducible print order.
- fmt.Println(metricStrings)
+ fmt.Println(proto.MarshalTextString(metricFamilies[0]))
// Output:
- // [label: <
- // name: "species"
- // value: "lithobates-catesbeianus"
- // >
- // summary: <
- // sample_count: 1000
- // sample_sum: 31956.100000000017
- // quantile: <
- // quantile: 0.5
- // value: 32.4
+ // name: "pond_temperature_celsius"
+ // help: "The temperature of the frog pond."
+ // type: SUMMARY
+ // metric: <
+ // label: <
+ // name: "species"
+ // value: "leiopelma-hochstetteri"
// >
- // quantile: <
- // quantile: 0.9
- // value: 41.4
- // >
- // quantile: <
- // quantile: 0.99
- // value: 41.9
+ // summary: <
+ // sample_count: 0
+ // sample_sum: 0
+ // quantile: <
+ // quantile: 0.5
+ // value: nan
+ // >
+ // quantile: <
+ // quantile: 0.9
+ // value: nan
+ // >
+ // quantile: <
+ // quantile: 0.99
+ // value: nan
+ // >
// >
// >
- // label: <
- // name: "species"
- // value: "litoria-caerulea"
- // >
- // summary: <
- // sample_count: 1000
- // sample_sum: 29969.50000000001
- // quantile: <
- // quantile: 0.5
- // value: 31.1
+ // metric: <
+ // label: <
+ // name: "species"
+ // value: "lithobates-catesbeianus"
// >
- // quantile: <
- // quantile: 0.9
- // value: 41.3
- // >
- // quantile: <
- // quantile: 0.99
- // value: 41.9
+ // summary: <
+ // sample_count: 1000
+ // sample_sum: 31956.100000000017
+ // quantile: <
+ // quantile: 0.5
+ // value: 32.4
+ // >
+ // quantile: <
+ // quantile: 0.9
+ // value: 41.4
+ // >
+ // quantile: <
+ // quantile: 0.99
+ // value: 41.9
+ // >
+ // >
+ // >
+ // metric: <
+ // label: <
+ // name: "species"
+ // value: "litoria-caerulea"
+ // >
+ // summary: <
+ // sample_count: 1000
+ // sample_sum: 29969.50000000001
+ // quantile: <
+ // quantile: 0.5
+ // value: 31.1
+ // >
+ // quantile: <
+ // quantile: 0.9
+ // value: 41.3
+ // >
+ // quantile: <
+ // quantile: 0.99
+ // value: 41.9
+ // >
// >
// >
- // ]
}
-func ExampleConstSummary() {
+func ExampleNewConstSummary() {
desc := prometheus.NewDesc(
"http_request_duration_seconds",
"A summary of the HTTP request durations.",
@@ -551,7 +567,7 @@ func ExampleHistogram() {
// >
}
-func ExampleConstHistogram() {
+func ExampleNewConstHistogram() {
desc := prometheus.NewDesc(
"http_request_duration_seconds",
"A histogram of the HTTP request durations.",
@@ -609,18 +625,127 @@ func ExampleConstHistogram() {
// >
}
-func ExamplePushCollectors() {
- hostname, _ := os.Hostname()
- completionTime := prometheus.NewGauge(prometheus.GaugeOpts{
- Name: "db_backup_last_completion_time",
- Help: "The timestamp of the last succesful completion of a DB backup.",
+func ExampleAlreadyRegisteredError() {
+ reqCounter := prometheus.NewCounter(prometheus.CounterOpts{
+ Name: "requests_total",
+ Help: "The total number of requests served.",
})
- completionTime.Set(float64(time.Now().Unix()))
- if err := prometheus.PushCollectors(
- "db_backup", hostname,
- "http://pushgateway:9091",
- completionTime,
- ); err != nil {
- fmt.Println("Could not push completion time to Pushgateway:", err)
+ if err := prometheus.Register(reqCounter); err != nil {
+ if are, ok := err.(prometheus.AlreadyRegisteredError); ok {
+ // A counter for that metric has been registered before.
+ // Use the old counter from now on.
+ reqCounter = are.ExistingCollector.(prometheus.Counter)
+ } else {
+ // Something else went wrong!
+ panic(err)
+ }
}
}
+
+func ExampleGatherers() {
+ reg := prometheus.NewRegistry()
+ temp := prometheus.NewGaugeVec(
+ prometheus.GaugeOpts{
+ Name: "temperature_kelvin",
+ Help: "Temperature in Kelvin.",
+ },
+ []string{"location"},
+ )
+ reg.MustRegister(temp)
+ temp.WithLabelValues("outside").Set(273.14)
+ temp.WithLabelValues("inside").Set(298.44)
+
+ var parser expfmt.TextParser
+
+ text := `
+# TYPE humidity_percent gauge
+# HELP humidity_percent Humidity in %.
+humidity_percent{location="outside"} 45.4
+humidity_percent{location="inside"} 33.2
+# TYPE temperature_kelvin gauge
+# HELP temperature_kelvin Temperature in Kelvin.
+temperature_kelvin{location="somewhere else"} 4.5
+`
+
+ parseText := func() ([]*dto.MetricFamily, error) {
+ parsed, err := parser.TextToMetricFamilies(strings.NewReader(text))
+ if err != nil {
+ return nil, err
+ }
+ var result []*dto.MetricFamily
+ for _, mf := range parsed {
+ result = append(result, mf)
+ }
+ return result, nil
+ }
+
+ gatherers := prometheus.Gatherers{
+ reg,
+ prometheus.GathererFunc(parseText),
+ }
+
+ gathering, err := gatherers.Gather()
+ if err != nil {
+ fmt.Println(err)
+ }
+
+ out := &bytes.Buffer{}
+ for _, mf := range gathering {
+ if _, err := expfmt.MetricFamilyToText(out, mf); err != nil {
+ panic(err)
+ }
+ }
+ fmt.Print(out.String())
+ fmt.Println("----------")
+
+ // Note how the temperature_kelvin metric family has been merged from
+ // different sources. Now try
+ text = `
+# TYPE humidity_percent gauge
+# HELP humidity_percent Humidity in %.
+humidity_percent{location="outside"} 45.4
+humidity_percent{location="inside"} 33.2
+# TYPE temperature_kelvin gauge
+# HELP temperature_kelvin Temperature in Kelvin.
+# Duplicate metric:
+temperature_kelvin{location="outside"} 265.3
+ # Wrong labels:
+temperature_kelvin 4.5
+`
+
+ gathering, err = gatherers.Gather()
+ if err != nil {
+ fmt.Println(err)
+ }
+ // Note that still as many metrics as possible are returned:
+ out.Reset()
+ for _, mf := range gathering {
+ if _, err := expfmt.MetricFamilyToText(out, mf); err != nil {
+ panic(err)
+ }
+ }
+ fmt.Print(out.String())
+
+ // Output:
+ // # HELP humidity_percent Humidity in %.
+ // # TYPE humidity_percent gauge
+ // humidity_percent{location="inside"} 33.2
+ // humidity_percent{location="outside"} 45.4
+ // # HELP temperature_kelvin Temperature in Kelvin.
+ // # TYPE temperature_kelvin gauge
+ // temperature_kelvin{location="inside"} 298.44
+ // temperature_kelvin{location="outside"} 273.14
+ // temperature_kelvin{location="somewhere else"} 4.5
+ // ----------
+ // 2 error(s) occurred:
+ // * collected metric temperature_kelvin label: gauge: was collected before with the same name and label values
+ // * collected metric temperature_kelvin gauge: has label dimensions inconsistent with previously collected metrics in the same metric family
+ // # HELP humidity_percent Humidity in %.
+ // # TYPE humidity_percent gauge
+ // humidity_percent{location="inside"} 33.2
+ // humidity_percent{location="outside"} 45.4
+ // # HELP temperature_kelvin Temperature in Kelvin.
+ // # TYPE temperature_kelvin gauge
+ // temperature_kelvin{location="inside"} 298.44
+ // temperature_kelvin{location="outside"} 273.14
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/expvar.go b/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go
similarity index 81%
rename from vendor/github.com/prometheus/client_golang/prometheus/expvar.go
rename to vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go
index 0f7630d..18a99d5 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/expvar.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go
@@ -18,21 +18,21 @@ import (
"expvar"
)
-// ExpvarCollector collects metrics from the expvar interface. It provides a
-// quick way to expose numeric values that are already exported via expvar as
-// Prometheus metrics. Note that the data models of expvar and Prometheus are
-// fundamentally different, and that the ExpvarCollector is inherently
-// slow. Thus, the ExpvarCollector is probably great for experiments and
-// prototying, but you should seriously consider a more direct implementation of
-// Prometheus metrics for monitoring production systems.
-//
-// Use NewExpvarCollector to create new instances.
-type ExpvarCollector struct {
+type expvarCollector struct {
exports map[string]*Desc
}
-// NewExpvarCollector returns a newly allocated ExpvarCollector that still has
-// to be registered with the Prometheus registry.
+// NewExpvarCollector returns a newly allocated expvar Collector that still has
+// to be registered with a Prometheus registry.
+//
+// An expvar Collector collects metrics from the expvar interface. It provides a
+// quick way to expose numeric values that are already exported via expvar as
+// Prometheus metrics. Note that the data models of expvar and Prometheus are
+// fundamentally different, and that the expvar Collector is inherently slower
+// than native Prometheus metrics. Thus, the expvar Collector is probably great
+// for experiments and prototying, but you should seriously consider a more
+// direct implementation of Prometheus metrics for monitoring production
+// systems.
//
// The exports map has the following meaning:
//
@@ -59,21 +59,21 @@ type ExpvarCollector struct {
// sample values.
//
// Anything that does not fit into the scheme above is silently ignored.
-func NewExpvarCollector(exports map[string]*Desc) *ExpvarCollector {
- return &ExpvarCollector{
+func NewExpvarCollector(exports map[string]*Desc) Collector {
+ return &expvarCollector{
exports: exports,
}
}
// Describe implements Collector.
-func (e *ExpvarCollector) Describe(ch chan<- *Desc) {
+func (e *expvarCollector) Describe(ch chan<- *Desc) {
for _, desc := range e.exports {
ch <- desc
}
}
// Collect implements Collector.
-func (e *ExpvarCollector) Collect(ch chan<- Metric) {
+func (e *expvarCollector) Collect(ch chan<- Metric) {
for name, desc := range e.exports {
var m Metric
expVar := expvar.Get(name)
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/expvar_test.go b/vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go
similarity index 100%
rename from vendor/github.com/prometheus/client_golang/prometheus/expvar_test.go
rename to vendor/github.com/prometheus/client_golang/prometheus/expvar_collector_test.go
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/fnv.go b/vendor/github.com/prometheus/client_golang/prometheus/fnv.go
new file mode 100644
index 0000000..e3b67df
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/fnv.go
@@ -0,0 +1,29 @@
+package prometheus
+
+// Inline and byte-free variant of hash/fnv's fnv64a.
+
+const (
+ offset64 = 14695981039346656037
+ prime64 = 1099511628211
+)
+
+// hashNew initializies a new fnv64a hash value.
+func hashNew() uint64 {
+ return offset64
+}
+
+// hashAdd adds a string to a fnv64a hash value, returning the updated hash.
+func hashAdd(h uint64, s string) uint64 {
+ for i := 0; i < len(s); i++ {
+ h ^= uint64(s[i])
+ h *= prime64
+ }
+ return h
+}
+
+// hashAddByte adds a byte to a fnv64a hash value, returning the updated hash.
+func hashAddByte(h uint64, b byte) uint64 {
+ h ^= uint64(b)
+ h *= prime64
+ return h
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go
index ba8a402..8b70e51 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/gauge.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/gauge.go
@@ -13,8 +13,6 @@
package prometheus
-import "hash/fnv"
-
// Gauge is a Metric that represents a single numerical value that can
// arbitrarily go up and down.
//
@@ -60,7 +58,7 @@ func NewGauge(opts GaugeOpts) Gauge {
// (e.g. number of operations queued, partitioned by user and operation
// type). Create instances with NewGaugeVec.
type GaugeVec struct {
- MetricVec
+ *MetricVec
}
// NewGaugeVec creates a new GaugeVec based on the provided GaugeOpts and
@@ -74,14 +72,9 @@ func NewGaugeVec(opts GaugeOpts, labelNames []string) *GaugeVec {
opts.ConstLabels,
)
return &GaugeVec{
- MetricVec: MetricVec{
- children: map[uint64]Metric{},
- desc: desc,
- hash: fnv.New64a(),
- newMetric: func(lvs ...string) Metric {
- return newValue(desc, GaugeValue, 0, lvs...)
- },
- },
+ MetricVec: newMetricVec(desc, func(lvs ...string) Metric {
+ return newValue(desc, GaugeValue, 0, lvs...)
+ }),
}
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go
index 85fa20b..abc9d4e 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/go_collector.go
@@ -1,6 +1,7 @@
package prometheus
import (
+ "fmt"
"runtime"
"runtime/debug"
"time"
@@ -9,27 +10,226 @@ import (
type goCollector struct {
goroutines Gauge
gcDesc *Desc
+
+ // metrics to describe and collect
+ metrics memStatsMetrics
}
// NewGoCollector returns a collector which exports metrics about the current
// go process.
-func NewGoCollector() *goCollector {
+func NewGoCollector() Collector {
return &goCollector{
goroutines: NewGauge(GaugeOpts{
- Name: "go_goroutines",
- Help: "Number of goroutines that currently exist.",
+ Namespace: "go",
+ Name: "goroutines",
+ Help: "Number of goroutines that currently exist.",
}),
gcDesc: NewDesc(
"go_gc_duration_seconds",
"A summary of the GC invocation durations.",
nil, nil),
+ metrics: memStatsMetrics{
+ {
+ desc: NewDesc(
+ memstatNamespace("alloc_bytes"),
+ "Number of bytes allocated and still in use.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.Alloc) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("alloc_bytes_total"),
+ "Total number of bytes allocated, even if freed.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.TotalAlloc) },
+ valType: CounterValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("sys_bytes"),
+ "Number of bytes obtained by system. Sum of all system allocations.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.Sys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("lookups_total"),
+ "Total number of pointer lookups.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.Lookups) },
+ valType: CounterValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("mallocs_total"),
+ "Total number of mallocs.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.Mallocs) },
+ valType: CounterValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("frees_total"),
+ "Total number of frees.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.Frees) },
+ valType: CounterValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("heap_alloc_bytes"),
+ "Number of heap bytes allocated and still in use.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapAlloc) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("heap_sys_bytes"),
+ "Number of heap bytes obtained from system.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("heap_idle_bytes"),
+ "Number of heap bytes waiting to be used.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapIdle) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("heap_inuse_bytes"),
+ "Number of heap bytes that are in use.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapInuse) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("heap_released_bytes_total"),
+ "Total number of heap bytes released to OS.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapReleased) },
+ valType: CounterValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("heap_objects"),
+ "Number of allocated objects.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.HeapObjects) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("stack_inuse_bytes"),
+ "Number of bytes in use by the stack allocator.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.StackInuse) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("stack_sys_bytes"),
+ "Number of bytes obtained from system for stack allocator.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.StackSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("mspan_inuse_bytes"),
+ "Number of bytes in use by mspan structures.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.MSpanInuse) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("mspan_sys_bytes"),
+ "Number of bytes used for mspan structures obtained from system.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.MSpanSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("mcache_inuse_bytes"),
+ "Number of bytes in use by mcache structures.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.MCacheInuse) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("mcache_sys_bytes"),
+ "Number of bytes used for mcache structures obtained from system.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.MCacheSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("buck_hash_sys_bytes"),
+ "Number of bytes used by the profiling bucket hash table.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.BuckHashSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("gc_sys_bytes"),
+ "Number of bytes used for garbage collection system metadata.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.GCSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("other_sys_bytes"),
+ "Number of bytes used for other system allocations.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.OtherSys) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("next_gc_bytes"),
+ "Number of heap bytes when next garbage collection will take place.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.NextGC) },
+ valType: GaugeValue,
+ }, {
+ desc: NewDesc(
+ memstatNamespace("last_gc_time_seconds"),
+ "Number of seconds since 1970 of last garbage collection.",
+ nil, nil,
+ ),
+ eval: func(ms *runtime.MemStats) float64 { return float64(ms.LastGC) / 1e9 },
+ valType: GaugeValue,
+ },
+ },
}
}
+func memstatNamespace(s string) string {
+ return fmt.Sprintf("go_memstats_%s", s)
+}
+
// Describe returns all descriptions of the collector.
func (c *goCollector) Describe(ch chan<- *Desc) {
ch <- c.goroutines.Desc()
ch <- c.gcDesc
+
+ for _, i := range c.metrics {
+ ch <- i.desc
+ }
}
// Collect returns the current state of all metrics of the collector.
@@ -47,4 +247,17 @@ func (c *goCollector) Collect(ch chan<- Metric) {
}
quantiles[0.0] = stats.PauseQuantiles[0].Seconds()
ch <- MustNewConstSummary(c.gcDesc, uint64(stats.NumGC), float64(stats.PauseTotal.Seconds()), quantiles)
+
+ ms := &runtime.MemStats{}
+ runtime.ReadMemStats(ms)
+ for _, i := range c.metrics {
+ ch <- MustNewConstMetric(i.desc, i.valType, i.eval(ms))
+ }
+}
+
+// memStatsMetrics provide description, value, and value type for memstat metrics.
+type memStatsMetrics []struct {
+ desc *Desc
+ eval func(*runtime.MemStats) float64
+ valType ValueType
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go
index b75d28e..9a8858c 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/go_collector_test.go
@@ -50,6 +50,10 @@ func TestGoCollector(t *testing.T) {
t.Errorf("want 1 new goroutine, got %d", diff)
}
+ // GoCollector performs two sends per call.
+ // On line 27 we need to receive the second send
+ // to shut down cleanly.
+ <-ch
return
}
case <-time.After(1 * time.Second):
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go
index a94bbaf..9719e8f 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/histogram.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/histogram.go
@@ -15,14 +15,12 @@ package prometheus
import (
"fmt"
- "hash/fnv"
"math"
"sort"
"sync/atomic"
"github.com/golang/protobuf/proto"
- "github.com/prometheus/client_golang/model"
dto "github.com/prometheus/client_model/go"
)
@@ -49,15 +47,19 @@ type Histogram interface {
Observe(float64)
}
+// bucketLabel is used for the label that defines the upper bound of a
+// bucket of a histogram ("le" -> "less or equal").
+const bucketLabel = "le"
+
+// DefBuckets are the default Histogram buckets. The default buckets are
+// tailored to broadly measure the response time (in seconds) of a network
+// service. Most likely, however, you will be required to define buckets
+// customized to your use case.
var (
- // DefBuckets are the default Histogram buckets. The default buckets are
- // tailored to broadly measure the response time (in seconds) of a
- // network service. Most likely, however, you will be required to define
- // buckets customized to your use case.
DefBuckets = []float64{.005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10}
errBucketLabelNotAllowed = fmt.Errorf(
- "%q is not allowed as label name in histograms", model.BucketLabel,
+ "%q is not allowed as label name in histograms", bucketLabel,
)
)
@@ -171,12 +173,12 @@ func newHistogram(desc *Desc, opts HistogramOpts, labelValues ...string) Histogr
}
for _, n := range desc.variableLabels {
- if n == model.BucketLabel {
+ if n == bucketLabel {
panic(errBucketLabelNotAllowed)
}
}
for _, lp := range desc.constLabelPairs {
- if lp.GetName() == model.BucketLabel {
+ if lp.GetName() == bucketLabel {
panic(errBucketLabelNotAllowed)
}
}
@@ -208,7 +210,7 @@ func newHistogram(desc *Desc, opts HistogramOpts, labelValues ...string) Histogr
// Finally we know the final length of h.upperBounds and can make counts.
h.counts = make([]uint64, len(h.upperBounds))
- h.Init(h) // Init self-collection.
+ h.init(h) // Init self-collection.
return h
}
@@ -220,7 +222,7 @@ type histogram struct {
sumBits uint64
count uint64
- SelfCollector
+ selfCollector
// Note that there is no mutex required.
desc *Desc
@@ -285,7 +287,7 @@ func (h *histogram) Write(out *dto.Metric) error {
// (e.g. HTTP request latencies, partitioned by status code and method). Create
// instances with NewHistogramVec.
type HistogramVec struct {
- MetricVec
+ *MetricVec
}
// NewHistogramVec creates a new HistogramVec based on the provided HistogramOpts and
@@ -299,14 +301,9 @@ func NewHistogramVec(opts HistogramOpts, labelNames []string) *HistogramVec {
opts.ConstLabels,
)
return &HistogramVec{
- MetricVec: MetricVec{
- children: map[uint64]Metric{},
- desc: desc,
- hash: fnv.New64a(),
- newMetric: func(lvs ...string) Metric {
- return newHistogram(desc, opts, lvs...)
- },
- },
+ MetricVec: newMetricVec(desc, func(lvs ...string) Metric {
+ return newHistogram(desc, opts, lvs...)
+ }),
}
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go b/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go
index 855af46..d1242e0 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/histogram_test.go
@@ -124,6 +124,10 @@ func BenchmarkHistogramWrite8(b *testing.B) {
var testBuckets = []float64{-2, -1, -0.5, 0, 0.5, 1, 2, math.Inf(+1)}
func TestHistogramConcurrency(t *testing.T) {
+ if testing.Short() {
+ t.Skip("Skipping test in short mode.")
+ }
+
rand.Seed(42)
it := func(n uint32) bool {
@@ -198,6 +202,10 @@ func TestHistogramConcurrency(t *testing.T) {
}
func TestHistogramVecConcurrency(t *testing.T) {
+ if testing.Short() {
+ t.Skip("Skipping test in short mode.")
+ }
+
rand.Seed(42)
objectives := make([]float64, 0, len(DefObjectives))
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/http.go b/vendor/github.com/prometheus/client_golang/prometheus/http.go
index eabe602..67ee5ac 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/http.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/http.go
@@ -15,14 +15,114 @@ package prometheus
import (
"bufio"
+ "bytes"
+ "compress/gzip"
+ "fmt"
"io"
"net"
"net/http"
"strconv"
"strings"
+ "sync"
"time"
+
+ "github.com/prometheus/common/expfmt"
)
+// TODO(beorn7): Remove this whole file. It is a partial mirror of
+// promhttp/http.go (to avoid circular import chains) where everything HTTP
+// related should live. The functions here are just for avoiding
+// breakage. Everything is deprecated.
+
+const (
+ contentTypeHeader = "Content-Type"
+ contentLengthHeader = "Content-Length"
+ contentEncodingHeader = "Content-Encoding"
+ acceptEncodingHeader = "Accept-Encoding"
+)
+
+var bufPool sync.Pool
+
+func getBuf() *bytes.Buffer {
+ buf := bufPool.Get()
+ if buf == nil {
+ return &bytes.Buffer{}
+ }
+ return buf.(*bytes.Buffer)
+}
+
+func giveBuf(buf *bytes.Buffer) {
+ buf.Reset()
+ bufPool.Put(buf)
+}
+
+// Handler returns an HTTP handler for the DefaultGatherer. It is
+// already instrumented with InstrumentHandler (using "prometheus" as handler
+// name).
+//
+// Deprecated: Please note the issues described in the doc comment of
+// InstrumentHandler. You might want to consider using promhttp.Handler instead
+// (which is non instrumented).
+func Handler() http.Handler {
+ return InstrumentHandler("prometheus", UninstrumentedHandler())
+}
+
+// UninstrumentedHandler returns an HTTP handler for the DefaultGatherer.
+//
+// Deprecated: Use promhttp.Handler instead. See there for further documentation.
+func UninstrumentedHandler() http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ mfs, err := DefaultGatherer.Gather()
+ if err != nil {
+ http.Error(w, "An error has occurred during metrics collection:\n\n"+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ contentType := expfmt.Negotiate(req.Header)
+ buf := getBuf()
+ defer giveBuf(buf)
+ writer, encoding := decorateWriter(req, buf)
+ enc := expfmt.NewEncoder(writer, contentType)
+ var lastErr error
+ for _, mf := range mfs {
+ if err := enc.Encode(mf); err != nil {
+ lastErr = err
+ http.Error(w, "An error has occurred during metrics encoding:\n\n"+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ }
+ if closer, ok := writer.(io.Closer); ok {
+ closer.Close()
+ }
+ if lastErr != nil && buf.Len() == 0 {
+ http.Error(w, "No metrics encoded, last error:\n\n"+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ header := w.Header()
+ header.Set(contentTypeHeader, string(contentType))
+ header.Set(contentLengthHeader, fmt.Sprint(buf.Len()))
+ if encoding != "" {
+ header.Set(contentEncodingHeader, encoding)
+ }
+ w.Write(buf.Bytes())
+ })
+}
+
+// decorateWriter wraps a writer to handle gzip compression if requested. It
+// returns the decorated writer and the appropriate "Content-Encoding" header
+// (which is empty if no compression is enabled).
+func decorateWriter(request *http.Request, writer io.Writer) (io.Writer, string) {
+ header := request.Header.Get(acceptEncodingHeader)
+ parts := strings.Split(header, ",")
+ for _, part := range parts {
+ part := strings.TrimSpace(part)
+ if part == "gzip" || strings.HasPrefix(part, "gzip;") {
+ return gzip.NewWriter(writer), "gzip"
+ }
+ }
+ return writer, ""
+}
+
var instLabels = []string{"method", "code"}
type nower interface {
@@ -57,12 +157,34 @@ func nowSeries(t ...time.Time) nower {
// has a constant label named "handler" with the provided handlerName as
// value. http_requests_total is a metric vector partitioned by HTTP method
// (label name "method") and HTTP status code (label name "code").
+//
+// Deprecated: InstrumentHandler has several issues:
+//
+// - It uses Summaries rather than Histograms. Summaries are not useful if
+// aggregation across multiple instances is required.
+//
+// - It uses microseconds as unit, which is deprecated and should be replaced by
+// seconds.
+//
+// - The size of the request is calculated in a separate goroutine. Since this
+// calculator requires access to the request header, it creates a race with
+// any writes to the header performed during request handling.
+// httputil.ReverseProxy is a prominent example for a handler
+// performing such writes.
+//
+// Upcoming versions of this package will provide ways of instrumenting HTTP
+// handlers that are more flexible and have fewer issues. Please prefer direct
+// instrumentation in the meantime.
func InstrumentHandler(handlerName string, handler http.Handler) http.HandlerFunc {
return InstrumentHandlerFunc(handlerName, handler.ServeHTTP)
}
// InstrumentHandlerFunc wraps the given function for instrumentation. It
-// otherwise works in the same way as InstrumentHandler.
+// otherwise works in the same way as InstrumentHandler (and shares the same
+// issues).
+//
+// Deprecated: InstrumentHandlerFunc is deprecated for the same reasons as
+// InstrumentHandler is.
func InstrumentHandlerFunc(handlerName string, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
return InstrumentHandlerFuncWithOpts(
SummaryOpts{
@@ -73,13 +195,13 @@ func InstrumentHandlerFunc(handlerName string, handlerFunc func(http.ResponseWri
)
}
-// InstrumentHandlerWithOpts works like InstrumentHandler but provides more
-// flexibility (at the cost of a more complex call syntax). As
-// InstrumentHandler, this function registers four metric collectors, but it
-// uses the provided SummaryOpts to create them. However, the fields "Name" and
-// "Help" in the SummaryOpts are ignored. "Name" is replaced by
-// "requests_total", "request_duration_microseconds", "request_size_bytes", and
-// "response_size_bytes", respectively. "Help" is replaced by an appropriate
+// InstrumentHandlerWithOpts works like InstrumentHandler (and shares the same
+// issues) but provides more flexibility (at the cost of a more complex call
+// syntax). As InstrumentHandler, this function registers four metric
+// collectors, but it uses the provided SummaryOpts to create them. However, the
+// fields "Name" and "Help" in the SummaryOpts are ignored. "Name" is replaced
+// by "requests_total", "request_duration_microseconds", "request_size_bytes",
+// and "response_size_bytes", respectively. "Help" is replaced by an appropriate
// help string. The names of the variable labels of the http_requests_total
// CounterVec are "method" (get, post, etc.), and "code" (HTTP status code).
//
@@ -98,13 +220,20 @@ func InstrumentHandlerFunc(handlerName string, handlerFunc func(http.ResponseWri
// cannot use SummaryOpts. Instead, a CounterOpts struct is created internally,
// and all its fields are set to the equally named fields in the provided
// SummaryOpts.
+//
+// Deprecated: InstrumentHandlerWithOpts is deprecated for the same reasons as
+// InstrumentHandler is.
func InstrumentHandlerWithOpts(opts SummaryOpts, handler http.Handler) http.HandlerFunc {
return InstrumentHandlerFuncWithOpts(opts, handler.ServeHTTP)
}
-// InstrumentHandlerFuncWithOpts works like InstrumentHandlerFunc but provides
-// more flexibility (at the cost of a more complex call syntax). See
-// InstrumentHandlerWithOpts for details how the provided SummaryOpts are used.
+// InstrumentHandlerFuncWithOpts works like InstrumentHandlerFunc (and shares
+// the same issues) but provides more flexibility (at the cost of a more complex
+// call syntax). See InstrumentHandlerWithOpts for details how the provided
+// SummaryOpts are used.
+//
+// Deprecated: InstrumentHandlerFuncWithOpts is deprecated for the same reasons
+// as InstrumentHandler is.
func InstrumentHandlerFuncWithOpts(opts SummaryOpts, handlerFunc func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
reqCnt := NewCounterVec(
CounterOpts{
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/metric.go b/vendor/github.com/prometheus/client_golang/prometheus/metric.go
index d8905de..d4063d9 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/metric.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/metric.go
@@ -19,11 +19,11 @@ import (
dto "github.com/prometheus/client_model/go"
)
+const separatorByte byte = 255
+
// A Metric models a single sample value with its meta data being exported to
-// Prometheus. Implementers of Metric in this package inclued Gauge, Counter,
-// Untyped, and Summary. Users can implement their own Metric types, but that
-// should be rarely needed. See the example for SelfCollector, which is also an
-// example for a user-implemented Metric.
+// Prometheus. Implementations of Metric in this package are Gauge, Counter,
+// Histogram, Summary, and Untyped.
type Metric interface {
// Desc returns the descriptor for the Metric. This method idempotently
// returns the same descriptor throughout the lifetime of the
@@ -34,21 +34,23 @@ type Metric interface {
// Write encodes the Metric into a "Metric" Protocol Buffer data
// transmission object.
//
- // Implementers of custom Metric types must observe concurrency safety
- // as reads of this metric may occur at any time, and any blocking
- // occurs at the expense of total performance of rendering all
- // registered metrics. Ideally Metric implementations should support
- // concurrent readers.
+ // Metric implementations must observe concurrency safety as reads of
+ // this metric may occur at any time, and any blocking occurs at the
+ // expense of total performance of rendering all registered
+ // metrics. Ideally, Metric implementations should support concurrent
+ // readers.
//
- // The Prometheus client library attempts to minimize memory allocations
- // and will provide a pre-existing reset dto.Metric pointer. Prometheus
- // may recycle the dto.Metric proto message, so Metric implementations
- // should just populate the provided dto.Metric and then should not keep
- // any reference to it.
- //
- // While populating dto.Metric, labels must be sorted lexicographically.
- // (Implementers may find LabelPairSorter useful for that.)
+ // While populating dto.Metric, it is the responsibility of the
+ // implementation to ensure validity of the Metric protobuf (like valid
+ // UTF-8 strings or syntactically valid metric and label names). It is
+ // recommended to sort labels lexicographically. (Implementers may find
+ // LabelPairSorter useful for that.) Callers of Write should still make
+ // sure of sorting if they depend on it.
Write(*dto.Metric) error
+ // TODO(beorn7): The original rationale of passing in a pre-allocated
+ // dto.Metric protobuf to save allocations has disappeared. The
+ // signature of this method should be changed to "Write() (*dto.Metric,
+ // error)".
}
// Opts bundles the options for creating most Metric types. Each metric
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go
index d8cf0ed..e31e62e 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector.go
@@ -28,7 +28,7 @@ type processCollector struct {
// NewProcessCollector returns a collector which exports the current state of
// process metrics including cpu, memory and file descriptor usage as well as
// the process start time for the given process id under the given namespace.
-func NewProcessCollector(pid int, namespace string) *processCollector {
+func NewProcessCollector(pid int, namespace string) Collector {
return NewProcessCollectorPIDFn(
func() (int, error) { return pid, nil },
namespace,
@@ -43,7 +43,7 @@ func NewProcessCollector(pid int, namespace string) *processCollector {
func NewProcessCollectorPIDFn(
pidFn func() (int, error),
namespace string,
-) *processCollector {
+) Collector {
c := processCollector{
pidFn: pidFn,
collectFn: func(chan<- Metric) {},
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go
index 829715a..d3362da 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/process_collector_test.go
@@ -1,13 +1,12 @@
package prometheus
import (
- "io/ioutil"
- "net/http"
- "net/http/httptest"
+ "bytes"
"os"
"regexp"
"testing"
+ "github.com/prometheus/common/expfmt"
"github.com/prometheus/procfs"
)
@@ -16,39 +15,44 @@ func TestProcessCollector(t *testing.T) {
t.Skipf("skipping TestProcessCollector, procfs not available: %s", err)
}
- registry := newRegistry()
- registry.Register(NewProcessCollector(os.Getpid(), ""))
- registry.Register(NewProcessCollectorPIDFn(
- func() (int, error) { return os.Getpid(), nil }, "foobar"))
+ registry := NewRegistry()
+ if err := registry.Register(NewProcessCollector(os.Getpid(), "")); err != nil {
+ t.Fatal(err)
+ }
+ if err := registry.Register(NewProcessCollectorPIDFn(
+ func() (int, error) { return os.Getpid(), nil }, "foobar"),
+ ); err != nil {
+ t.Fatal(err)
+ }
- s := httptest.NewServer(InstrumentHandler("prometheus", registry))
- defer s.Close()
- r, err := http.Get(s.URL)
+ mfs, err := registry.Gather()
if err != nil {
t.Fatal(err)
}
- defer r.Body.Close()
- body, err := ioutil.ReadAll(r.Body)
- if err != nil {
- t.Fatal(err)
+
+ var buf bytes.Buffer
+ for _, mf := range mfs {
+ if _, err := expfmt.MetricFamilyToText(&buf, mf); err != nil {
+ t.Fatal(err)
+ }
}
for _, re := range []*regexp.Regexp{
regexp.MustCompile("process_cpu_seconds_total [0-9]"),
- regexp.MustCompile("process_max_fds [0-9]{2,}"),
+ regexp.MustCompile("process_max_fds [1-9]"),
regexp.MustCompile("process_open_fds [1-9]"),
regexp.MustCompile("process_virtual_memory_bytes [1-9]"),
regexp.MustCompile("process_resident_memory_bytes [1-9]"),
regexp.MustCompile("process_start_time_seconds [0-9.]{10,}"),
regexp.MustCompile("foobar_process_cpu_seconds_total [0-9]"),
- regexp.MustCompile("foobar_process_max_fds [0-9]{2,}"),
+ regexp.MustCompile("foobar_process_max_fds [1-9]"),
regexp.MustCompile("foobar_process_open_fds [1-9]"),
regexp.MustCompile("foobar_process_virtual_memory_bytes [1-9]"),
regexp.MustCompile("foobar_process_resident_memory_bytes [1-9]"),
regexp.MustCompile("foobar_process_start_time_seconds [0-9.]{10,}"),
} {
- if !re.Match(body) {
- t.Errorf("want body to match %s\n%s", re, body)
+ if !re.Match(buf.Bytes()) {
+ t.Errorf("want body to match %s\n%s", re, buf.String())
}
}
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go
new file mode 100644
index 0000000..b6dd5a2
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http.go
@@ -0,0 +1,201 @@
+// Copyright 2016 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Copyright (c) 2013, The Prometheus 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 promhttp contains functions to create http.Handler instances to
+// expose Prometheus metrics via HTTP. In later versions of this package, it
+// will also contain tooling to instrument instances of http.Handler and
+// http.RoundTripper.
+//
+// promhttp.Handler acts on the prometheus.DefaultGatherer. With HandlerFor,
+// you can create a handler for a custom registry or anything that implements
+// the Gatherer interface. It also allows to create handlers that act
+// differently on errors or allow to log errors.
+package promhttp
+
+import (
+ "bytes"
+ "compress/gzip"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "sync"
+
+ "github.com/prometheus/common/expfmt"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+const (
+ contentTypeHeader = "Content-Type"
+ contentLengthHeader = "Content-Length"
+ contentEncodingHeader = "Content-Encoding"
+ acceptEncodingHeader = "Accept-Encoding"
+)
+
+var bufPool sync.Pool
+
+func getBuf() *bytes.Buffer {
+ buf := bufPool.Get()
+ if buf == nil {
+ return &bytes.Buffer{}
+ }
+ return buf.(*bytes.Buffer)
+}
+
+func giveBuf(buf *bytes.Buffer) {
+ buf.Reset()
+ bufPool.Put(buf)
+}
+
+// Handler returns an HTTP handler for the prometheus.DefaultGatherer. The
+// Handler uses the default HandlerOpts, i.e. report the first error as an HTTP
+// error, no error logging, and compression if requested by the client.
+//
+// If you want to create a Handler for the DefaultGatherer with different
+// HandlerOpts, create it with HandlerFor with prometheus.DefaultGatherer and
+// your desired HandlerOpts.
+func Handler() http.Handler {
+ return HandlerFor(prometheus.DefaultGatherer, HandlerOpts{})
+}
+
+// HandlerFor returns an http.Handler for the provided Gatherer. The behavior
+// of the Handler is defined by the provided HandlerOpts.
+func HandlerFor(reg prometheus.Gatherer, opts HandlerOpts) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ mfs, err := reg.Gather()
+ if err != nil {
+ if opts.ErrorLog != nil {
+ opts.ErrorLog.Println("error gathering metrics:", err)
+ }
+ switch opts.ErrorHandling {
+ case PanicOnError:
+ panic(err)
+ case ContinueOnError:
+ if len(mfs) == 0 {
+ http.Error(w, "No metrics gathered, last error:\n\n"+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ case HTTPErrorOnError:
+ http.Error(w, "An error has occurred during metrics gathering:\n\n"+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ }
+
+ contentType := expfmt.Negotiate(req.Header)
+ buf := getBuf()
+ defer giveBuf(buf)
+ writer, encoding := decorateWriter(req, buf, opts.DisableCompression)
+ enc := expfmt.NewEncoder(writer, contentType)
+ var lastErr error
+ for _, mf := range mfs {
+ if err := enc.Encode(mf); err != nil {
+ lastErr = err
+ if opts.ErrorLog != nil {
+ opts.ErrorLog.Println("error encoding metric family:", err)
+ }
+ switch opts.ErrorHandling {
+ case PanicOnError:
+ panic(err)
+ case ContinueOnError:
+ // Handled later.
+ case HTTPErrorOnError:
+ http.Error(w, "An error has occurred during metrics encoding:\n\n"+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ }
+ }
+ if closer, ok := writer.(io.Closer); ok {
+ closer.Close()
+ }
+ if lastErr != nil && buf.Len() == 0 {
+ http.Error(w, "No metrics encoded, last error:\n\n"+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ header := w.Header()
+ header.Set(contentTypeHeader, string(contentType))
+ header.Set(contentLengthHeader, fmt.Sprint(buf.Len()))
+ if encoding != "" {
+ header.Set(contentEncodingHeader, encoding)
+ }
+ w.Write(buf.Bytes())
+ // TODO(beorn7): Consider streaming serving of metrics.
+ })
+}
+
+// HandlerErrorHandling defines how a Handler serving metrics will handle
+// errors.
+type HandlerErrorHandling int
+
+// These constants cause handlers serving metrics to behave as described if
+// errors are encountered.
+const (
+ // Serve an HTTP status code 500 upon the first error
+ // encountered. Report the error message in the body.
+ HTTPErrorOnError HandlerErrorHandling = iota
+ // Ignore errors and try to serve as many metrics as possible. However,
+ // if no metrics can be served, serve an HTTP status code 500 and the
+ // last error message in the body. Only use this in deliberate "best
+ // effort" metrics collection scenarios. It is recommended to at least
+ // log errors (by providing an ErrorLog in HandlerOpts) to not mask
+ // errors completely.
+ ContinueOnError
+ // Panic upon the first error encountered (useful for "crash only" apps).
+ PanicOnError
+)
+
+// Logger is the minimal interface HandlerOpts needs for logging. Note that
+// log.Logger from the standard library implements this interface, and it is
+// easy to implement by custom loggers, if they don't do so already anyway.
+type Logger interface {
+ Println(v ...interface{})
+}
+
+// HandlerOpts specifies options how to serve metrics via an http.Handler. The
+// zero value of HandlerOpts is a reasonable default.
+type HandlerOpts struct {
+ // ErrorLog specifies an optional logger for errors collecting and
+ // serving metrics. If nil, errors are not logged at all.
+ ErrorLog Logger
+ // ErrorHandling defines how errors are handled. Note that errors are
+ // logged regardless of the configured ErrorHandling provided ErrorLog
+ // is not nil.
+ ErrorHandling HandlerErrorHandling
+ // If DisableCompression is true, the handler will never compress the
+ // response, even if requested by the client.
+ DisableCompression bool
+}
+
+// decorateWriter wraps a writer to handle gzip compression if requested. It
+// returns the decorated writer and the appropriate "Content-Encoding" header
+// (which is empty if no compression is enabled).
+func decorateWriter(request *http.Request, writer io.Writer, compressionDisabled bool) (io.Writer, string) {
+ if compressionDisabled {
+ return writer, ""
+ }
+ header := request.Header.Get(acceptEncodingHeader)
+ parts := strings.Split(header, ",")
+ for _, part := range parts {
+ part := strings.TrimSpace(part)
+ if part == "gzip" || strings.HasPrefix(part, "gzip;") {
+ return gzip.NewWriter(writer), "gzip"
+ }
+ }
+ return writer, ""
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go
new file mode 100644
index 0000000..d4a7d4a
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/promhttp/http_test.go
@@ -0,0 +1,137 @@
+// Copyright 2016 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Copyright (c) 2013, The Prometheus 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 promhttp
+
+import (
+ "bytes"
+ "errors"
+ "log"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+type errorCollector struct{}
+
+func (e errorCollector) Describe(ch chan<- *prometheus.Desc) {
+ ch <- prometheus.NewDesc("invalid_metric", "not helpful", nil, nil)
+}
+
+func (e errorCollector) Collect(ch chan<- prometheus.Metric) {
+ ch <- prometheus.NewInvalidMetric(
+ prometheus.NewDesc("invalid_metric", "not helpful", nil, nil),
+ errors.New("collect error"),
+ )
+}
+
+func TestHandlerErrorHandling(t *testing.T) {
+
+ // Create a registry that collects a MetricFamily with two elements,
+ // another with one, and reports an error.
+ reg := prometheus.NewRegistry()
+
+ cnt := prometheus.NewCounter(prometheus.CounterOpts{
+ Name: "the_count",
+ Help: "Ah-ah-ah! Thunder and lightning!",
+ })
+ reg.MustRegister(cnt)
+
+ cntVec := prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "name",
+ Help: "docstring",
+ ConstLabels: prometheus.Labels{"constname": "constvalue"},
+ },
+ []string{"labelname"},
+ )
+ cntVec.WithLabelValues("val1").Inc()
+ cntVec.WithLabelValues("val2").Inc()
+ reg.MustRegister(cntVec)
+
+ reg.MustRegister(errorCollector{})
+
+ logBuf := &bytes.Buffer{}
+ logger := log.New(logBuf, "", 0)
+
+ writer := httptest.NewRecorder()
+ request, _ := http.NewRequest("GET", "/", nil)
+ request.Header.Add("Accept", "test/plain")
+
+ errorHandler := HandlerFor(reg, HandlerOpts{
+ ErrorLog: logger,
+ ErrorHandling: HTTPErrorOnError,
+ })
+ continueHandler := HandlerFor(reg, HandlerOpts{
+ ErrorLog: logger,
+ ErrorHandling: ContinueOnError,
+ })
+ panicHandler := HandlerFor(reg, HandlerOpts{
+ ErrorLog: logger,
+ ErrorHandling: PanicOnError,
+ })
+ wantMsg := `error gathering metrics: error collecting metric Desc{fqName: "invalid_metric", help: "not helpful", constLabels: {}, variableLabels: []}: collect error
+`
+ wantErrorBody := `An error has occurred during metrics gathering:
+
+error collecting metric Desc{fqName: "invalid_metric", help: "not helpful", constLabels: {}, variableLabels: []}: collect error
+`
+ wantOKBody := `# HELP name docstring
+# TYPE name counter
+name{constname="constvalue",labelname="val1"} 1
+name{constname="constvalue",labelname="val2"} 1
+# HELP the_count Ah-ah-ah! Thunder and lightning!
+# TYPE the_count counter
+the_count 0
+`
+
+ errorHandler.ServeHTTP(writer, request)
+ if got, want := writer.Code, http.StatusInternalServerError; got != want {
+ t.Errorf("got HTTP status code %d, want %d", got, want)
+ }
+ if got := logBuf.String(); got != wantMsg {
+ t.Errorf("got log message:\n%s\nwant log mesage:\n%s\n", got, wantMsg)
+ }
+ if got := writer.Body.String(); got != wantErrorBody {
+ t.Errorf("got body:\n%s\nwant body:\n%s\n", got, wantErrorBody)
+ }
+ logBuf.Reset()
+ writer.Body.Reset()
+ writer.Code = http.StatusOK
+
+ continueHandler.ServeHTTP(writer, request)
+ if got, want := writer.Code, http.StatusOK; got != want {
+ t.Errorf("got HTTP status code %d, want %d", got, want)
+ }
+ if got := logBuf.String(); got != wantMsg {
+ t.Errorf("got log message %q, want %q", got, wantMsg)
+ }
+ if got := writer.Body.String(); got != wantOKBody {
+ t.Errorf("got body %q, want %q", got, wantOKBody)
+ }
+
+ defer func() {
+ if err := recover(); err == nil {
+ t.Error("expected panic from panicHandler")
+ }
+ }()
+ panicHandler.ServeHTTP(writer, request)
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push.go b/vendor/github.com/prometheus/client_golang/prometheus/push.go
deleted file mode 100644
index 1c33848..0000000
--- a/vendor/github.com/prometheus/client_golang/prometheus/push.go
+++ /dev/null
@@ -1,65 +0,0 @@
-// Copyright 2015 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-// Copyright (c) 2013, The Prometheus 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 prometheus
-
-// Push triggers a metric collection by the default registry and pushes all
-// collected metrics to the Pushgateway specified by addr. See the Pushgateway
-// documentation for detailed implications of the job and instance
-// parameter. instance can be left empty. You can use just host:port or ip:port
-// as url, in which case 'http://' is added automatically. You can also include
-// the schema in the URL. However, do not include the '/metrics/jobs/...' part.
-//
-// Note that all previously pushed metrics with the same job and instance will
-// be replaced with the metrics pushed by this call. (It uses HTTP method 'PUT'
-// to push to the Pushgateway.)
-func Push(job, instance, url string) error {
- return defRegistry.Push(job, instance, url, "PUT")
-}
-
-// PushAdd works like Push, but only previously pushed metrics with the same
-// name (and the same job and instance) will be replaced. (It uses HTTP method
-// 'POST' to push to the Pushgateway.)
-func PushAdd(job, instance, url string) error {
- return defRegistry.Push(job, instance, url, "POST")
-}
-
-// PushCollectors works like Push, but it does not collect from the default
-// registry. Instead, it collects from the provided collectors. It is a
-// convenient way to push only a few metrics.
-func PushCollectors(job, instance, url string, collectors ...Collector) error {
- return pushCollectors(job, instance, url, "PUT", collectors...)
-}
-
-// PushAddCollectors works like PushAdd, but it does not collect from the
-// default registry. Instead, it collects from the provided collectors. It is a
-// convenient way to push only a few metrics.
-func PushAddCollectors(job, instance, url string, collectors ...Collector) error {
- return pushCollectors(job, instance, url, "POST", collectors...)
-}
-
-func pushCollectors(job, instance, url, method string, collectors ...Collector) error {
- r := newRegistry()
- for _, collector := range collectors {
- if _, err := r.Register(collector); err != nil {
- return err
- }
- }
- return r.Push(job, instance, url, method)
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go b/vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go
new file mode 100644
index 0000000..7f17ca2
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/push/examples_test.go
@@ -0,0 +1,56 @@
+// Copyright 2016 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package push_test
+
+import (
+ "fmt"
+ "time"
+
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/push"
+)
+
+func ExampleCollectors() {
+ completionTime := prometheus.NewGauge(prometheus.GaugeOpts{
+ Name: "db_backup_last_completion_timestamp_seconds",
+ Help: "The timestamp of the last succesful completion of a DB backup.",
+ })
+ completionTime.Set(float64(time.Now().Unix()))
+ if err := push.Collectors(
+ "db_backup", push.HostnameGroupingKey(),
+ "http://pushgateway:9091",
+ completionTime,
+ ); err != nil {
+ fmt.Println("Could not push completion time to Pushgateway:", err)
+ }
+}
+
+func ExampleRegistry() {
+ registry := prometheus.NewRegistry()
+
+ completionTime := prometheus.NewGauge(prometheus.GaugeOpts{
+ Name: "db_backup_last_completion_timestamp_seconds",
+ Help: "The timestamp of the last succesful completion of a DB backup.",
+ })
+ registry.MustRegister(completionTime)
+
+ completionTime.Set(float64(time.Now().Unix()))
+ if err := push.FromGatherer(
+ "db_backup", push.HostnameGroupingKey(),
+ "http://pushgateway:9091",
+ registry,
+ ); err != nil {
+ fmt.Println("Could not push completion time to Pushgateway:", err)
+ }
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/push.go b/vendor/github.com/prometheus/client_golang/prometheus/push/push.go
new file mode 100644
index 0000000..ae40402
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/push/push.go
@@ -0,0 +1,172 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Copyright (c) 2013, The Prometheus 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 push provides functions to push metrics to a Pushgateway. The metrics
+// to push are either collected from a provided registry, or from explicitly
+// listed collectors.
+//
+// See the documentation of the Pushgateway to understand the meaning of the
+// grouping parameters and the differences between push.Registry and
+// push.Collectors on the one hand and push.AddRegistry and push.AddCollectors
+// on the other hand: https://github.com/prometheus/pushgateway
+package push
+
+import (
+ "bytes"
+ "fmt"
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "os"
+ "strings"
+
+ "github.com/prometheus/common/expfmt"
+ "github.com/prometheus/common/model"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+const contentTypeHeader = "Content-Type"
+
+// FromGatherer triggers a metric collection by the provided Gatherer (which is
+// usually implemented by a prometheus.Registry) and pushes all gathered metrics
+// to the Pushgateway specified by url, using the provided job name and the
+// (optional) further grouping labels (the grouping map may be nil). See the
+// Pushgateway documentation for detailed implications of the job and other
+// grouping labels. Neither the job name nor any grouping label value may
+// contain a "/". The metrics pushed must not contain a job label of their own
+// nor any of the grouping labels.
+//
+// You can use just host:port or ip:port as url, in which case 'http://' is
+// added automatically. You can also include the schema in the URL. However, do
+// not include the '/metrics/jobs/...' part.
+//
+// Note that all previously pushed metrics with the same job and other grouping
+// labels will be replaced with the metrics pushed by this call. (It uses HTTP
+// method 'PUT' to push to the Pushgateway.)
+func FromGatherer(job string, grouping map[string]string, url string, g prometheus.Gatherer) error {
+ return push(job, grouping, url, g, "PUT")
+}
+
+// AddFromGatherer works like FromGatherer, but only previously pushed metrics
+// with the same name (and the same job and other grouping labels) will be
+// replaced. (It uses HTTP method 'POST' to push to the Pushgateway.)
+func AddFromGatherer(job string, grouping map[string]string, url string, g prometheus.Gatherer) error {
+ return push(job, grouping, url, g, "POST")
+}
+
+func push(job string, grouping map[string]string, pushURL string, g prometheus.Gatherer, method string) error {
+ if !strings.Contains(pushURL, "://") {
+ pushURL = "http://" + pushURL
+ }
+ if strings.HasSuffix(pushURL, "/") {
+ pushURL = pushURL[:len(pushURL)-1]
+ }
+
+ if strings.Contains(job, "/") {
+ return fmt.Errorf("job contains '/': %s", job)
+ }
+ urlComponents := []string{url.QueryEscape(job)}
+ for ln, lv := range grouping {
+ if !model.LabelNameRE.MatchString(ln) {
+ return fmt.Errorf("grouping label has invalid name: %s", ln)
+ }
+ if strings.Contains(lv, "/") {
+ return fmt.Errorf("value of grouping label %s contains '/': %s", ln, lv)
+ }
+ urlComponents = append(urlComponents, ln, lv)
+ }
+ pushURL = fmt.Sprintf("%s/metrics/job/%s", pushURL, strings.Join(urlComponents, "/"))
+
+ mfs, err := g.Gather()
+ if err != nil {
+ return err
+ }
+ buf := &bytes.Buffer{}
+ enc := expfmt.NewEncoder(buf, expfmt.FmtProtoDelim)
+ // Check for pre-existing grouping labels:
+ for _, mf := range mfs {
+ for _, m := range mf.GetMetric() {
+ for _, l := range m.GetLabel() {
+ if l.GetName() == "job" {
+ return fmt.Errorf("pushed metric %s (%s) already contains a job label", mf.GetName(), m)
+ }
+ if _, ok := grouping[l.GetName()]; ok {
+ return fmt.Errorf(
+ "pushed metric %s (%s) already contains grouping label %s",
+ mf.GetName(), m, l.GetName(),
+ )
+ }
+ }
+ }
+ enc.Encode(mf)
+ }
+ req, err := http.NewRequest(method, pushURL, buf)
+ if err != nil {
+ return err
+ }
+ req.Header.Set(contentTypeHeader, string(expfmt.FmtProtoDelim))
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != 202 {
+ body, _ := ioutil.ReadAll(resp.Body) // Ignore any further error as this is for an error message only.
+ return fmt.Errorf("unexpected status code %d while pushing to %s: %s", resp.StatusCode, pushURL, body)
+ }
+ return nil
+}
+
+// Collectors works like FromGatherer, but it does not use a Gatherer. Instead,
+// it collects from the provided collectors directly. It is a convenient way to
+// push only a few metrics.
+func Collectors(job string, grouping map[string]string, url string, collectors ...prometheus.Collector) error {
+ return pushCollectors(job, grouping, url, "PUT", collectors...)
+}
+
+// AddCollectors works like AddFromGatherer, but it does not use a Gatherer.
+// Instead, it collects from the provided collectors directly. It is a
+// convenient way to push only a few metrics.
+func AddCollectors(job string, grouping map[string]string, url string, collectors ...prometheus.Collector) error {
+ return pushCollectors(job, grouping, url, "POST", collectors...)
+}
+
+func pushCollectors(job string, grouping map[string]string, url, method string, collectors ...prometheus.Collector) error {
+ r := prometheus.NewRegistry()
+ for _, collector := range collectors {
+ if err := r.Register(collector); err != nil {
+ return err
+ }
+ }
+ return push(job, grouping, url, r, method)
+}
+
+// HostnameGroupingKey returns a label map with the only entry
+// {instance=""}. This can be conveniently used as the grouping
+// parameter if metrics should be pushed with the hostname as label. The
+// returned map is created upon each call so that the caller is free to add more
+// labels to the map.
+func HostnameGroupingKey() map[string]string {
+ hostname, err := os.Hostname()
+ if err != nil {
+ return map[string]string{"instance": "unknown"}
+ }
+ return map[string]string{"instance": hostname}
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/push/push_test.go b/vendor/github.com/prometheus/client_golang/prometheus/push/push_test.go
new file mode 100644
index 0000000..28ed9b7
--- /dev/null
+++ b/vendor/github.com/prometheus/client_golang/prometheus/push/push_test.go
@@ -0,0 +1,176 @@
+// Copyright 2016 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Copyright (c) 2013, The Prometheus 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 push
+
+import (
+ "bytes"
+ "io/ioutil"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "testing"
+
+ "github.com/prometheus/common/expfmt"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+func TestPush(t *testing.T) {
+
+ var (
+ lastMethod string
+ lastBody []byte
+ lastPath string
+ )
+
+ host, err := os.Hostname()
+ if err != nil {
+ t.Error(err)
+ }
+
+ // Fake a Pushgateway that always responds with 202.
+ pgwOK := httptest.NewServer(
+ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ lastMethod = r.Method
+ var err error
+ lastBody, err = ioutil.ReadAll(r.Body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ lastPath = r.URL.EscapedPath()
+ w.Header().Set("Content-Type", `text/plain; charset=utf-8`)
+ w.WriteHeader(http.StatusAccepted)
+ }),
+ )
+ defer pgwOK.Close()
+
+ // Fake a Pushgateway that always responds with 500.
+ pgwErr := httptest.NewServer(
+ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, "fake error", http.StatusInternalServerError)
+ }),
+ )
+ defer pgwErr.Close()
+
+ metric1 := prometheus.NewCounter(prometheus.CounterOpts{
+ Name: "testname1",
+ Help: "testhelp1",
+ })
+ metric2 := prometheus.NewGauge(prometheus.GaugeOpts{
+ Name: "testname2",
+ Help: "testhelp2",
+ ConstLabels: prometheus.Labels{"foo": "bar", "dings": "bums"},
+ })
+
+ reg := prometheus.NewRegistry()
+ reg.MustRegister(metric1)
+ reg.MustRegister(metric2)
+
+ mfs, err := reg.Gather()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ buf := &bytes.Buffer{}
+ enc := expfmt.NewEncoder(buf, expfmt.FmtProtoDelim)
+
+ for _, mf := range mfs {
+ if err := enc.Encode(mf); err != nil {
+ t.Fatal(err)
+ }
+ }
+ wantBody := buf.Bytes()
+
+ // PushCollectors, all good.
+ if err := Collectors("testjob", HostnameGroupingKey(), pgwOK.URL, metric1, metric2); err != nil {
+ t.Fatal(err)
+ }
+ if lastMethod != "PUT" {
+ t.Error("want method PUT for PushCollectors, got", lastMethod)
+ }
+ if bytes.Compare(lastBody, wantBody) != 0 {
+ t.Errorf("got body %v, want %v", lastBody, wantBody)
+ }
+ if lastPath != "/metrics/job/testjob/instance/"+host {
+ t.Error("unexpected path:", lastPath)
+ }
+
+ // PushAddCollectors, with nil grouping, all good.
+ if err := AddCollectors("testjob", nil, pgwOK.URL, metric1, metric2); err != nil {
+ t.Fatal(err)
+ }
+ if lastMethod != "POST" {
+ t.Error("want method POST for PushAddCollectors, got", lastMethod)
+ }
+ if bytes.Compare(lastBody, wantBody) != 0 {
+ t.Errorf("got body %v, want %v", lastBody, wantBody)
+ }
+ if lastPath != "/metrics/job/testjob" {
+ t.Error("unexpected path:", lastPath)
+ }
+
+ // PushCollectors with a broken PGW.
+ if err := Collectors("testjob", nil, pgwErr.URL, metric1, metric2); err == nil {
+ t.Error("push to broken Pushgateway succeeded")
+ } else {
+ if got, want := err.Error(), "unexpected status code 500 while pushing to "+pgwErr.URL+"/metrics/job/testjob: fake error\n"; got != want {
+ t.Errorf("got error %q, want %q", got, want)
+ }
+ }
+
+ // PushCollectors with invalid grouping or job.
+ if err := Collectors("testjob", map[string]string{"foo": "bums"}, pgwErr.URL, metric1, metric2); err == nil {
+ t.Error("push with grouping contained in metrics succeeded")
+ }
+ if err := Collectors("test/job", nil, pgwErr.URL, metric1, metric2); err == nil {
+ t.Error("push with invalid job value succeeded")
+ }
+ if err := Collectors("testjob", map[string]string{"foo/bar": "bums"}, pgwErr.URL, metric1, metric2); err == nil {
+ t.Error("push with invalid grouping succeeded")
+ }
+ if err := Collectors("testjob", map[string]string{"foo-bar": "bums"}, pgwErr.URL, metric1, metric2); err == nil {
+ t.Error("push with invalid grouping succeeded")
+ }
+
+ // Push registry, all good.
+ if err := FromGatherer("testjob", HostnameGroupingKey(), pgwOK.URL, reg); err != nil {
+ t.Fatal(err)
+ }
+ if lastMethod != "PUT" {
+ t.Error("want method PUT for Push, got", lastMethod)
+ }
+ if bytes.Compare(lastBody, wantBody) != 0 {
+ t.Errorf("got body %v, want %v", lastBody, wantBody)
+ }
+
+ // PushAdd registry, all good.
+ if err := AddFromGatherer("testjob", map[string]string{"a": "x", "b": "y"}, pgwOK.URL, reg); err != nil {
+ t.Fatal(err)
+ }
+ if lastMethod != "POST" {
+ t.Error("want method POSTT for PushAdd, got", lastMethod)
+ }
+ if bytes.Compare(lastBody, wantBody) != 0 {
+ t.Errorf("got body %v, want %v", lastBody, wantBody)
+ }
+ if lastPath != "/metrics/job/testjob/a/x/b/y" && lastPath != "/metrics/job/testjob/b/y/a/x" {
+ t.Error("unexpected path:", lastPath)
+ }
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry.go b/vendor/github.com/prometheus/client_golang/prometheus/registry.go
index 3223193..32a3986 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/registry.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/registry.go
@@ -11,223 +11,287 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-// Copyright (c) 2013, The Prometheus 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 prometheus
import (
"bytes"
- "compress/gzip"
"errors"
"fmt"
- "hash/fnv"
- "io"
- "net/http"
- "net/url"
"os"
"sort"
- "strings"
"sync"
- "bitbucket.org/ww/goautoneg"
"github.com/golang/protobuf/proto"
dto "github.com/prometheus/client_model/go"
-
- "github.com/prometheus/client_golang/model"
- "github.com/prometheus/client_golang/text"
)
-var (
- defRegistry = newDefaultRegistry()
- errAlreadyReg = errors.New("duplicate metrics collector registration attempted")
-)
-
-// Constants relevant to the HTTP interface.
const (
- // APIVersion is the version of the format of the exported data. This
- // will match this library's version, which subscribes to the Semantic
- // Versioning scheme.
- APIVersion = "0.0.4"
-
- // DelimitedTelemetryContentType is the content type set on telemetry
- // data responses in delimited protobuf format.
- DelimitedTelemetryContentType = `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited`
- // TextTelemetryContentType is the content type set on telemetry data
- // responses in text format.
- TextTelemetryContentType = `text/plain; version=` + APIVersion
- // ProtoTextTelemetryContentType is the content type set on telemetry
- // data responses in protobuf text format. (Only used for debugging.)
- ProtoTextTelemetryContentType = `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=text`
- // ProtoCompactTextTelemetryContentType is the content type set on
- // telemetry data responses in protobuf compact text format. (Only used
- // for debugging.)
- ProtoCompactTextTelemetryContentType = `application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=compact-text`
-
- // Constants for object pools.
- numBufs = 4
- numMetricFamilies = 1000
- numMetrics = 10000
-
// Capacity for the channel to collect metrics and descriptors.
capMetricChan = 1000
capDescChan = 10
-
- contentTypeHeader = "Content-Type"
- contentLengthHeader = "Content-Length"
- contentEncodingHeader = "Content-Encoding"
-
- acceptEncodingHeader = "Accept-Encoding"
- acceptHeader = "Accept"
)
-// Handler returns the HTTP handler for the global Prometheus registry. It is
-// already instrumented with InstrumentHandler (using "prometheus" as handler
-// name). Usually the handler is used to handle the "/metrics" endpoint.
-func Handler() http.Handler {
- return InstrumentHandler("prometheus", defRegistry)
+// DefaultRegisterer and DefaultGatherer are the implementations of the
+// Registerer and Gatherer interface a number of convenience functions in this
+// package act on. Initially, both variables point to the same Registry, which
+// has a process collector (see NewProcessCollector) and a Go collector (see
+// NewGoCollector) already registered. This approach to keep default instances
+// as global state mirrors the approach of other packages in the Go standard
+// library. Note that there are caveats. Change the variables with caution and
+// only if you understand the consequences. Users who want to avoid global state
+// altogether should not use the convenience function and act on custom
+// instances instead.
+var (
+ defaultRegistry = NewRegistry()
+ DefaultRegisterer Registerer = defaultRegistry
+ DefaultGatherer Gatherer = defaultRegistry
+)
+
+func init() {
+ MustRegister(NewProcessCollector(os.Getpid(), ""))
+ MustRegister(NewGoCollector())
}
-// UninstrumentedHandler works in the same way as Handler, but the returned HTTP
-// handler is not instrumented. This is useful if no instrumentation is desired
-// (for whatever reason) or if the instrumentation has to happen with a
-// different handler name (or with a different instrumentation approach
-// altogether). See the InstrumentHandler example.
-func UninstrumentedHandler() http.Handler {
- return defRegistry
-}
-
-// Register registers a new Collector to be included in metrics collection. It
-// returns an error if the descriptors provided by the Collector are invalid or
-// if they - in combination with descriptors of already registered Collectors -
-// do not fulfill the consistency and uniqueness criteria described in the Desc
-// documentation.
-//
-// Do not register the same Collector multiple times concurrently. (Registering
-// the same Collector twice would result in an error anyway, but on top of that,
-// it is not safe to do so concurrently.)
-func Register(m Collector) error {
- _, err := defRegistry.Register(m)
- return err
-}
-
-// MustRegister works like Register but panics where Register would have
-// returned an error.
-func MustRegister(m Collector) {
- err := Register(m)
- if err != nil {
- panic(err)
+// NewRegistry creates a new vanilla Registry without any Collectors
+// pre-registered.
+func NewRegistry() *Registry {
+ return &Registry{
+ collectorsByID: map[uint64]Collector{},
+ descIDs: map[uint64]struct{}{},
+ dimHashesByName: map[string]uint64{},
}
}
-// RegisterOrGet works like Register but does not return an error if a Collector
-// is registered that equals a previously registered Collector. (Two Collectors
-// are considered equal if their Describe method yields the same set of
-// descriptors.) Instead, the previously registered Collector is returned (which
-// is helpful if the new and previously registered Collectors are equal but not
-// identical, i.e. not pointers to the same object).
+// NewPedanticRegistry returns a registry that checks during collection if each
+// collected Metric is consistent with its reported Desc, and if the Desc has
+// actually been registered with the registry.
//
-// As for Register, it is still not safe to call RegisterOrGet with the same
-// Collector multiple times concurrently.
-func RegisterOrGet(m Collector) (Collector, error) {
- return defRegistry.RegisterOrGet(m)
+// Usually, a Registry will be happy as long as the union of all collected
+// Metrics is consistent and valid even if some metrics are not consistent with
+// their own Desc or a Desc provided by their registered Collector. Well-behaved
+// Collectors and Metrics will only provide consistent Descs. This Registry is
+// useful to test the implementation of Collectors and Metrics.
+func NewPedanticRegistry() *Registry {
+ r := NewRegistry()
+ r.pedanticChecksEnabled = true
+ return r
}
-// MustRegisterOrGet works like Register but panics where RegisterOrGet would
-// have returned an error.
-func MustRegisterOrGet(m Collector) Collector {
- existing, err := RegisterOrGet(m)
+// Registerer is the interface for the part of a registry in charge of
+// registering and unregistering. Users of custom registries should use
+// Registerer as type for registration purposes (rather then the Registry type
+// directly). In that way, they are free to use custom Registerer implementation
+// (e.g. for testing purposes).
+type Registerer interface {
+ // Register registers a new Collector to be included in metrics
+ // collection. It returns an error if the descriptors provided by the
+ // Collector are invalid or if they — in combination with descriptors of
+ // already registered Collectors — do not fulfill the consistency and
+ // uniqueness criteria described in the documentation of metric.Desc.
+ //
+ // If the provided Collector is equal to a Collector already registered
+ // (which includes the case of re-registering the same Collector), the
+ // returned error is an instance of AlreadyRegisteredError, which
+ // contains the previously registered Collector.
+ //
+ // It is in general not safe to register the same Collector multiple
+ // times concurrently.
+ Register(Collector) error
+ // MustRegister works like Register but registers any number of
+ // Collectors and panics upon the first registration that causes an
+ // error.
+ MustRegister(...Collector)
+ // Unregister unregisters the Collector that equals the Collector passed
+ // in as an argument. (Two Collectors are considered equal if their
+ // Describe method yields the same set of descriptors.) The function
+ // returns whether a Collector was unregistered.
+ //
+ // Note that even after unregistering, it will not be possible to
+ // register a new Collector that is inconsistent with the unregistered
+ // Collector, e.g. a Collector collecting metrics with the same name but
+ // a different help string. The rationale here is that the same registry
+ // instance must only collect consistent metrics throughout its
+ // lifetime.
+ Unregister(Collector) bool
+}
+
+// Gatherer is the interface for the part of a registry in charge of gathering
+// the collected metrics into a number of MetricFamilies. The Gatherer interface
+// comes with the same general implication as described for the Registerer
+// interface.
+type Gatherer interface {
+ // Gather calls the Collect method of the registered Collectors and then
+ // gathers the collected metrics into a lexicographically sorted slice
+ // of MetricFamily protobufs. Even if an error occurs, Gather attempts
+ // to gather as many metrics as possible. Hence, if a non-nil error is
+ // returned, the returned MetricFamily slice could be nil (in case of a
+ // fatal error that prevented any meaningful metric collection) or
+ // contain a number of MetricFamily protobufs, some of which might be
+ // incomplete, and some might be missing altogether. The returned error
+ // (which might be a MultiError) explains the details. In scenarios
+ // where complete collection is critical, the returned MetricFamily
+ // protobufs should be disregarded if the returned error is non-nil.
+ Gather() ([]*dto.MetricFamily, error)
+}
+
+// Register registers the provided Collector with the DefaultRegisterer.
+//
+// Register is a shortcut for DefaultRegisterer.Register(c). See there for more
+// details.
+func Register(c Collector) error {
+ return DefaultRegisterer.Register(c)
+}
+
+// MustRegister registers the provided Collectors with the DefaultRegisterer and
+// panics if any error occurs.
+//
+// MustRegister is a shortcut for DefaultRegisterer.MustRegister(cs...). See
+// there for more details.
+func MustRegister(cs ...Collector) {
+ DefaultRegisterer.MustRegister(cs...)
+}
+
+// RegisterOrGet registers the provided Collector with the DefaultRegisterer and
+// returns the Collector, unless an equal Collector was registered before, in
+// which case that Collector is returned.
+//
+// Deprecated: RegisterOrGet is merely a convenience function for the
+// implementation as described in the documentation for
+// AlreadyRegisteredError. As the use case is relatively rare, this function
+// will be removed in a future version of this package to clean up the
+// namespace.
+func RegisterOrGet(c Collector) (Collector, error) {
+ if err := Register(c); err != nil {
+ if are, ok := err.(AlreadyRegisteredError); ok {
+ return are.ExistingCollector, nil
+ }
+ return nil, err
+ }
+ return c, nil
+}
+
+// MustRegisterOrGet behaves like RegisterOrGet but panics instead of returning
+// an error.
+//
+// Deprecated: This is deprecated for the same reason RegisterOrGet is. See
+// there for details.
+func MustRegisterOrGet(c Collector) Collector {
+ c, err := RegisterOrGet(c)
if err != nil {
panic(err)
}
- return existing
+ return c
}
-// Unregister unregisters the Collector that equals the Collector passed in as
-// an argument. (Two Collectors are considered equal if their Describe method
-// yields the same set of descriptors.) The function returns whether a Collector
-// was unregistered.
+// Unregister removes the registration of the provided Collector from the
+// DefaultRegisterer.
+//
+// Unregister is a shortcut for DefaultRegisterer.Unregister(c). See there for
+// more details.
func Unregister(c Collector) bool {
- return defRegistry.Unregister(c)
+ return DefaultRegisterer.Unregister(c)
}
-// SetMetricFamilyInjectionHook sets a function that is called whenever metrics
-// are collected. The hook function must be set before metrics collection begins
-// (i.e. call SetMetricFamilyInjectionHook before setting the HTTP handler.) The
-// MetricFamily protobufs returned by the hook function are merged with the
-// metrics collected in the usual way.
+// GathererFunc turns a function into a Gatherer.
+type GathererFunc func() ([]*dto.MetricFamily, error)
+
+// Gather implements Gatherer.
+func (gf GathererFunc) Gather() ([]*dto.MetricFamily, error) {
+ return gf()
+}
+
+// SetMetricFamilyInjectionHook replaces the DefaultGatherer with one that
+// gathers from the previous DefaultGatherers but then merges the MetricFamily
+// protobufs returned from the provided hook function with the MetricFamily
+// protobufs returned from the original DefaultGatherer.
//
-// This is a way to directly inject MetricFamily protobufs managed and owned by
-// the caller. The caller has full responsibility. As no registration of the
-// injected metrics has happened, there is no descriptor to check against, and
-// there are no registration-time checks. If collect-time checks are disabled
-// (see function EnableCollectChecks), no sanity checks are performed on the
-// returned protobufs at all. If collect-checks are enabled, type and uniqueness
-// checks are performed, but no further consistency checks (which would require
-// knowledge of a metric descriptor).
-//
-// Sorting concerns: The caller is responsible for sorting the label pairs in
-// each metric. However, the order of metrics will be sorted by the registry as
-// it is required anyway after merging with the metric families collected
-// conventionally.
-//
-// The function must be callable at any time and concurrently.
+// Deprecated: This function manipulates the DefaultGatherer variable. Consider
+// the implications, i.e. don't do this concurrently with any uses of the
+// DefaultGatherer. In the rare cases where you need to inject MetricFamily
+// protobufs directly, it is recommended to use a custom Registry and combine it
+// with a custom Gatherer using the Gatherers type (see
+// there). SetMetricFamilyInjectionHook only exists for compatibility reasons
+// with previous versions of this package.
func SetMetricFamilyInjectionHook(hook func() []*dto.MetricFamily) {
- defRegistry.metricFamilyInjectionHook = hook
+ DefaultGatherer = Gatherers{
+ DefaultGatherer,
+ GathererFunc(func() ([]*dto.MetricFamily, error) { return hook(), nil }),
+ }
}
-// PanicOnCollectError sets the behavior whether a panic is caused upon an error
-// while metrics are collected and served to the HTTP endpoint. By default, an
-// internal server error (status code 500) is served with an error message.
-func PanicOnCollectError(b bool) {
- defRegistry.panicOnCollectError = b
+// AlreadyRegisteredError is returned by the Register method if the Collector to
+// be registered has already been registered before, or a different Collector
+// that collects the same metrics has been registered before. Registration fails
+// in that case, but you can detect from the kind of error what has
+// happened. The error contains fields for the existing Collector and the
+// (rejected) new Collector that equals the existing one. This can be used to
+// find out if an equal Collector has been registered before and switch over to
+// using the old one, as demonstrated in the example.
+type AlreadyRegisteredError struct {
+ ExistingCollector, NewCollector Collector
}
-// EnableCollectChecks enables (or disables) additional consistency checks
-// during metrics collection. These additional checks are not enabled by default
-// because they inflict a performance penalty and the errors they check for can
-// only happen if the used Metric and Collector types have internal programming
-// errors. It can be helpful to enable these checks while working with custom
-// Collectors or Metrics whose correctness is not well established yet.
-func EnableCollectChecks(b bool) {
- defRegistry.collectChecksEnabled = b
+func (err AlreadyRegisteredError) Error() string {
+ return "duplicate metrics collector registration attempted"
}
-// encoder is a function that writes a dto.MetricFamily to an io.Writer in a
-// certain encoding. It returns the number of bytes written and any error
-// encountered. Note that pbutil.WriteDelimited and pbutil.MetricFamilyToText
-// are encoders.
-type encoder func(io.Writer, *dto.MetricFamily) (int, error)
+// MultiError is a slice of errors implementing the error interface. It is used
+// by a Gatherer to report multiple errors during MetricFamily gathering.
+type MultiError []error
-type registry struct {
- mtx sync.RWMutex
- collectorsByID map[uint64]Collector // ID is a hash of the descIDs.
- descIDs map[uint64]struct{}
- dimHashesByName map[string]uint64
- bufPool chan *bytes.Buffer
- metricFamilyPool chan *dto.MetricFamily
- metricPool chan *dto.Metric
- metricFamilyInjectionHook func() []*dto.MetricFamily
-
- panicOnCollectError, collectChecksEnabled bool
+func (errs MultiError) Error() string {
+ if len(errs) == 0 {
+ return ""
+ }
+ buf := &bytes.Buffer{}
+ fmt.Fprintf(buf, "%d error(s) occurred:", len(errs))
+ for _, err := range errs {
+ fmt.Fprintf(buf, "\n* %s", err)
+ }
+ return buf.String()
}
-func (r *registry) Register(c Collector) (Collector, error) {
- descChan := make(chan *Desc, capDescChan)
+// MaybeUnwrap returns nil if len(errs) is 0. It returns the first and only
+// contained error as error if len(errs is 1). In all other cases, it returns
+// the MultiError directly. This is helpful for returning a MultiError in a way
+// that only uses the MultiError if needed.
+func (errs MultiError) MaybeUnwrap() error {
+ switch len(errs) {
+ case 0:
+ return nil
+ case 1:
+ return errs[0]
+ default:
+ return errs
+ }
+}
+
+// Registry registers Prometheus collectors, collects their metrics, and gathers
+// them into MetricFamilies for exposition. It implements both Registerer and
+// Gatherer. The zero value is not usable. Create instances with NewRegistry or
+// NewPedanticRegistry.
+type Registry struct {
+ mtx sync.RWMutex
+ collectorsByID map[uint64]Collector // ID is a hash of the descIDs.
+ descIDs map[uint64]struct{}
+ dimHashesByName map[string]uint64
+ pedanticChecksEnabled bool
+}
+
+// Register implements Registerer.
+func (r *Registry) Register(c Collector) error {
+ var (
+ descChan = make(chan *Desc, capDescChan)
+ newDescIDs = map[uint64]struct{}{}
+ newDimHashesByName = map[string]uint64{}
+ collectorID uint64 // Just a sum of all desc IDs.
+ duplicateDescErr error
+ )
go func() {
c.Describe(descChan)
close(descChan)
}()
-
- newDescIDs := map[uint64]struct{}{}
- newDimHashesByName := map[string]uint64{}
- var collectorID uint64 // Just a sum of all desc IDs.
- var duplicateDescErr error
-
r.mtx.Lock()
defer r.mtx.Unlock()
// Coduct various tests...
@@ -235,7 +299,7 @@ func (r *registry) Register(c Collector) (Collector, error) {
// Is the descriptor valid at all?
if desc.err != nil {
- return c, fmt.Errorf("descriptor %s is invalid: %s", desc, desc.err)
+ return fmt.Errorf("descriptor %s is invalid: %s", desc, desc.err)
}
// Is the descID unique?
@@ -256,13 +320,13 @@ func (r *registry) Register(c Collector) (Collector, error) {
// First check existing descriptors...
if dimHash, exists := r.dimHashesByName[desc.fqName]; exists {
if dimHash != desc.dimHash {
- return nil, fmt.Errorf("a previously registered descriptor with the same fully-qualified name as %s has different label names or a different help string", desc)
+ return fmt.Errorf("a previously registered descriptor with the same fully-qualified name as %s has different label names or a different help string", desc)
}
} else {
// ...then check the new descriptors already seen.
if dimHash, exists := newDimHashesByName[desc.fqName]; exists {
if dimHash != desc.dimHash {
- return nil, fmt.Errorf("descriptors reported by collector have inconsistent label names or help strings for the same fully-qualified name, offender is %s", desc)
+ return fmt.Errorf("descriptors reported by collector have inconsistent label names or help strings for the same fully-qualified name, offender is %s", desc)
}
} else {
newDimHashesByName[desc.fqName] = desc.dimHash
@@ -271,15 +335,18 @@ func (r *registry) Register(c Collector) (Collector, error) {
}
// Did anything happen at all?
if len(newDescIDs) == 0 {
- return nil, errors.New("collector has no descriptors")
+ return errors.New("collector has no descriptors")
}
if existing, exists := r.collectorsByID[collectorID]; exists {
- return existing, errAlreadyReg
+ return AlreadyRegisteredError{
+ ExistingCollector: existing,
+ NewCollector: c,
+ }
}
// If the collectorID is new, but at least one of the descs existed
// before, we are in trouble.
if duplicateDescErr != nil {
- return nil, duplicateDescErr
+ return duplicateDescErr
}
// Only after all tests have passed, actually register.
@@ -290,26 +357,20 @@ func (r *registry) Register(c Collector) (Collector, error) {
for name, dimHash := range newDimHashesByName {
r.dimHashesByName[name] = dimHash
}
- return c, nil
+ return nil
}
-func (r *registry) RegisterOrGet(m Collector) (Collector, error) {
- existing, err := r.Register(m)
- if err != nil && err != errAlreadyReg {
- return nil, err
- }
- return existing, nil
-}
-
-func (r *registry) Unregister(c Collector) bool {
- descChan := make(chan *Desc, capDescChan)
+// Unregister implements Registerer.
+func (r *Registry) Unregister(c Collector) bool {
+ var (
+ descChan = make(chan *Desc, capDescChan)
+ descIDs = map[uint64]struct{}{}
+ collectorID uint64 // Just a sum of the desc IDs.
+ )
go func() {
c.Describe(descChan)
close(descChan)
}()
-
- descIDs := map[uint64]struct{}{}
- var collectorID uint64 // Just a sum of the desc IDs.
for desc := range descChan {
if _, exists := descIDs[desc.id]; !exists {
collectorID += desc.id
@@ -336,69 +397,25 @@ func (r *registry) Unregister(c Collector) bool {
return true
}
-func (r *registry) Push(job, instance, pushURL, method string) error {
- if !strings.Contains(pushURL, "://") {
- pushURL = "http://" + pushURL
- }
- pushURL = fmt.Sprintf("%s/metrics/jobs/%s", pushURL, url.QueryEscape(job))
- if instance != "" {
- pushURL += "/instances/" + url.QueryEscape(instance)
- }
- buf := r.getBuf()
- defer r.giveBuf(buf)
- if _, err := r.writePB(buf, text.WriteProtoDelimited); err != nil {
- if r.panicOnCollectError {
+// MustRegister implements Registerer.
+func (r *Registry) MustRegister(cs ...Collector) {
+ for _, c := range cs {
+ if err := r.Register(c); err != nil {
panic(err)
}
- return err
}
- req, err := http.NewRequest(method, pushURL, buf)
- if err != nil {
- return err
- }
- req.Header.Set(contentTypeHeader, DelimitedTelemetryContentType)
- resp, err := http.DefaultClient.Do(req)
- if err != nil {
- return err
- }
- defer resp.Body.Close()
- if resp.StatusCode != 202 {
- return fmt.Errorf("unexpected status code %d while pushing to %s", resp.StatusCode, pushURL)
- }
- return nil
}
-func (r *registry) ServeHTTP(w http.ResponseWriter, req *http.Request) {
- enc, contentType := chooseEncoder(req)
- buf := r.getBuf()
- defer r.giveBuf(buf)
- writer, encoding := decorateWriter(req, buf)
- if _, err := r.writePB(writer, enc); err != nil {
- if r.panicOnCollectError {
- panic(err)
- }
- http.Error(w, "An error has occurred:\n\n"+err.Error(), http.StatusInternalServerError)
- return
- }
- if closer, ok := writer.(io.Closer); ok {
- closer.Close()
- }
- header := w.Header()
- header.Set(contentTypeHeader, contentType)
- header.Set(contentLengthHeader, fmt.Sprint(buf.Len()))
- if encoding != "" {
- header.Set(contentEncodingHeader, encoding)
- }
- w.Write(buf.Bytes())
-}
-
-func (r *registry) writePB(w io.Writer, writeEncoded encoder) (int, error) {
- var metricHashes map[uint64]struct{}
- if r.collectChecksEnabled {
- metricHashes = make(map[uint64]struct{})
- }
- metricChan := make(chan Metric, capMetricChan)
- wg := sync.WaitGroup{}
+// Gather implements Gatherer.
+func (r *Registry) Gather() ([]*dto.MetricFamily, error) {
+ var (
+ metricChan = make(chan Metric, capMetricChan)
+ metricHashes = map[uint64]struct{}{}
+ dimHashes = map[string]uint64{}
+ wg sync.WaitGroup
+ errs MultiError // The collected errors to return in the end.
+ registeredDescIDs map[uint64]struct{} // Only used for pedantic checks
+ )
r.mtx.RLock()
metricFamiliesByName := make(map[string]*dto.MetricFamily, len(r.dimHashesByName))
@@ -416,6 +433,16 @@ func (r *registry) writePB(w io.Writer, writeEncoded encoder) (int, error) {
collector.Collect(metricChan)
}(collector)
}
+
+ // In case pedantic checks are enabled, we have to copy the map before
+ // giving up the RLock.
+ if r.pedanticChecksEnabled {
+ registeredDescIDs = make(map[uint64]struct{}, len(r.descIDs))
+ for id := range r.descIDs {
+ registeredDescIDs[id] = struct{}{}
+ }
+ }
+
r.mtx.RUnlock()
// Drain metricChan in case of premature return.
@@ -430,97 +457,267 @@ func (r *registry) writePB(w io.Writer, writeEncoded encoder) (int, error) {
// of metricFamiliesByName (and of metricHashes if checks are
// enabled). Most likely not worth it.
desc := metric.Desc()
+ dtoMetric := &dto.Metric{}
+ if err := metric.Write(dtoMetric); err != nil {
+ errs = append(errs, fmt.Errorf(
+ "error collecting metric %v: %s", desc, err,
+ ))
+ continue
+ }
metricFamily, ok := metricFamiliesByName[desc.fqName]
- if !ok {
- metricFamily = r.getMetricFamily()
- defer r.giveMetricFamily(metricFamily)
+ if ok {
+ if metricFamily.GetHelp() != desc.help {
+ errs = append(errs, fmt.Errorf(
+ "collected metric %s %s has help %q but should have %q",
+ desc.fqName, dtoMetric, desc.help, metricFamily.GetHelp(),
+ ))
+ continue
+ }
+ // TODO(beorn7): Simplify switch once Desc has type.
+ switch metricFamily.GetType() {
+ case dto.MetricType_COUNTER:
+ if dtoMetric.Counter == nil {
+ errs = append(errs, fmt.Errorf(
+ "collected metric %s %s should be a Counter",
+ desc.fqName, dtoMetric,
+ ))
+ continue
+ }
+ case dto.MetricType_GAUGE:
+ if dtoMetric.Gauge == nil {
+ errs = append(errs, fmt.Errorf(
+ "collected metric %s %s should be a Gauge",
+ desc.fqName, dtoMetric,
+ ))
+ continue
+ }
+ case dto.MetricType_SUMMARY:
+ if dtoMetric.Summary == nil {
+ errs = append(errs, fmt.Errorf(
+ "collected metric %s %s should be a Summary",
+ desc.fqName, dtoMetric,
+ ))
+ continue
+ }
+ case dto.MetricType_UNTYPED:
+ if dtoMetric.Untyped == nil {
+ errs = append(errs, fmt.Errorf(
+ "collected metric %s %s should be Untyped",
+ desc.fqName, dtoMetric,
+ ))
+ continue
+ }
+ case dto.MetricType_HISTOGRAM:
+ if dtoMetric.Histogram == nil {
+ errs = append(errs, fmt.Errorf(
+ "collected metric %s %s should be a Histogram",
+ desc.fqName, dtoMetric,
+ ))
+ continue
+ }
+ default:
+ panic("encountered MetricFamily with invalid type")
+ }
+ } else {
+ metricFamily = &dto.MetricFamily{}
metricFamily.Name = proto.String(desc.fqName)
metricFamily.Help = proto.String(desc.help)
+ // TODO(beorn7): Simplify switch once Desc has type.
+ switch {
+ case dtoMetric.Gauge != nil:
+ metricFamily.Type = dto.MetricType_GAUGE.Enum()
+ case dtoMetric.Counter != nil:
+ metricFamily.Type = dto.MetricType_COUNTER.Enum()
+ case dtoMetric.Summary != nil:
+ metricFamily.Type = dto.MetricType_SUMMARY.Enum()
+ case dtoMetric.Untyped != nil:
+ metricFamily.Type = dto.MetricType_UNTYPED.Enum()
+ case dtoMetric.Histogram != nil:
+ metricFamily.Type = dto.MetricType_HISTOGRAM.Enum()
+ default:
+ errs = append(errs, fmt.Errorf(
+ "empty metric collected: %s", dtoMetric,
+ ))
+ continue
+ }
metricFamiliesByName[desc.fqName] = metricFamily
}
- dtoMetric := r.getMetric()
- defer r.giveMetric(dtoMetric)
- if err := metric.Write(dtoMetric); err != nil {
- // TODO: Consider different means of error reporting so
- // that a single erroneous metric could be skipped
- // instead of blowing up the whole collection.
- return 0, fmt.Errorf("error collecting metric %v: %s", desc, err)
+ if err := checkMetricConsistency(metricFamily, dtoMetric, metricHashes, dimHashes); err != nil {
+ errs = append(errs, err)
+ continue
}
- switch {
- case metricFamily.Type != nil:
- // Type already set. We are good.
- case dtoMetric.Gauge != nil:
- metricFamily.Type = dto.MetricType_GAUGE.Enum()
- case dtoMetric.Counter != nil:
- metricFamily.Type = dto.MetricType_COUNTER.Enum()
- case dtoMetric.Summary != nil:
- metricFamily.Type = dto.MetricType_SUMMARY.Enum()
- case dtoMetric.Untyped != nil:
- metricFamily.Type = dto.MetricType_UNTYPED.Enum()
- case dtoMetric.Histogram != nil:
- metricFamily.Type = dto.MetricType_HISTOGRAM.Enum()
- default:
- return 0, fmt.Errorf("empty metric collected: %s", dtoMetric)
- }
- if r.collectChecksEnabled {
- if err := r.checkConsistency(metricFamily, dtoMetric, desc, metricHashes); err != nil {
- return 0, err
+ if r.pedanticChecksEnabled {
+ // Is the desc registered at all?
+ if _, exist := registeredDescIDs[desc.id]; !exist {
+ errs = append(errs, fmt.Errorf(
+ "collected metric %s %s with unregistered descriptor %s",
+ metricFamily.GetName(), dtoMetric, desc,
+ ))
+ continue
+ }
+ if err := checkDescConsistency(metricFamily, dtoMetric, desc); err != nil {
+ errs = append(errs, err)
+ continue
}
}
metricFamily.Metric = append(metricFamily.Metric, dtoMetric)
}
+ return normalizeMetricFamilies(metricFamiliesByName), errs.MaybeUnwrap()
+}
- if r.metricFamilyInjectionHook != nil {
- for _, mf := range r.metricFamilyInjectionHook() {
- existingMF, exists := metricFamiliesByName[mf.GetName()]
- if !exists {
- metricFamiliesByName[mf.GetName()] = mf
- if r.collectChecksEnabled {
- for _, m := range mf.Metric {
- if err := r.checkConsistency(mf, m, nil, metricHashes); err != nil {
- return 0, err
- }
- }
+// Gatherers is a slice of Gatherer instances that implements the Gatherer
+// interface itself. Its Gather method calls Gather on all Gatherers in the
+// slice in order and returns the merged results. Errors returned from the
+// Gather calles are all returned in a flattened MultiError. Duplicate and
+// inconsistent Metrics are skipped (first occurrence in slice order wins) and
+// reported in the returned error.
+//
+// Gatherers can be used to merge the Gather results from multiple
+// Registries. It also provides a way to directly inject existing MetricFamily
+// protobufs into the gathering by creating a custom Gatherer with a Gather
+// method that simply returns the existing MetricFamily protobufs. Note that no
+// registration is involved (in contrast to Collector registration), so
+// obviously registration-time checks cannot happen. Any inconsistencies between
+// the gathered MetricFamilies are reported as errors by the Gather method, and
+// inconsistent Metrics are dropped. Invalid parts of the MetricFamilies
+// (e.g. syntactically invalid metric or label names) will go undetected.
+type Gatherers []Gatherer
+
+// Gather implements Gatherer.
+func (gs Gatherers) Gather() ([]*dto.MetricFamily, error) {
+ var (
+ metricFamiliesByName = map[string]*dto.MetricFamily{}
+ metricHashes = map[uint64]struct{}{}
+ dimHashes = map[string]uint64{}
+ errs MultiError // The collected errors to return in the end.
+ )
+
+ for i, g := range gs {
+ mfs, err := g.Gather()
+ if err != nil {
+ if multiErr, ok := err.(MultiError); ok {
+ for _, err := range multiErr {
+ errs = append(errs, fmt.Errorf("[from Gatherer #%d] %s", i+1, err))
}
- continue
+ } else {
+ errs = append(errs, fmt.Errorf("[from Gatherer #%d] %s", i+1, err))
+ }
+ }
+ for _, mf := range mfs {
+ existingMF, exists := metricFamiliesByName[mf.GetName()]
+ if exists {
+ if existingMF.GetHelp() != mf.GetHelp() {
+ errs = append(errs, fmt.Errorf(
+ "gathered metric family %s has help %q but should have %q",
+ mf.GetName(), mf.GetHelp(), existingMF.GetHelp(),
+ ))
+ continue
+ }
+ if existingMF.GetType() != mf.GetType() {
+ errs = append(errs, fmt.Errorf(
+ "gathered metric family %s has type %s but should have %s",
+ mf.GetName(), mf.GetType(), existingMF.GetType(),
+ ))
+ continue
+ }
+ } else {
+ existingMF = &dto.MetricFamily{}
+ existingMF.Name = mf.Name
+ existingMF.Help = mf.Help
+ existingMF.Type = mf.Type
+ metricFamiliesByName[mf.GetName()] = existingMF
}
for _, m := range mf.Metric {
- if r.collectChecksEnabled {
- if err := r.checkConsistency(existingMF, m, nil, metricHashes); err != nil {
- return 0, err
- }
+ if err := checkMetricConsistency(existingMF, m, metricHashes, dimHashes); err != nil {
+ errs = append(errs, err)
+ continue
}
existingMF.Metric = append(existingMF.Metric, m)
}
}
}
+ return normalizeMetricFamilies(metricFamiliesByName), errs.MaybeUnwrap()
+}
- // Now that MetricFamilies are all set, sort their Metrics
- // lexicographically by their label values.
+// metricSorter is a sortable slice of *dto.Metric.
+type metricSorter []*dto.Metric
+
+func (s metricSorter) Len() int {
+ return len(s)
+}
+
+func (s metricSorter) Swap(i, j int) {
+ s[i], s[j] = s[j], s[i]
+}
+
+func (s metricSorter) Less(i, j int) bool {
+ if len(s[i].Label) != len(s[j].Label) {
+ // This should not happen. The metrics are
+ // inconsistent. However, we have to deal with the fact, as
+ // people might use custom collectors or metric family injection
+ // to create inconsistent metrics. So let's simply compare the
+ // number of labels in this case. That will still yield
+ // reproducible sorting.
+ return len(s[i].Label) < len(s[j].Label)
+ }
+ for n, lp := range s[i].Label {
+ vi := lp.GetValue()
+ vj := s[j].Label[n].GetValue()
+ if vi != vj {
+ return vi < vj
+ }
+ }
+
+ // We should never arrive here. Multiple metrics with the same
+ // label set in the same scrape will lead to undefined ingestion
+ // behavior. However, as above, we have to provide stable sorting
+ // here, even for inconsistent metrics. So sort equal metrics
+ // by their timestamp, with missing timestamps (implying "now")
+ // coming last.
+ if s[i].TimestampMs == nil {
+ return false
+ }
+ if s[j].TimestampMs == nil {
+ return true
+ }
+ return s[i].GetTimestampMs() < s[j].GetTimestampMs()
+}
+
+// normalizeMetricFamilies returns a MetricFamily slice whith empty
+// MetricFamilies pruned and the remaining MetricFamilies sorted by name within
+// the slice, with the contained Metrics sorted within each MetricFamily.
+func normalizeMetricFamilies(metricFamiliesByName map[string]*dto.MetricFamily) []*dto.MetricFamily {
for _, mf := range metricFamiliesByName {
sort.Sort(metricSorter(mf.Metric))
}
-
- // Write out MetricFamilies sorted by their name.
names := make([]string, 0, len(metricFamiliesByName))
- for name := range metricFamiliesByName {
- names = append(names, name)
- }
- sort.Strings(names)
-
- var written int
- for _, name := range names {
- w, err := writeEncoded(w, metricFamiliesByName[name])
- written += w
- if err != nil {
- return written, err
+ for name, mf := range metricFamiliesByName {
+ if len(mf.Metric) > 0 {
+ names = append(names, name)
}
}
- return written, nil
+ sort.Strings(names)
+ result := make([]*dto.MetricFamily, 0, len(names))
+ for _, name := range names {
+ result = append(result, metricFamiliesByName[name])
+ }
+ return result
}
-func (r *registry) checkConsistency(metricFamily *dto.MetricFamily, dtoMetric *dto.Metric, desc *Desc, metricHashes map[uint64]struct{}) error {
-
+// checkMetricConsistency checks if the provided Metric is consistent with the
+// provided MetricFamily. It also hashed the Metric labels and the MetricFamily
+// name. If the resulting hash is alread in the provided metricHashes, an error
+// is returned. If not, it is added to metricHashes. The provided dimHashes maps
+// MetricFamily names to their dimHash (hashed sorted label names). If dimHashes
+// doesn't yet contain a hash for the provided MetricFamily, it is
+// added. Otherwise, an error is returned if the existing dimHashes in not equal
+// the calculated dimHash.
+func checkMetricConsistency(
+ metricFamily *dto.MetricFamily,
+ dtoMetric *dto.Metric,
+ metricHashes map[uint64]struct{},
+ dimHashes map[string]uint64,
+) error {
// Type consistency with metric family.
if metricFamily.GetType() == dto.MetricType_GAUGE && dtoMetric.Gauge == nil ||
metricFamily.GetType() == dto.MetricType_COUNTER && dtoMetric.Counter == nil ||
@@ -534,42 +731,45 @@ func (r *registry) checkConsistency(metricFamily *dto.MetricFamily, dtoMetric *d
}
// Is the metric unique (i.e. no other metric with the same name and the same label values)?
- h := fnv.New64a()
- var buf bytes.Buffer
- buf.WriteString(metricFamily.GetName())
- buf.WriteByte(model.SeparatorByte)
- h.Write(buf.Bytes())
+ h := hashNew()
+ h = hashAdd(h, metricFamily.GetName())
+ h = hashAddByte(h, separatorByte)
+ dh := hashNew()
// Make sure label pairs are sorted. We depend on it for the consistency
- // check. Label pairs must be sorted by contract. But the point of this
- // method is to check for contract violations. So we better do the sort
- // now.
+ // check.
sort.Sort(LabelPairSorter(dtoMetric.Label))
for _, lp := range dtoMetric.Label {
- buf.Reset()
- buf.WriteString(lp.GetValue())
- buf.WriteByte(model.SeparatorByte)
- h.Write(buf.Bytes())
+ h = hashAdd(h, lp.GetValue())
+ h = hashAddByte(h, separatorByte)
+ dh = hashAdd(dh, lp.GetName())
+ dh = hashAddByte(dh, separatorByte)
}
- metricHash := h.Sum64()
- if _, exists := metricHashes[metricHash]; exists {
+ if _, exists := metricHashes[h]; exists {
return fmt.Errorf(
"collected metric %s %s was collected before with the same name and label values",
metricFamily.GetName(), dtoMetric,
)
}
- metricHashes[metricHash] = struct{}{}
-
- if desc == nil {
- return nil // Nothing left to check if we have no desc.
+ if dimHash, ok := dimHashes[metricFamily.GetName()]; ok {
+ if dimHash != dh {
+ return fmt.Errorf(
+ "collected metric %s %s has label dimensions inconsistent with previously collected metrics in the same metric family",
+ metricFamily.GetName(), dtoMetric,
+ )
+ }
+ } else {
+ dimHashes[metricFamily.GetName()] = dh
}
+ metricHashes[h] = struct{}{}
+ return nil
+}
- // Desc consistency with metric family.
- if metricFamily.GetName() != desc.fqName {
- return fmt.Errorf(
- "collected metric %s %s has name %q but should have %q",
- metricFamily.GetName(), dtoMetric, metricFamily.GetName(), desc.fqName,
- )
- }
+func checkDescConsistency(
+ metricFamily *dto.MetricFamily,
+ dtoMetric *dto.Metric,
+ desc *Desc,
+) error {
+ // Desc help consistency with metric family help.
if metricFamily.GetHelp() != desc.help {
return fmt.Errorf(
"collected metric %s %s has help %q but should have %q",
@@ -602,159 +802,5 @@ func (r *registry) checkConsistency(metricFamily *dto.MetricFamily, dtoMetric *d
)
}
}
-
- r.mtx.RLock() // Remaining checks need the read lock.
- defer r.mtx.RUnlock()
-
- // Is the desc registered?
- if _, exist := r.descIDs[desc.id]; !exist {
- return fmt.Errorf(
- "collected metric %s %s with unregistered descriptor %s",
- metricFamily.GetName(), dtoMetric, desc,
- )
- }
-
return nil
}
-
-func (r *registry) getBuf() *bytes.Buffer {
- select {
- case buf := <-r.bufPool:
- return buf
- default:
- return &bytes.Buffer{}
- }
-}
-
-func (r *registry) giveBuf(buf *bytes.Buffer) {
- buf.Reset()
- select {
- case r.bufPool <- buf:
- default:
- }
-}
-
-func (r *registry) getMetricFamily() *dto.MetricFamily {
- select {
- case mf := <-r.metricFamilyPool:
- return mf
- default:
- return &dto.MetricFamily{}
- }
-}
-
-func (r *registry) giveMetricFamily(mf *dto.MetricFamily) {
- mf.Reset()
- select {
- case r.metricFamilyPool <- mf:
- default:
- }
-}
-
-func (r *registry) getMetric() *dto.Metric {
- select {
- case m := <-r.metricPool:
- return m
- default:
- return &dto.Metric{}
- }
-}
-
-func (r *registry) giveMetric(m *dto.Metric) {
- m.Reset()
- select {
- case r.metricPool <- m:
- default:
- }
-}
-
-func newRegistry() *registry {
- return ®istry{
- collectorsByID: map[uint64]Collector{},
- descIDs: map[uint64]struct{}{},
- dimHashesByName: map[string]uint64{},
- bufPool: make(chan *bytes.Buffer, numBufs),
- metricFamilyPool: make(chan *dto.MetricFamily, numMetricFamilies),
- metricPool: make(chan *dto.Metric, numMetrics),
- }
-}
-
-func newDefaultRegistry() *registry {
- r := newRegistry()
- r.Register(NewProcessCollector(os.Getpid(), ""))
- r.Register(NewGoCollector())
- return r
-}
-
-func chooseEncoder(req *http.Request) (encoder, string) {
- accepts := goautoneg.ParseAccept(req.Header.Get(acceptHeader))
- for _, accept := range accepts {
- switch {
- case accept.Type == "application" &&
- accept.SubType == "vnd.google.protobuf" &&
- accept.Params["proto"] == "io.prometheus.client.MetricFamily":
- switch accept.Params["encoding"] {
- case "delimited":
- return text.WriteProtoDelimited, DelimitedTelemetryContentType
- case "text":
- return text.WriteProtoText, ProtoTextTelemetryContentType
- case "compact-text":
- return text.WriteProtoCompactText, ProtoCompactTextTelemetryContentType
- default:
- continue
- }
- case accept.Type == "text" &&
- accept.SubType == "plain" &&
- (accept.Params["version"] == "0.0.4" || accept.Params["version"] == ""):
- return text.MetricFamilyToText, TextTelemetryContentType
- default:
- continue
- }
- }
- return text.MetricFamilyToText, TextTelemetryContentType
-}
-
-// decorateWriter wraps a writer to handle gzip compression if requested. It
-// returns the decorated writer and the appropriate "Content-Encoding" header
-// (which is empty if no compression is enabled).
-func decorateWriter(request *http.Request, writer io.Writer) (io.Writer, string) {
- header := request.Header.Get(acceptEncodingHeader)
- parts := strings.Split(header, ",")
- for _, part := range parts {
- part := strings.TrimSpace(part)
- if part == "gzip" || strings.HasPrefix(part, "gzip;") {
- return gzip.NewWriter(writer), "gzip"
- }
- }
- return writer, ""
-}
-
-type metricSorter []*dto.Metric
-
-func (s metricSorter) Len() int {
- return len(s)
-}
-
-func (s metricSorter) Swap(i, j int) {
- s[i], s[j] = s[j], s[i]
-}
-
-func (s metricSorter) Less(i, j int) bool {
- if len(s[i].Label) != len(s[j].Label) {
- // This should not happen. The metrics are
- // inconsistent. However, we have to deal with the fact, as
- // people might use custom collectors or metric family injection
- // to create inconsistent metrics. So let's simply compare the
- // number of labels in this case. That will still yield
- // reproducible sorting.
- return len(s[i].Label) < len(s[j].Label)
- }
- for n, lp := range s[i].Label {
- vi := lp.GetValue()
- vj := s[j].Label[n].GetValue()
- if vi != vj {
- return vi < vj
- }
- }
- return true
-}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go b/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go
index f30c90c..9dacb62 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/registry_test.go
@@ -17,41 +17,30 @@
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file.
-package prometheus
+package prometheus_test
import (
"bytes"
- "encoding/binary"
"net/http"
+ "net/http/httptest"
"testing"
- "github.com/golang/protobuf/proto"
dto "github.com/prometheus/client_model/go"
+
+ "github.com/golang/protobuf/proto"
+ "github.com/prometheus/common/expfmt"
+
+ "github.com/prometheus/client_golang/prometheus"
+ "github.com/prometheus/client_golang/prometheus/promhttp"
)
-type fakeResponseWriter struct {
- header http.Header
- body bytes.Buffer
-}
-
-func (r *fakeResponseWriter) Header() http.Header {
- return r.header
-}
-
-func (r *fakeResponseWriter) Write(d []byte) (l int, err error) {
- return r.body.Write(d)
-}
-
-func (r *fakeResponseWriter) WriteHeader(c int) {
-}
-
func testHandler(t testing.TB) {
- metricVec := NewCounterVec(
- CounterOpts{
+ metricVec := prometheus.NewCounterVec(
+ prometheus.CounterOpts{
Name: "name",
Help: "docstring",
- ConstLabels: Labels{"constname": "constvalue"},
+ ConstLabels: prometheus.Labels{"constname": "constvalue"},
},
[]string{"labelname"},
)
@@ -59,8 +48,6 @@ func testHandler(t testing.TB) {
metricVec.WithLabelValues("val1").Inc()
metricVec.WithLabelValues("val2").Inc()
- varintBuf := make([]byte, binary.MaxVarintLen32)
-
externalMetricFamily := &dto.MetricFamily{
Name: proto.String("externalname"),
Help: proto.String("externaldocstring"),
@@ -83,18 +70,9 @@ func testHandler(t testing.TB) {
},
},
}
- marshaledExternalMetricFamily, err := proto.Marshal(externalMetricFamily)
- if err != nil {
- t.Fatal(err)
- }
- var externalBuf bytes.Buffer
- l := binary.PutUvarint(varintBuf, uint64(len(marshaledExternalMetricFamily)))
- _, err = externalBuf.Write(varintBuf[:l])
- if err != nil {
- t.Fatal(err)
- }
- _, err = externalBuf.Write(marshaledExternalMetricFamily)
- if err != nil {
+ externalBuf := &bytes.Buffer{}
+ enc := expfmt.NewEncoder(externalBuf, expfmt.FmtProtoDelim)
+ if err := enc.Encode(externalMetricFamily); err != nil {
t.Fatal(err)
}
externalMetricFamilyAsBytes := externalBuf.Bytes()
@@ -160,18 +138,9 @@ metric: <
},
},
}
- marshaledExpectedMetricFamily, err := proto.Marshal(expectedMetricFamily)
- if err != nil {
- t.Fatal(err)
- }
- var buf bytes.Buffer
- l = binary.PutUvarint(varintBuf, uint64(len(marshaledExpectedMetricFamily)))
- _, err = buf.Write(varintBuf[:l])
- if err != nil {
- t.Fatal(err)
- }
- _, err = buf.Write(marshaledExpectedMetricFamily)
- if err != nil {
+ buf := &bytes.Buffer{}
+ enc = expfmt.NewEncoder(buf, expfmt.FmtProtoDelim)
+ if err := enc.Encode(expectedMetricFamily); err != nil {
t.Fatal(err)
}
expectedMetricFamilyAsBytes := buf.Bytes()
@@ -216,7 +185,7 @@ metric: <
externalMetricFamilyWithSameName := &dto.MetricFamily{
Name: proto.String("name"),
- Help: proto.String("inconsistent help string does not matter here"),
+ Help: proto.String("docstring"),
Type: dto.MetricType_COUNTER.Enum(),
Metric: []*dto.Metric{
{
@@ -248,7 +217,7 @@ metric: <
var scenarios = []struct {
headers map[string]string
out output
- collector Collector
+ collector prometheus.Collector
externalMF []*dto.MetricFamily
}{
{ // 0
@@ -485,21 +454,22 @@ metric: <
},
}
for i, scenario := range scenarios {
- registry := newRegistry()
- registry.collectChecksEnabled = true
+ registry := prometheus.NewPedanticRegistry()
+ gatherer := prometheus.Gatherer(registry)
+ if scenario.externalMF != nil {
+ gatherer = prometheus.Gatherers{
+ registry,
+ prometheus.GathererFunc(func() ([]*dto.MetricFamily, error) {
+ return scenario.externalMF, nil
+ }),
+ }
+ }
if scenario.collector != nil {
registry.Register(scenario.collector)
}
- if scenario.externalMF != nil {
- registry.metricFamilyInjectionHook = func() []*dto.MetricFamily {
- return scenario.externalMF
- }
- }
- writer := &fakeResponseWriter{
- header: http.Header{},
- }
- handler := InstrumentHandler("prometheus", registry)
+ writer := httptest.NewRecorder()
+ handler := prometheus.InstrumentHandler("prometheus", promhttp.HandlerFor(gatherer, promhttp.HandlerOpts{}))
request, _ := http.NewRequest("GET", "/", nil)
for key, value := range scenario.headers {
request.Header.Add(key, value)
@@ -507,7 +477,7 @@ metric: <
handler(writer, request)
for key, value := range scenario.out.headers {
- if writer.Header().Get(key) != value {
+ if writer.HeaderMap.Get(key) != value {
t.Errorf(
"%d. expected %q for header %q, got %q",
i, value, key, writer.Header().Get(key),
@@ -515,10 +485,10 @@ metric: <
}
}
- if !bytes.Equal(scenario.out.body, writer.body.Bytes()) {
+ if !bytes.Equal(scenario.out.body, writer.Body.Bytes()) {
t.Errorf(
- "%d. expected %q for body, got %q",
- i, scenario.out.body, writer.body.Bytes(),
+ "%d. expected body:\n%s\ngot body:\n%s\n",
+ i, scenario.out.body, writer.Body.Bytes(),
)
}
}
@@ -533,3 +503,43 @@ func BenchmarkHandler(b *testing.B) {
testHandler(b)
}
}
+
+func TestRegisterWithOrGet(t *testing.T) {
+ // Replace the default registerer just to be sure. This is bad, but this
+ // whole test will go away once RegisterOrGet is removed.
+ oldRegisterer := prometheus.DefaultRegisterer
+ defer func() {
+ prometheus.DefaultRegisterer = oldRegisterer
+ }()
+ prometheus.DefaultRegisterer = prometheus.NewRegistry()
+ original := prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "test",
+ Help: "help",
+ },
+ []string{"foo", "bar"},
+ )
+ equalButNotSame := prometheus.NewCounterVec(
+ prometheus.CounterOpts{
+ Name: "test",
+ Help: "help",
+ },
+ []string{"foo", "bar"},
+ )
+ if err := prometheus.Register(original); err != nil {
+ t.Fatal(err)
+ }
+ if err := prometheus.Register(equalButNotSame); err == nil {
+ t.Fatal("expected error when registringe equal collector")
+ }
+ existing, err := prometheus.RegisterOrGet(equalButNotSame)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if existing != original {
+ t.Error("expected original collector but got something else")
+ }
+ if existing == equalButNotSame {
+ t.Error("expected original callector but got new one")
+ }
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary.go b/vendor/github.com/prometheus/client_golang/prometheus/summary.go
index 67fe43c..bce05bf 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/summary.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/summary.go
@@ -15,7 +15,6 @@ package prometheus
import (
"fmt"
- "hash/fnv"
"math"
"sort"
"sync"
@@ -25,10 +24,12 @@ import (
"github.com/golang/protobuf/proto"
dto "github.com/prometheus/client_model/go"
-
- "github.com/prometheus/client_golang/model"
)
+// quantileLabel is used for the label that defines the quantile in a
+// summary.
+const quantileLabel = "quantile"
+
// A Summary captures individual observations from an event or sample stream and
// summarizes them in a manner similar to traditional summary statistics: 1. sum
// of observations, 2. observation count, 3. rank estimations.
@@ -52,12 +53,12 @@ type Summary interface {
Observe(float64)
}
+// DefObjectives are the default Summary quantile values.
var (
- // DefObjectives are the default Summary quantile values.
DefObjectives = map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001}
errQuantileLabelNotAllowed = fmt.Errorf(
- "%q is not allowed as label name in summaries", model.QuantileLabel,
+ "%q is not allowed as label name in summaries", quantileLabel,
)
)
@@ -112,7 +113,9 @@ type SummaryOpts struct {
ConstLabels Labels
// Objectives defines the quantile rank estimates with their respective
- // absolute error. The default value is DefObjectives.
+ // absolute error. If Objectives[q] = e, then the value reported
+ // for q will be the φ-quantile value for some φ between q-e and q+e.
+ // The default value is DefObjectives.
Objectives map[float64]float64
// MaxAge defines the duration for which an observation stays relevant
@@ -136,11 +139,11 @@ type SummaryOpts struct {
BufCap uint32
}
-// TODO: Great fuck-up with the sliding-window decay algorithm... The Merge
-// method of perk/quantile is actually not working as advertised - and it might
-// be unfixable, as the underlying algorithm is apparently not capable of
-// merging summaries in the first place. To avoid using Merge, we are currently
-// adding observations to _each_ age bucket, i.e. the effort to add a sample is
+// Great fuck-up with the sliding-window decay algorithm... The Merge method of
+// perk/quantile is actually not working as advertised - and it might be
+// unfixable, as the underlying algorithm is apparently not capable of merging
+// summaries in the first place. To avoid using Merge, we are currently adding
+// observations to _each_ age bucket, i.e. the effort to add a sample is
// essentially multiplied by the number of age buckets. When rotating age
// buckets, we empty the previous head stream. On scrape time, we simply take
// the quantiles from the head stream (no merging required). Result: More effort
@@ -170,12 +173,12 @@ func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary {
}
for _, n := range desc.variableLabels {
- if n == model.QuantileLabel {
+ if n == quantileLabel {
panic(errQuantileLabelNotAllowed)
}
}
for _, lp := range desc.constLabelPairs {
- if lp.GetName() == model.QuantileLabel {
+ if lp.GetName() == quantileLabel {
panic(errQuantileLabelNotAllowed)
}
}
@@ -224,12 +227,12 @@ func newSummary(desc *Desc, opts SummaryOpts, labelValues ...string) Summary {
}
sort.Float64s(s.sortedObjectives)
- s.Init(s) // Init self-collection.
+ s.init(s) // Init self-collection.
return s
}
type summary struct {
- SelfCollector
+ selfCollector
bufMtx sync.Mutex // Protects hotBuf and hotBufExpTime.
mtx sync.Mutex // Protects every other moving part.
@@ -387,7 +390,7 @@ func (s quantSort) Less(i, j int) bool {
// (e.g. HTTP request latencies, partitioned by status code and method). Create
// instances with NewSummaryVec.
type SummaryVec struct {
- MetricVec
+ *MetricVec
}
// NewSummaryVec creates a new SummaryVec based on the provided SummaryOpts and
@@ -401,14 +404,9 @@ func NewSummaryVec(opts SummaryOpts, labelNames []string) *SummaryVec {
opts.ConstLabels,
)
return &SummaryVec{
- MetricVec: MetricVec{
- children: map[uint64]Metric{},
- desc: desc,
- hash: fnv.New64a(),
- newMetric: func(lvs ...string) Metric {
- return newSummary(desc, opts, lvs...)
- },
- },
+ MetricVec: newMetricVec(desc, func(lvs ...string) Metric {
+ return newSummary(desc, opts, lvs...)
+ }),
}
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go b/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go
index 0790cdf..c4575ff 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/summary_test.go
@@ -329,8 +329,8 @@ func TestSummaryDecay(t *testing.T) {
}
func getBounds(vars []float64, q, ε float64) (min, max float64) {
- // TODO: This currently tolerates an error of up to 2*ε. The error must
- // be at most ε, but for some reason, it's sometimes slightly
+ // TODO(beorn7): This currently tolerates an error of up to 2*ε. The
+ // error must be at most ε, but for some reason, it's sometimes slightly
// higher. That's a bug.
n := float64(len(vars))
lower := int((q - 2*ε) * n)
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/untyped.go b/vendor/github.com/prometheus/client_golang/prometheus/untyped.go
index c65ab1c..5faf7e6 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/untyped.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/untyped.go
@@ -13,8 +13,6 @@
package prometheus
-import "hash/fnv"
-
// Untyped is a Metric that represents a single numerical value that can
// arbitrarily go up and down.
//
@@ -58,7 +56,7 @@ func NewUntyped(opts UntypedOpts) Untyped {
// labels. This is used if you want to count the same thing partitioned by
// various dimensions. Create instances with NewUntypedVec.
type UntypedVec struct {
- MetricVec
+ *MetricVec
}
// NewUntypedVec creates a new UntypedVec based on the provided UntypedOpts and
@@ -72,14 +70,9 @@ func NewUntypedVec(opts UntypedOpts, labelNames []string) *UntypedVec {
opts.ConstLabels,
)
return &UntypedVec{
- MetricVec: MetricVec{
- children: map[uint64]Metric{},
- desc: desc,
- hash: fnv.New64a(),
- newMetric: func(lvs ...string) Metric {
- return newValue(desc, UntypedValue, 0, lvs...)
- },
- },
+ MetricVec: newMetricVec(desc, func(lvs ...string) Metric {
+ return newValue(desc, UntypedValue, 0, lvs...)
+ }),
}
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/value.go b/vendor/github.com/prometheus/client_golang/prometheus/value.go
index b54ac11..a944c37 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/value.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/value.go
@@ -48,7 +48,7 @@ type value struct {
// operations. http://golang.org/pkg/sync/atomic/#pkg-note-BUG
valBits uint64
- SelfCollector
+ selfCollector
desc *Desc
valType ValueType
@@ -68,7 +68,7 @@ func newValue(desc *Desc, valueType ValueType, val float64, labelValues ...strin
valBits: math.Float64bits(val),
labelPairs: makeLabelPairs(desc, labelValues),
}
- result.Init(result)
+ result.init(result)
return result
}
@@ -113,7 +113,7 @@ func (v *value) Write(out *dto.Metric) error {
// library to back the implementations of CounterFunc, GaugeFunc, and
// UntypedFunc.
type valueFunc struct {
- SelfCollector
+ selfCollector
desc *Desc
valType ValueType
@@ -134,7 +134,7 @@ func newValueFunc(desc *Desc, valueType ValueType, function func() float64) *val
function: function,
labelPairs: makeLabelPairs(desc, nil),
}
- result.Init(result)
+ result.init(result)
return result
}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/vec.go b/vendor/github.com/prometheus/client_golang/prometheus/vec.go
index aa49deb..7f3eef9 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/vec.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/vec.go
@@ -14,10 +14,10 @@
package prometheus
import (
- "bytes"
"fmt"
- "hash"
"sync"
+
+ "github.com/prometheus/common/model"
)
// MetricVec is a Collector to bundle metrics of the same name that
@@ -26,17 +26,32 @@ import (
// type. GaugeVec, CounterVec, SummaryVec, and UntypedVec are examples already
// provided in this package.
type MetricVec struct {
- mtx sync.RWMutex // Protects not only children, but also hash and buf.
- children map[uint64]Metric
+ mtx sync.RWMutex // Protects the children.
+ children map[uint64][]metricWithLabelValues
desc *Desc
- // hash is our own hash instance to avoid repeated allocations.
- hash hash.Hash64
- // buf is used to copy string contents into it for hashing,
- // again to avoid allocations.
- buf bytes.Buffer
+ newMetric func(labelValues ...string) Metric
+ hashAdd func(h uint64, s string) uint64 // replace hash function for testing collision handling
+ hashAddByte func(h uint64, b byte) uint64
+}
- newMetric func(labelValues ...string) Metric
+// newMetricVec returns an initialized MetricVec. The concrete value is
+// returned for embedding into another struct.
+func newMetricVec(desc *Desc, newMetric func(lvs ...string) Metric) *MetricVec {
+ return &MetricVec{
+ children: map[uint64][]metricWithLabelValues{},
+ desc: desc,
+ newMetric: newMetric,
+ hashAdd: hashAdd,
+ hashAddByte: hashAddByte,
+ }
+}
+
+// metricWithLabelValues provides the metric and its label values for
+// disambiguation on hash collision.
+type metricWithLabelValues struct {
+ values []string
+ metric Metric
}
// Describe implements Collector. The length of the returned slice
@@ -50,14 +65,21 @@ func (m *MetricVec) Collect(ch chan<- Metric) {
m.mtx.RLock()
defer m.mtx.RUnlock()
- for _, metric := range m.children {
- ch <- metric
+ for _, metrics := range m.children {
+ for _, metric := range metrics {
+ ch <- metric.metric
+ }
}
}
// GetMetricWithLabelValues returns the Metric for the given slice of label
// values (same order as the VariableLabels in Desc). If that combination of
// label values is accessed for the first time, a new Metric is created.
+//
+// It is possible to call this method without using the returned Metric to only
+// create the new Metric but leave it at its start value (e.g. a Summary or
+// Histogram without any observations). See also the SummaryVec example.
+//
// Keeping the Metric for later use is possible (and should be considered if
// performance is critical), but keep in mind that Reset, DeleteLabelValues and
// Delete can be used to delete the Metric from the MetricVec. In that case, the
@@ -75,20 +97,19 @@ func (m *MetricVec) Collect(ch chan<- Metric) {
// with a performance overhead (for creating and processing the Labels map).
// See also the GaugeVec example.
func (m *MetricVec) GetMetricWithLabelValues(lvs ...string) (Metric, error) {
- m.mtx.Lock()
- defer m.mtx.Unlock()
-
h, err := m.hashLabelValues(lvs)
if err != nil {
return nil, err
}
- return m.getOrCreateMetric(h, lvs...), nil
+
+ return m.getOrCreateMetricWithLabelValues(h, lvs), nil
}
// GetMetricWith returns the Metric for the given Labels map (the label names
// must match those of the VariableLabels in Desc). If that label map is
-// accessed for the first time, a new Metric is created. Implications of keeping
-// the Metric are the same as for GetMetricWithLabelValues.
+// accessed for the first time, a new Metric is created. Implications of
+// creating a Metric without using it and keeping the Metric for later use are
+// the same as for GetMetricWithLabelValues.
//
// An error is returned if the number and names of the Labels are inconsistent
// with those of the VariableLabels in Desc.
@@ -97,18 +118,12 @@ func (m *MetricVec) GetMetricWithLabelValues(lvs ...string) (Metric, error) {
// GetMetricWithLabelValues(...string). See there for pros and cons of the two
// methods.
func (m *MetricVec) GetMetricWith(labels Labels) (Metric, error) {
- m.mtx.Lock()
- defer m.mtx.Unlock()
-
h, err := m.hashLabels(labels)
if err != nil {
return nil, err
}
- lvs := make([]string, len(labels))
- for i, label := range m.desc.variableLabels {
- lvs[i] = labels[label]
- }
- return m.getOrCreateMetric(h, lvs...), nil
+
+ return m.getOrCreateMetricWithLabels(h, labels), nil
}
// WithLabelValues works as GetMetricWithLabelValues, but panics if an error
@@ -156,11 +171,7 @@ func (m *MetricVec) DeleteLabelValues(lvs ...string) bool {
if err != nil {
return false
}
- if _, has := m.children[h]; !has {
- return false
- }
- delete(m.children, h)
- return true
+ return m.deleteByHashWithLabelValues(h, lvs)
}
// Delete deletes the metric where the variable labels are the same as those
@@ -181,10 +192,50 @@ func (m *MetricVec) Delete(labels Labels) bool {
if err != nil {
return false
}
- if _, has := m.children[h]; !has {
+
+ return m.deleteByHashWithLabels(h, labels)
+}
+
+// deleteByHashWithLabelValues removes the metric from the hash bucket h. If
+// there are multiple matches in the bucket, use lvs to select a metric and
+// remove only that metric.
+func (m *MetricVec) deleteByHashWithLabelValues(h uint64, lvs []string) bool {
+ metrics, ok := m.children[h]
+ if !ok {
return false
}
- delete(m.children, h)
+
+ i := m.findMetricWithLabelValues(metrics, lvs)
+ if i >= len(metrics) {
+ return false
+ }
+
+ if len(metrics) > 1 {
+ m.children[h] = append(metrics[:i], metrics[i+1:]...)
+ } else {
+ delete(m.children, h)
+ }
+ return true
+}
+
+// deleteByHashWithLabels removes the metric from the hash bucket h. If there
+// are multiple matches in the bucket, use lvs to select a metric and remove
+// only that metric.
+func (m *MetricVec) deleteByHashWithLabels(h uint64, labels Labels) bool {
+ metrics, ok := m.children[h]
+ if !ok {
+ return false
+ }
+ i := m.findMetricWithLabels(metrics, labels)
+ if i >= len(metrics) {
+ return false
+ }
+
+ if len(metrics) > 1 {
+ m.children[h] = append(metrics[:i], metrics[i+1:]...)
+ } else {
+ delete(m.children, h)
+ }
return true
}
@@ -202,40 +253,152 @@ func (m *MetricVec) hashLabelValues(vals []string) (uint64, error) {
if len(vals) != len(m.desc.variableLabels) {
return 0, errInconsistentCardinality
}
- m.hash.Reset()
+ h := hashNew()
for _, val := range vals {
- m.buf.Reset()
- m.buf.WriteString(val)
- m.hash.Write(m.buf.Bytes())
+ h = m.hashAdd(h, val)
+ h = m.hashAddByte(h, model.SeparatorByte)
}
- return m.hash.Sum64(), nil
+ return h, nil
}
func (m *MetricVec) hashLabels(labels Labels) (uint64, error) {
if len(labels) != len(m.desc.variableLabels) {
return 0, errInconsistentCardinality
}
- m.hash.Reset()
+ h := hashNew()
for _, label := range m.desc.variableLabels {
val, ok := labels[label]
if !ok {
return 0, fmt.Errorf("label name %q missing in label map", label)
}
- m.buf.Reset()
- m.buf.WriteString(val)
- m.hash.Write(m.buf.Bytes())
+ h = m.hashAdd(h, val)
+ h = m.hashAddByte(h, model.SeparatorByte)
}
- return m.hash.Sum64(), nil
+ return h, nil
}
-func (m *MetricVec) getOrCreateMetric(hash uint64, labelValues ...string) Metric {
- metric, ok := m.children[hash]
+// getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
+// or creates it and returns the new one.
+//
+// This function holds the mutex.
+func (m *MetricVec) getOrCreateMetricWithLabelValues(hash uint64, lvs []string) Metric {
+ m.mtx.RLock()
+ metric, ok := m.getMetricWithLabelValues(hash, lvs)
+ m.mtx.RUnlock()
+ if ok {
+ return metric
+ }
+
+ m.mtx.Lock()
+ defer m.mtx.Unlock()
+ metric, ok = m.getMetricWithLabelValues(hash, lvs)
if !ok {
- // Copy labelValues. Otherwise, they would be allocated even if we don't go
- // down this code path.
- copiedLabelValues := append(make([]string, 0, len(labelValues)), labelValues...)
- metric = m.newMetric(copiedLabelValues...)
- m.children[hash] = metric
+ // Copy to avoid allocation in case wo don't go down this code path.
+ copiedLVs := make([]string, len(lvs))
+ copy(copiedLVs, lvs)
+ metric = m.newMetric(copiedLVs...)
+ m.children[hash] = append(m.children[hash], metricWithLabelValues{values: copiedLVs, metric: metric})
}
return metric
}
+
+// getOrCreateMetricWithLabelValues retrieves the metric by hash and label value
+// or creates it and returns the new one.
+//
+// This function holds the mutex.
+func (m *MetricVec) getOrCreateMetricWithLabels(hash uint64, labels Labels) Metric {
+ m.mtx.RLock()
+ metric, ok := m.getMetricWithLabels(hash, labels)
+ m.mtx.RUnlock()
+ if ok {
+ return metric
+ }
+
+ m.mtx.Lock()
+ defer m.mtx.Unlock()
+ metric, ok = m.getMetricWithLabels(hash, labels)
+ if !ok {
+ lvs := m.extractLabelValues(labels)
+ metric = m.newMetric(lvs...)
+ m.children[hash] = append(m.children[hash], metricWithLabelValues{values: lvs, metric: metric})
+ }
+ return metric
+}
+
+// getMetricWithLabelValues gets a metric while handling possible collisions in
+// the hash space. Must be called while holding read mutex.
+func (m *MetricVec) getMetricWithLabelValues(h uint64, lvs []string) (Metric, bool) {
+ metrics, ok := m.children[h]
+ if ok {
+ if i := m.findMetricWithLabelValues(metrics, lvs); i < len(metrics) {
+ return metrics[i].metric, true
+ }
+ }
+ return nil, false
+}
+
+// getMetricWithLabels gets a metric while handling possible collisions in
+// the hash space. Must be called while holding read mutex.
+func (m *MetricVec) getMetricWithLabels(h uint64, labels Labels) (Metric, bool) {
+ metrics, ok := m.children[h]
+ if ok {
+ if i := m.findMetricWithLabels(metrics, labels); i < len(metrics) {
+ return metrics[i].metric, true
+ }
+ }
+ return nil, false
+}
+
+// findMetricWithLabelValues returns the index of the matching metric or
+// len(metrics) if not found.
+func (m *MetricVec) findMetricWithLabelValues(metrics []metricWithLabelValues, lvs []string) int {
+ for i, metric := range metrics {
+ if m.matchLabelValues(metric.values, lvs) {
+ return i
+ }
+ }
+ return len(metrics)
+}
+
+// findMetricWithLabels returns the index of the matching metric or len(metrics)
+// if not found.
+func (m *MetricVec) findMetricWithLabels(metrics []metricWithLabelValues, labels Labels) int {
+ for i, metric := range metrics {
+ if m.matchLabels(metric.values, labels) {
+ return i
+ }
+ }
+ return len(metrics)
+}
+
+func (m *MetricVec) matchLabelValues(values []string, lvs []string) bool {
+ if len(values) != len(lvs) {
+ return false
+ }
+ for i, v := range values {
+ if v != lvs[i] {
+ return false
+ }
+ }
+ return true
+}
+
+func (m *MetricVec) matchLabels(values []string, labels Labels) bool {
+ if len(labels) != len(values) {
+ return false
+ }
+ for i, k := range m.desc.variableLabels {
+ if values[i] != labels[k] {
+ return false
+ }
+ }
+ return true
+}
+
+func (m *MetricVec) extractLabelValues(labels Labels) []string {
+ labelValues := make([]string, len(labels))
+ for i, k := range m.desc.variableLabels {
+ labelValues[i] = labels[k]
+ }
+ return labelValues
+}
diff --git a/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go b/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go
index 0e9431e..445a6b3 100644
--- a/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go
+++ b/vendor/github.com/prometheus/client_golang/prometheus/vec_test.go
@@ -14,21 +14,37 @@
package prometheus
import (
- "hash/fnv"
+ "fmt"
"testing"
+
+ dto "github.com/prometheus/client_model/go"
)
func TestDelete(t *testing.T) {
- desc := NewDesc("test", "helpless", []string{"l1", "l2"}, nil)
- vec := MetricVec{
- children: map[uint64]Metric{},
- desc: desc,
- hash: fnv.New64a(),
- newMetric: func(lvs ...string) Metric {
- return newValue(desc, UntypedValue, 0, lvs...)
+ vec := NewUntypedVec(
+ UntypedOpts{
+ Name: "test",
+ Help: "helpless",
},
- }
+ []string{"l1", "l2"},
+ )
+ testDelete(t, vec)
+}
+func TestDeleteWithCollisions(t *testing.T) {
+ vec := NewUntypedVec(
+ UntypedOpts{
+ Name: "test",
+ Help: "helpless",
+ },
+ []string{"l1", "l2"},
+ )
+ vec.hashAdd = func(h uint64, s string) uint64 { return 1 }
+ vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 }
+ testDelete(t, vec)
+}
+
+func testDelete(t *testing.T, vec *UntypedVec) {
if got, want := vec.Delete(Labels{"l1": "v1", "l2": "v2"}), false; got != want {
t.Errorf("got %v, want %v", got, want)
}
@@ -59,29 +75,48 @@ func TestDelete(t *testing.T) {
}
func TestDeleteLabelValues(t *testing.T) {
- desc := NewDesc("test", "helpless", []string{"l1", "l2"}, nil)
- vec := MetricVec{
- children: map[uint64]Metric{},
- desc: desc,
- hash: fnv.New64a(),
- newMetric: func(lvs ...string) Metric {
- return newValue(desc, UntypedValue, 0, lvs...)
+ vec := NewUntypedVec(
+ UntypedOpts{
+ Name: "test",
+ Help: "helpless",
},
- }
+ []string{"l1", "l2"},
+ )
+ testDeleteLabelValues(t, vec)
+}
+func TestDeleteLabelValuesWithCollisions(t *testing.T) {
+ vec := NewUntypedVec(
+ UntypedOpts{
+ Name: "test",
+ Help: "helpless",
+ },
+ []string{"l1", "l2"},
+ )
+ vec.hashAdd = func(h uint64, s string) uint64 { return 1 }
+ vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 }
+ testDeleteLabelValues(t, vec)
+}
+
+func testDeleteLabelValues(t *testing.T, vec *UntypedVec) {
if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want {
t.Errorf("got %v, want %v", got, want)
}
vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42)
+ vec.With(Labels{"l1": "v1", "l2": "v3"}).(Untyped).Set(42) // Add junk data for collision.
if got, want := vec.DeleteLabelValues("v1", "v2"), true; got != want {
t.Errorf("got %v, want %v", got, want)
}
if got, want := vec.DeleteLabelValues("v1", "v2"), false; got != want {
t.Errorf("got %v, want %v", got, want)
}
+ if got, want := vec.DeleteLabelValues("v1", "v3"), true; got != want {
+ t.Errorf("got %v, want %v", got, want)
+ }
vec.With(Labels{"l1": "v1", "l2": "v2"}).(Untyped).Set(42)
+ // Delete out of order.
if got, want := vec.DeleteLabelValues("v2", "v1"), false; got != want {
t.Errorf("got %v, want %v", got, want)
}
@@ -89,3 +124,189 @@ func TestDeleteLabelValues(t *testing.T) {
t.Errorf("got %v, want %v", got, want)
}
}
+
+func TestMetricVec(t *testing.T) {
+ vec := NewUntypedVec(
+ UntypedOpts{
+ Name: "test",
+ Help: "helpless",
+ },
+ []string{"l1", "l2"},
+ )
+ testMetricVec(t, vec)
+}
+
+func TestMetricVecWithCollisions(t *testing.T) {
+ vec := NewUntypedVec(
+ UntypedOpts{
+ Name: "test",
+ Help: "helpless",
+ },
+ []string{"l1", "l2"},
+ )
+ vec.hashAdd = func(h uint64, s string) uint64 { return 1 }
+ vec.hashAddByte = func(h uint64, b byte) uint64 { return 1 }
+ testMetricVec(t, vec)
+}
+
+func testMetricVec(t *testing.T, vec *UntypedVec) {
+ vec.Reset() // Actually test Reset now!
+
+ var pair [2]string
+ // Keep track of metrics.
+ expected := map[[2]string]int{}
+
+ for i := 0; i < 1000; i++ {
+ pair[0], pair[1] = fmt.Sprint(i%4), fmt.Sprint(i%5) // Varying combinations multiples.
+ expected[pair]++
+ vec.WithLabelValues(pair[0], pair[1]).Inc()
+
+ expected[[2]string{"v1", "v2"}]++
+ vec.WithLabelValues("v1", "v2").(Untyped).Inc()
+ }
+
+ var total int
+ for _, metrics := range vec.children {
+ for _, metric := range metrics {
+ total++
+ copy(pair[:], metric.values)
+
+ var metricOut dto.Metric
+ if err := metric.metric.Write(&metricOut); err != nil {
+ t.Fatal(err)
+ }
+ actual := *metricOut.Untyped.Value
+
+ var actualPair [2]string
+ for i, label := range metricOut.Label {
+ actualPair[i] = *label.Value
+ }
+
+ // Test output pair against metric.values to ensure we've selected
+ // the right one. We check this to ensure the below check means
+ // anything at all.
+ if actualPair != pair {
+ t.Fatalf("unexpected pair association in metric map: %v != %v", actualPair, pair)
+ }
+
+ if actual != float64(expected[pair]) {
+ t.Fatalf("incorrect counter value for %v: %v != %v", pair, actual, expected[pair])
+ }
+ }
+ }
+
+ if total != len(expected) {
+ t.Fatalf("unexpected number of metrics: %v != %v", total, len(expected))
+ }
+
+ vec.Reset()
+
+ if len(vec.children) > 0 {
+ t.Fatalf("reset failed")
+ }
+}
+
+func TestCounterVecEndToEndWithCollision(t *testing.T) {
+ vec := NewCounterVec(
+ CounterOpts{
+ Name: "test",
+ Help: "helpless",
+ },
+ []string{"labelname"},
+ )
+ vec.WithLabelValues("77kepQFQ8Kl").Inc()
+ vec.WithLabelValues("!0IC=VloaY").Add(2)
+
+ m := &dto.Metric{}
+ if err := vec.WithLabelValues("77kepQFQ8Kl").Write(m); err != nil {
+ t.Fatal(err)
+ }
+ if got, want := m.GetLabel()[0].GetValue(), "77kepQFQ8Kl"; got != want {
+ t.Errorf("got label value %q, want %q", got, want)
+ }
+ if got, want := m.GetCounter().GetValue(), 1.; got != want {
+ t.Errorf("got value %f, want %f", got, want)
+ }
+ m.Reset()
+ if err := vec.WithLabelValues("!0IC=VloaY").Write(m); err != nil {
+ t.Fatal(err)
+ }
+ if got, want := m.GetLabel()[0].GetValue(), "!0IC=VloaY"; got != want {
+ t.Errorf("got label value %q, want %q", got, want)
+ }
+ if got, want := m.GetCounter().GetValue(), 2.; got != want {
+ t.Errorf("got value %f, want %f", got, want)
+ }
+}
+
+func BenchmarkMetricVecWithLabelValuesBasic(b *testing.B) {
+ benchmarkMetricVecWithLabelValues(b, map[string][]string{
+ "l1": []string{"onevalue"},
+ "l2": []string{"twovalue"},
+ })
+}
+
+func BenchmarkMetricVecWithLabelValues2Keys10ValueCardinality(b *testing.B) {
+ benchmarkMetricVecWithLabelValuesCardinality(b, 2, 10)
+}
+
+func BenchmarkMetricVecWithLabelValues4Keys10ValueCardinality(b *testing.B) {
+ benchmarkMetricVecWithLabelValuesCardinality(b, 4, 10)
+}
+
+func BenchmarkMetricVecWithLabelValues2Keys100ValueCardinality(b *testing.B) {
+ benchmarkMetricVecWithLabelValuesCardinality(b, 2, 100)
+}
+
+func BenchmarkMetricVecWithLabelValues10Keys100ValueCardinality(b *testing.B) {
+ benchmarkMetricVecWithLabelValuesCardinality(b, 10, 100)
+}
+
+func BenchmarkMetricVecWithLabelValues10Keys1000ValueCardinality(b *testing.B) {
+ benchmarkMetricVecWithLabelValuesCardinality(b, 10, 1000)
+}
+
+func benchmarkMetricVecWithLabelValuesCardinality(b *testing.B, nkeys, nvalues int) {
+ labels := map[string][]string{}
+
+ for i := 0; i < nkeys; i++ {
+ var (
+ k = fmt.Sprintf("key-%v", i)
+ vs = make([]string, 0, nvalues)
+ )
+ for j := 0; j < nvalues; j++ {
+ vs = append(vs, fmt.Sprintf("value-%v", j))
+ }
+ labels[k] = vs
+ }
+
+ benchmarkMetricVecWithLabelValues(b, labels)
+}
+
+func benchmarkMetricVecWithLabelValues(b *testing.B, labels map[string][]string) {
+ var keys []string
+ for k := range labels { // Map order dependent, who cares though.
+ keys = append(keys, k)
+ }
+
+ values := make([]string, len(labels)) // Value cache for permutations.
+ vec := NewUntypedVec(
+ UntypedOpts{
+ Name: "test",
+ Help: "helpless",
+ },
+ keys,
+ )
+
+ b.ReportAllocs()
+ b.ResetTimer()
+ for i := 0; i < b.N; i++ {
+ // Varies input across provide map entries based on key size.
+ for j, k := range keys {
+ candidates := labels[k]
+ values[j] = candidates[i%len(candidates)]
+ }
+
+ vec.WithLabelValues(values...)
+ }
+}
diff --git a/vendor/github.com/prometheus/client_golang/text/proto.go b/vendor/github.com/prometheus/client_golang/text/proto.go
deleted file mode 100644
index e82bbb3..0000000
--- a/vendor/github.com/prometheus/client_golang/text/proto.go
+++ /dev/null
@@ -1,43 +0,0 @@
-// Copyright 2014 The Prometheus Authors
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package text
-
-import (
- "fmt"
- "io"
-
- "github.com/golang/protobuf/proto"
- "github.com/matttproud/golang_protobuf_extensions/pbutil"
-
- dto "github.com/prometheus/client_model/go"
-)
-
-// WriteProtoDelimited writes the MetricFamily to the writer in delimited
-// protobuf format and returns the number of bytes written and any error
-// encountered.
-func WriteProtoDelimited(w io.Writer, p *dto.MetricFamily) (int, error) {
- return pbutil.WriteDelimited(w, p)
-}
-
-// WriteProtoText writes the MetricFamily to the writer in text format and
-// returns the number of bytes written and any error encountered.
-func WriteProtoText(w io.Writer, p *dto.MetricFamily) (int, error) {
- return fmt.Fprintf(w, "%s\n", proto.MarshalTextString(p))
-}
-
-// WriteProtoCompactText writes the MetricFamily to the writer in compact text
-// format and returns the number of bytes written and any error encountered.
-func WriteProtoCompactText(w io.Writer, p *dto.MetricFamily) (int, error) {
- return fmt.Fprintf(w, "%s\n", p)
-}
diff --git a/vendor/github.com/prometheus/client_model/.gitignore b/vendor/github.com/prometheus/client_model/.gitignore
new file mode 100644
index 0000000..2f7896d
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/.gitignore
@@ -0,0 +1 @@
+target/
diff --git a/vendor/github.com/prometheus/client_model/CONTRIBUTING.md b/vendor/github.com/prometheus/client_model/CONTRIBUTING.md
new file mode 100644
index 0000000..40503ed
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/CONTRIBUTING.md
@@ -0,0 +1,18 @@
+# Contributing
+
+Prometheus uses GitHub to manage reviews of pull requests.
+
+* If you have a trivial fix or improvement, go ahead and create a pull request,
+ addressing (with `@...`) the maintainer of this repository (see
+ [MAINTAINERS.md](MAINTAINERS.md)) in the description of the pull request.
+
+* If you plan to do something more involved, first discuss your ideas
+ on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers).
+ This will avoid unnecessary work and surely give you and us a good deal
+ of inspiration.
+
+* Relevant coding style guidelines are the [Go Code Review
+ Comments](https://code.google.com/p/go-wiki/wiki/CodeReviewComments)
+ and the _Formatting and style_ section of Peter Bourgon's [Go: Best
+ Practices for Production
+ Environments](http://peter.bourgon.org/go-in-production/#formatting-and-style).
diff --git a/vendor/github.com/prometheus/client_model/LICENSE b/vendor/github.com/prometheus/client_model/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/prometheus/client_model/MAINTAINERS.md b/vendor/github.com/prometheus/client_model/MAINTAINERS.md
new file mode 100644
index 0000000..3ede55f
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/MAINTAINERS.md
@@ -0,0 +1 @@
+* Björn Rabenstein
diff --git a/vendor/github.com/prometheus/client_model/Makefile b/vendor/github.com/prometheus/client_model/Makefile
new file mode 100644
index 0000000..9cc23b3
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/Makefile
@@ -0,0 +1,61 @@
+# Copyright 2013 Prometheus Team
+# 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.
+
+KEY_ID ?= _DEFINE_ME_
+
+all: cpp go java python ruby
+
+SUFFIXES:
+
+cpp: cpp/metrics.pb.cc cpp/metrics.pb.h
+
+cpp/metrics.pb.cc: metrics.proto
+ protoc $< --cpp_out=cpp/
+
+cpp/metrics.pb.h: metrics.proto
+ protoc $< --cpp_out=cpp/
+
+go: go/metrics.pb.go
+
+go/metrics.pb.go: metrics.proto
+ protoc $< --go_out=go/
+
+java: src/main/java/io/prometheus/client/Metrics.java pom.xml
+ mvn clean compile package
+
+src/main/java/io/prometheus/client/Metrics.java: metrics.proto
+ protoc $< --java_out=src/main/java
+
+python: python/prometheus/client/model/metrics_pb2.py
+
+python/prometheus/client/model/metrics_pb2.py: metrics.proto
+ protoc $< --python_out=python/prometheus/client/model
+
+ruby:
+ $(MAKE) -C ruby build
+
+clean:
+ -rm -rf cpp/*
+ -rm -rf go/*
+ -rm -rf java/*
+ -rm -rf python/*
+ -$(MAKE) -C ruby clean
+ -mvn clean
+
+maven-deploy-snapshot: java
+ mvn clean deploy -Dgpg.keyname=$(KEY_ID) -DperformRelease=true
+
+maven-deploy-release: java
+ mvn clean release:clean release:prepare release:perform -Dgpg.keyname=$(KEY_ID) -DperformRelease=true
+
+.PHONY: all clean cpp go java maven-deploy-snapshot maven-deploy-release python ruby
diff --git a/vendor/github.com/prometheus/client_model/NOTICE b/vendor/github.com/prometheus/client_model/NOTICE
new file mode 100644
index 0000000..20110e4
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/NOTICE
@@ -0,0 +1,5 @@
+Data model artifacts for Prometheus.
+Copyright 2012-2015 The Prometheus Authors
+
+This product includes software developed at
+SoundCloud Ltd. (http://soundcloud.com/).
diff --git a/vendor/github.com/prometheus/client_model/README.md b/vendor/github.com/prometheus/client_model/README.md
new file mode 100644
index 0000000..a710042
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/README.md
@@ -0,0 +1,26 @@
+# Background
+Under most circumstances, manually downloading this repository should never
+be required.
+
+# Prerequisites
+# Base
+* [Google Protocol Buffers](https://developers.google.com/protocol-buffers)
+
+## Java
+* [Apache Maven](http://maven.apache.org)
+* [Prometheus Maven Repository](https://github.com/prometheus/io.prometheus-maven-repository) checked out into ../io.prometheus-maven-repository
+
+## Go
+* [Go](http://golang.org)
+* [goprotobuf](https://code.google.com/p/goprotobuf)
+
+## Ruby
+* [Ruby](https://www.ruby-lang.org)
+* [bundler](https://rubygems.org/gems/bundler)
+
+# Building
+ $ make
+
+# Getting Started
+ * The Go source code is periodically indexed: [Go Protocol Buffer Model](http://godoc.org/github.com/prometheus/client_model/go).
+ * All of the core developers are accessible via the [Prometheus Developers Mailinglist](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers).
diff --git a/vendor/github.com/prometheus/client_model/cpp/metrics.pb.cc b/vendor/github.com/prometheus/client_model/cpp/metrics.pb.cc
new file mode 100644
index 0000000..1ff893b
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/cpp/metrics.pb.cc
@@ -0,0 +1,3380 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: metrics.proto
+
+#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
+#include "metrics.pb.h"
+
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+// @@protoc_insertion_point(includes)
+
+namespace io {
+namespace prometheus {
+namespace client {
+
+namespace {
+
+const ::google::protobuf::Descriptor* LabelPair_descriptor_ = NULL;
+const ::google::protobuf::internal::GeneratedMessageReflection*
+ LabelPair_reflection_ = NULL;
+const ::google::protobuf::Descriptor* Gauge_descriptor_ = NULL;
+const ::google::protobuf::internal::GeneratedMessageReflection*
+ Gauge_reflection_ = NULL;
+const ::google::protobuf::Descriptor* Counter_descriptor_ = NULL;
+const ::google::protobuf::internal::GeneratedMessageReflection*
+ Counter_reflection_ = NULL;
+const ::google::protobuf::Descriptor* Quantile_descriptor_ = NULL;
+const ::google::protobuf::internal::GeneratedMessageReflection*
+ Quantile_reflection_ = NULL;
+const ::google::protobuf::Descriptor* Summary_descriptor_ = NULL;
+const ::google::protobuf::internal::GeneratedMessageReflection*
+ Summary_reflection_ = NULL;
+const ::google::protobuf::Descriptor* Untyped_descriptor_ = NULL;
+const ::google::protobuf::internal::GeneratedMessageReflection*
+ Untyped_reflection_ = NULL;
+const ::google::protobuf::Descriptor* Histogram_descriptor_ = NULL;
+const ::google::protobuf::internal::GeneratedMessageReflection*
+ Histogram_reflection_ = NULL;
+const ::google::protobuf::Descriptor* Bucket_descriptor_ = NULL;
+const ::google::protobuf::internal::GeneratedMessageReflection*
+ Bucket_reflection_ = NULL;
+const ::google::protobuf::Descriptor* Metric_descriptor_ = NULL;
+const ::google::protobuf::internal::GeneratedMessageReflection*
+ Metric_reflection_ = NULL;
+const ::google::protobuf::Descriptor* MetricFamily_descriptor_ = NULL;
+const ::google::protobuf::internal::GeneratedMessageReflection*
+ MetricFamily_reflection_ = NULL;
+const ::google::protobuf::EnumDescriptor* MetricType_descriptor_ = NULL;
+
+} // namespace
+
+
+void protobuf_AssignDesc_metrics_2eproto() {
+ protobuf_AddDesc_metrics_2eproto();
+ const ::google::protobuf::FileDescriptor* file =
+ ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
+ "metrics.proto");
+ GOOGLE_CHECK(file != NULL);
+ LabelPair_descriptor_ = file->message_type(0);
+ static const int LabelPair_offsets_[2] = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LabelPair, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LabelPair, value_),
+ };
+ LabelPair_reflection_ =
+ new ::google::protobuf::internal::GeneratedMessageReflection(
+ LabelPair_descriptor_,
+ LabelPair::default_instance_,
+ LabelPair_offsets_,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LabelPair, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(LabelPair, _unknown_fields_),
+ -1,
+ ::google::protobuf::DescriptorPool::generated_pool(),
+ ::google::protobuf::MessageFactory::generated_factory(),
+ sizeof(LabelPair));
+ Gauge_descriptor_ = file->message_type(1);
+ static const int Gauge_offsets_[1] = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Gauge, value_),
+ };
+ Gauge_reflection_ =
+ new ::google::protobuf::internal::GeneratedMessageReflection(
+ Gauge_descriptor_,
+ Gauge::default_instance_,
+ Gauge_offsets_,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Gauge, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Gauge, _unknown_fields_),
+ -1,
+ ::google::protobuf::DescriptorPool::generated_pool(),
+ ::google::protobuf::MessageFactory::generated_factory(),
+ sizeof(Gauge));
+ Counter_descriptor_ = file->message_type(2);
+ static const int Counter_offsets_[1] = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Counter, value_),
+ };
+ Counter_reflection_ =
+ new ::google::protobuf::internal::GeneratedMessageReflection(
+ Counter_descriptor_,
+ Counter::default_instance_,
+ Counter_offsets_,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Counter, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Counter, _unknown_fields_),
+ -1,
+ ::google::protobuf::DescriptorPool::generated_pool(),
+ ::google::protobuf::MessageFactory::generated_factory(),
+ sizeof(Counter));
+ Quantile_descriptor_ = file->message_type(3);
+ static const int Quantile_offsets_[2] = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantile, quantile_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantile, value_),
+ };
+ Quantile_reflection_ =
+ new ::google::protobuf::internal::GeneratedMessageReflection(
+ Quantile_descriptor_,
+ Quantile::default_instance_,
+ Quantile_offsets_,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantile, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Quantile, _unknown_fields_),
+ -1,
+ ::google::protobuf::DescriptorPool::generated_pool(),
+ ::google::protobuf::MessageFactory::generated_factory(),
+ sizeof(Quantile));
+ Summary_descriptor_ = file->message_type(4);
+ static const int Summary_offsets_[3] = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, sample_count_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, sample_sum_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, quantile_),
+ };
+ Summary_reflection_ =
+ new ::google::protobuf::internal::GeneratedMessageReflection(
+ Summary_descriptor_,
+ Summary::default_instance_,
+ Summary_offsets_,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Summary, _unknown_fields_),
+ -1,
+ ::google::protobuf::DescriptorPool::generated_pool(),
+ ::google::protobuf::MessageFactory::generated_factory(),
+ sizeof(Summary));
+ Untyped_descriptor_ = file->message_type(5);
+ static const int Untyped_offsets_[1] = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Untyped, value_),
+ };
+ Untyped_reflection_ =
+ new ::google::protobuf::internal::GeneratedMessageReflection(
+ Untyped_descriptor_,
+ Untyped::default_instance_,
+ Untyped_offsets_,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Untyped, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Untyped, _unknown_fields_),
+ -1,
+ ::google::protobuf::DescriptorPool::generated_pool(),
+ ::google::protobuf::MessageFactory::generated_factory(),
+ sizeof(Untyped));
+ Histogram_descriptor_ = file->message_type(6);
+ static const int Histogram_offsets_[3] = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, sample_count_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, sample_sum_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, bucket_),
+ };
+ Histogram_reflection_ =
+ new ::google::protobuf::internal::GeneratedMessageReflection(
+ Histogram_descriptor_,
+ Histogram::default_instance_,
+ Histogram_offsets_,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Histogram, _unknown_fields_),
+ -1,
+ ::google::protobuf::DescriptorPool::generated_pool(),
+ ::google::protobuf::MessageFactory::generated_factory(),
+ sizeof(Histogram));
+ Bucket_descriptor_ = file->message_type(7);
+ static const int Bucket_offsets_[2] = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Bucket, cumulative_count_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Bucket, upper_bound_),
+ };
+ Bucket_reflection_ =
+ new ::google::protobuf::internal::GeneratedMessageReflection(
+ Bucket_descriptor_,
+ Bucket::default_instance_,
+ Bucket_offsets_,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Bucket, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Bucket, _unknown_fields_),
+ -1,
+ ::google::protobuf::DescriptorPool::generated_pool(),
+ ::google::protobuf::MessageFactory::generated_factory(),
+ sizeof(Bucket));
+ Metric_descriptor_ = file->message_type(8);
+ static const int Metric_offsets_[7] = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, label_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, gauge_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, counter_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, summary_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, untyped_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, histogram_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, timestamp_ms_),
+ };
+ Metric_reflection_ =
+ new ::google::protobuf::internal::GeneratedMessageReflection(
+ Metric_descriptor_,
+ Metric::default_instance_,
+ Metric_offsets_,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Metric, _unknown_fields_),
+ -1,
+ ::google::protobuf::DescriptorPool::generated_pool(),
+ ::google::protobuf::MessageFactory::generated_factory(),
+ sizeof(Metric));
+ MetricFamily_descriptor_ = file->message_type(9);
+ static const int MetricFamily_offsets_[4] = {
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, name_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, help_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, type_),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, metric_),
+ };
+ MetricFamily_reflection_ =
+ new ::google::protobuf::internal::GeneratedMessageReflection(
+ MetricFamily_descriptor_,
+ MetricFamily::default_instance_,
+ MetricFamily_offsets_,
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, _has_bits_[0]),
+ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MetricFamily, _unknown_fields_),
+ -1,
+ ::google::protobuf::DescriptorPool::generated_pool(),
+ ::google::protobuf::MessageFactory::generated_factory(),
+ sizeof(MetricFamily));
+ MetricType_descriptor_ = file->enum_type(0);
+}
+
+namespace {
+
+GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
+inline void protobuf_AssignDescriptorsOnce() {
+ ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
+ &protobuf_AssignDesc_metrics_2eproto);
+}
+
+void protobuf_RegisterTypes(const ::std::string&) {
+ protobuf_AssignDescriptorsOnce();
+ ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
+ LabelPair_descriptor_, &LabelPair::default_instance());
+ ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
+ Gauge_descriptor_, &Gauge::default_instance());
+ ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
+ Counter_descriptor_, &Counter::default_instance());
+ ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
+ Quantile_descriptor_, &Quantile::default_instance());
+ ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
+ Summary_descriptor_, &Summary::default_instance());
+ ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
+ Untyped_descriptor_, &Untyped::default_instance());
+ ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
+ Histogram_descriptor_, &Histogram::default_instance());
+ ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
+ Bucket_descriptor_, &Bucket::default_instance());
+ ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
+ Metric_descriptor_, &Metric::default_instance());
+ ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
+ MetricFamily_descriptor_, &MetricFamily::default_instance());
+}
+
+} // namespace
+
+void protobuf_ShutdownFile_metrics_2eproto() {
+ delete LabelPair::default_instance_;
+ delete LabelPair_reflection_;
+ delete Gauge::default_instance_;
+ delete Gauge_reflection_;
+ delete Counter::default_instance_;
+ delete Counter_reflection_;
+ delete Quantile::default_instance_;
+ delete Quantile_reflection_;
+ delete Summary::default_instance_;
+ delete Summary_reflection_;
+ delete Untyped::default_instance_;
+ delete Untyped_reflection_;
+ delete Histogram::default_instance_;
+ delete Histogram_reflection_;
+ delete Bucket::default_instance_;
+ delete Bucket_reflection_;
+ delete Metric::default_instance_;
+ delete Metric_reflection_;
+ delete MetricFamily::default_instance_;
+ delete MetricFamily_reflection_;
+}
+
+void protobuf_AddDesc_metrics_2eproto() {
+ static bool already_here = false;
+ if (already_here) return;
+ already_here = true;
+ GOOGLE_PROTOBUF_VERIFY_VERSION;
+
+ ::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
+ "\n\rmetrics.proto\022\024io.prometheus.client\"(\n"
+ "\tLabelPair\022\014\n\004name\030\001 \001(\t\022\r\n\005value\030\002 \001(\t\""
+ "\026\n\005Gauge\022\r\n\005value\030\001 \001(\001\"\030\n\007Counter\022\r\n\005va"
+ "lue\030\001 \001(\001\"+\n\010Quantile\022\020\n\010quantile\030\001 \001(\001\022"
+ "\r\n\005value\030\002 \001(\001\"e\n\007Summary\022\024\n\014sample_coun"
+ "t\030\001 \001(\004\022\022\n\nsample_sum\030\002 \001(\001\0220\n\010quantile\030"
+ "\003 \003(\0132\036.io.prometheus.client.Quantile\"\030\n"
+ "\007Untyped\022\r\n\005value\030\001 \001(\001\"c\n\tHistogram\022\024\n\014"
+ "sample_count\030\001 \001(\004\022\022\n\nsample_sum\030\002 \001(\001\022,"
+ "\n\006bucket\030\003 \003(\0132\034.io.prometheus.client.Bu"
+ "cket\"7\n\006Bucket\022\030\n\020cumulative_count\030\001 \001(\004"
+ "\022\023\n\013upper_bound\030\002 \001(\001\"\276\002\n\006Metric\022.\n\005labe"
+ "l\030\001 \003(\0132\037.io.prometheus.client.LabelPair"
+ "\022*\n\005gauge\030\002 \001(\0132\033.io.prometheus.client.G"
+ "auge\022.\n\007counter\030\003 \001(\0132\035.io.prometheus.cl"
+ "ient.Counter\022.\n\007summary\030\004 \001(\0132\035.io.prome"
+ "theus.client.Summary\022.\n\007untyped\030\005 \001(\0132\035."
+ "io.prometheus.client.Untyped\0222\n\thistogra"
+ "m\030\007 \001(\0132\037.io.prometheus.client.Histogram"
+ "\022\024\n\014timestamp_ms\030\006 \001(\003\"\210\001\n\014MetricFamily\022"
+ "\014\n\004name\030\001 \001(\t\022\014\n\004help\030\002 \001(\t\022.\n\004type\030\003 \001("
+ "\0162 .io.prometheus.client.MetricType\022,\n\006m"
+ "etric\030\004 \003(\0132\034.io.prometheus.client.Metri"
+ "c*M\n\nMetricType\022\013\n\007COUNTER\020\000\022\t\n\005GAUGE\020\001\022"
+ "\013\n\007SUMMARY\020\002\022\013\n\007UNTYPED\020\003\022\r\n\tHISTOGRAM\020\004"
+ "B\026\n\024io.prometheus.client", 1024);
+ ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
+ "metrics.proto", &protobuf_RegisterTypes);
+ LabelPair::default_instance_ = new LabelPair();
+ Gauge::default_instance_ = new Gauge();
+ Counter::default_instance_ = new Counter();
+ Quantile::default_instance_ = new Quantile();
+ Summary::default_instance_ = new Summary();
+ Untyped::default_instance_ = new Untyped();
+ Histogram::default_instance_ = new Histogram();
+ Bucket::default_instance_ = new Bucket();
+ Metric::default_instance_ = new Metric();
+ MetricFamily::default_instance_ = new MetricFamily();
+ LabelPair::default_instance_->InitAsDefaultInstance();
+ Gauge::default_instance_->InitAsDefaultInstance();
+ Counter::default_instance_->InitAsDefaultInstance();
+ Quantile::default_instance_->InitAsDefaultInstance();
+ Summary::default_instance_->InitAsDefaultInstance();
+ Untyped::default_instance_->InitAsDefaultInstance();
+ Histogram::default_instance_->InitAsDefaultInstance();
+ Bucket::default_instance_->InitAsDefaultInstance();
+ Metric::default_instance_->InitAsDefaultInstance();
+ MetricFamily::default_instance_->InitAsDefaultInstance();
+ ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_metrics_2eproto);
+}
+
+// Force AddDescriptors() to be called at static initialization time.
+struct StaticDescriptorInitializer_metrics_2eproto {
+ StaticDescriptorInitializer_metrics_2eproto() {
+ protobuf_AddDesc_metrics_2eproto();
+ }
+} static_descriptor_initializer_metrics_2eproto_;
+const ::google::protobuf::EnumDescriptor* MetricType_descriptor() {
+ protobuf_AssignDescriptorsOnce();
+ return MetricType_descriptor_;
+}
+bool MetricType_IsValid(int value) {
+ switch(value) {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ return true;
+ default:
+ return false;
+ }
+}
+
+
+// ===================================================================
+
+#ifndef _MSC_VER
+const int LabelPair::kNameFieldNumber;
+const int LabelPair::kValueFieldNumber;
+#endif // !_MSC_VER
+
+LabelPair::LabelPair()
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ // @@protoc_insertion_point(constructor:io.prometheus.client.LabelPair)
+}
+
+void LabelPair::InitAsDefaultInstance() {
+}
+
+LabelPair::LabelPair(const LabelPair& from)
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ MergeFrom(from);
+ // @@protoc_insertion_point(copy_constructor:io.prometheus.client.LabelPair)
+}
+
+void LabelPair::SharedCtor() {
+ ::google::protobuf::internal::GetEmptyString();
+ _cached_size_ = 0;
+ name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ value_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+}
+
+LabelPair::~LabelPair() {
+ // @@protoc_insertion_point(destructor:io.prometheus.client.LabelPair)
+ SharedDtor();
+}
+
+void LabelPair::SharedDtor() {
+ if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ delete name_;
+ }
+ if (value_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ delete value_;
+ }
+ if (this != default_instance_) {
+ }
+}
+
+void LabelPair::SetCachedSize(int size) const {
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+}
+const ::google::protobuf::Descriptor* LabelPair::descriptor() {
+ protobuf_AssignDescriptorsOnce();
+ return LabelPair_descriptor_;
+}
+
+const LabelPair& LabelPair::default_instance() {
+ if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto();
+ return *default_instance_;
+}
+
+LabelPair* LabelPair::default_instance_ = NULL;
+
+LabelPair* LabelPair::New() const {
+ return new LabelPair;
+}
+
+void LabelPair::Clear() {
+ if (_has_bits_[0 / 32] & 3) {
+ if (has_name()) {
+ if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ name_->clear();
+ }
+ }
+ if (has_value()) {
+ if (value_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ value_->clear();
+ }
+ }
+ }
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ mutable_unknown_fields()->Clear();
+}
+
+bool LabelPair::MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
+ ::google::protobuf::uint32 tag;
+ // @@protoc_insertion_point(parse_start:io.prometheus.client.LabelPair)
+ for (;;) {
+ ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
+ tag = p.first;
+ if (!p.second) goto handle_unusual;
+ switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+ // optional string name = 1;
+ case 1: {
+ if (tag == 10) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadString(
+ input, this->mutable_name()));
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->name().data(), this->name().length(),
+ ::google::protobuf::internal::WireFormat::PARSE,
+ "name");
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(18)) goto parse_value;
+ break;
+ }
+
+ // optional string value = 2;
+ case 2: {
+ if (tag == 18) {
+ parse_value:
+ DO_(::google::protobuf::internal::WireFormatLite::ReadString(
+ input, this->mutable_value()));
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->value().data(), this->value().length(),
+ ::google::protobuf::internal::WireFormat::PARSE,
+ "value");
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectAtEnd()) goto success;
+ break;
+ }
+
+ default: {
+ handle_unusual:
+ if (tag == 0 ||
+ ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ goto success;
+ }
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, mutable_unknown_fields()));
+ break;
+ }
+ }
+ }
+success:
+ // @@protoc_insertion_point(parse_success:io.prometheus.client.LabelPair)
+ return true;
+failure:
+ // @@protoc_insertion_point(parse_failure:io.prometheus.client.LabelPair)
+ return false;
+#undef DO_
+}
+
+void LabelPair::SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const {
+ // @@protoc_insertion_point(serialize_start:io.prometheus.client.LabelPair)
+ // optional string name = 1;
+ if (has_name()) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->name().data(), this->name().length(),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "name");
+ ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
+ 1, this->name(), output);
+ }
+
+ // optional string value = 2;
+ if (has_value()) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->value().data(), this->value().length(),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "value");
+ ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
+ 2, this->value(), output);
+ }
+
+ if (!unknown_fields().empty()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ unknown_fields(), output);
+ }
+ // @@protoc_insertion_point(serialize_end:io.prometheus.client.LabelPair)
+}
+
+::google::protobuf::uint8* LabelPair::SerializeWithCachedSizesToArray(
+ ::google::protobuf::uint8* target) const {
+ // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.LabelPair)
+ // optional string name = 1;
+ if (has_name()) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->name().data(), this->name().length(),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "name");
+ target =
+ ::google::protobuf::internal::WireFormatLite::WriteStringToArray(
+ 1, this->name(), target);
+ }
+
+ // optional string value = 2;
+ if (has_value()) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->value().data(), this->value().length(),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "value");
+ target =
+ ::google::protobuf::internal::WireFormatLite::WriteStringToArray(
+ 2, this->value(), target);
+ }
+
+ if (!unknown_fields().empty()) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ unknown_fields(), target);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.LabelPair)
+ return target;
+}
+
+int LabelPair::ByteSize() const {
+ int total_size = 0;
+
+ if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ // optional string name = 1;
+ if (has_name()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::StringSize(
+ this->name());
+ }
+
+ // optional string value = 2;
+ if (has_value()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::StringSize(
+ this->value());
+ }
+
+ }
+ if (!unknown_fields().empty()) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ unknown_fields());
+ }
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = total_size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ return total_size;
+}
+
+void LabelPair::MergeFrom(const ::google::protobuf::Message& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ const LabelPair* source =
+ ::google::protobuf::internal::dynamic_cast_if_available(
+ &from);
+ if (source == NULL) {
+ ::google::protobuf::internal::ReflectionOps::Merge(from, this);
+ } else {
+ MergeFrom(*source);
+ }
+}
+
+void LabelPair::MergeFrom(const LabelPair& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ if (from.has_name()) {
+ set_name(from.name());
+ }
+ if (from.has_value()) {
+ set_value(from.value());
+ }
+ }
+ mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+}
+
+void LabelPair::CopyFrom(const ::google::protobuf::Message& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+void LabelPair::CopyFrom(const LabelPair& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool LabelPair::IsInitialized() const {
+
+ return true;
+}
+
+void LabelPair::Swap(LabelPair* other) {
+ if (other != this) {
+ std::swap(name_, other->name_);
+ std::swap(value_, other->value_);
+ std::swap(_has_bits_[0], other->_has_bits_[0]);
+ _unknown_fields_.Swap(&other->_unknown_fields_);
+ std::swap(_cached_size_, other->_cached_size_);
+ }
+}
+
+::google::protobuf::Metadata LabelPair::GetMetadata() const {
+ protobuf_AssignDescriptorsOnce();
+ ::google::protobuf::Metadata metadata;
+ metadata.descriptor = LabelPair_descriptor_;
+ metadata.reflection = LabelPair_reflection_;
+ return metadata;
+}
+
+
+// ===================================================================
+
+#ifndef _MSC_VER
+const int Gauge::kValueFieldNumber;
+#endif // !_MSC_VER
+
+Gauge::Gauge()
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ // @@protoc_insertion_point(constructor:io.prometheus.client.Gauge)
+}
+
+void Gauge::InitAsDefaultInstance() {
+}
+
+Gauge::Gauge(const Gauge& from)
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ MergeFrom(from);
+ // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Gauge)
+}
+
+void Gauge::SharedCtor() {
+ _cached_size_ = 0;
+ value_ = 0;
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+}
+
+Gauge::~Gauge() {
+ // @@protoc_insertion_point(destructor:io.prometheus.client.Gauge)
+ SharedDtor();
+}
+
+void Gauge::SharedDtor() {
+ if (this != default_instance_) {
+ }
+}
+
+void Gauge::SetCachedSize(int size) const {
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+}
+const ::google::protobuf::Descriptor* Gauge::descriptor() {
+ protobuf_AssignDescriptorsOnce();
+ return Gauge_descriptor_;
+}
+
+const Gauge& Gauge::default_instance() {
+ if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto();
+ return *default_instance_;
+}
+
+Gauge* Gauge::default_instance_ = NULL;
+
+Gauge* Gauge::New() const {
+ return new Gauge;
+}
+
+void Gauge::Clear() {
+ value_ = 0;
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ mutable_unknown_fields()->Clear();
+}
+
+bool Gauge::MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
+ ::google::protobuf::uint32 tag;
+ // @@protoc_insertion_point(parse_start:io.prometheus.client.Gauge)
+ for (;;) {
+ ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
+ tag = p.first;
+ if (!p.second) goto handle_unusual;
+ switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+ // optional double value = 1;
+ case 1: {
+ if (tag == 9) {
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
+ input, &value_)));
+ set_has_value();
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectAtEnd()) goto success;
+ break;
+ }
+
+ default: {
+ handle_unusual:
+ if (tag == 0 ||
+ ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ goto success;
+ }
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, mutable_unknown_fields()));
+ break;
+ }
+ }
+ }
+success:
+ // @@protoc_insertion_point(parse_success:io.prometheus.client.Gauge)
+ return true;
+failure:
+ // @@protoc_insertion_point(parse_failure:io.prometheus.client.Gauge)
+ return false;
+#undef DO_
+}
+
+void Gauge::SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const {
+ // @@protoc_insertion_point(serialize_start:io.prometheus.client.Gauge)
+ // optional double value = 1;
+ if (has_value()) {
+ ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->value(), output);
+ }
+
+ if (!unknown_fields().empty()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ unknown_fields(), output);
+ }
+ // @@protoc_insertion_point(serialize_end:io.prometheus.client.Gauge)
+}
+
+::google::protobuf::uint8* Gauge::SerializeWithCachedSizesToArray(
+ ::google::protobuf::uint8* target) const {
+ // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Gauge)
+ // optional double value = 1;
+ if (has_value()) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->value(), target);
+ }
+
+ if (!unknown_fields().empty()) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ unknown_fields(), target);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Gauge)
+ return target;
+}
+
+int Gauge::ByteSize() const {
+ int total_size = 0;
+
+ if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ // optional double value = 1;
+ if (has_value()) {
+ total_size += 1 + 8;
+ }
+
+ }
+ if (!unknown_fields().empty()) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ unknown_fields());
+ }
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = total_size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ return total_size;
+}
+
+void Gauge::MergeFrom(const ::google::protobuf::Message& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ const Gauge* source =
+ ::google::protobuf::internal::dynamic_cast_if_available(
+ &from);
+ if (source == NULL) {
+ ::google::protobuf::internal::ReflectionOps::Merge(from, this);
+ } else {
+ MergeFrom(*source);
+ }
+}
+
+void Gauge::MergeFrom(const Gauge& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ if (from.has_value()) {
+ set_value(from.value());
+ }
+ }
+ mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+}
+
+void Gauge::CopyFrom(const ::google::protobuf::Message& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+void Gauge::CopyFrom(const Gauge& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool Gauge::IsInitialized() const {
+
+ return true;
+}
+
+void Gauge::Swap(Gauge* other) {
+ if (other != this) {
+ std::swap(value_, other->value_);
+ std::swap(_has_bits_[0], other->_has_bits_[0]);
+ _unknown_fields_.Swap(&other->_unknown_fields_);
+ std::swap(_cached_size_, other->_cached_size_);
+ }
+}
+
+::google::protobuf::Metadata Gauge::GetMetadata() const {
+ protobuf_AssignDescriptorsOnce();
+ ::google::protobuf::Metadata metadata;
+ metadata.descriptor = Gauge_descriptor_;
+ metadata.reflection = Gauge_reflection_;
+ return metadata;
+}
+
+
+// ===================================================================
+
+#ifndef _MSC_VER
+const int Counter::kValueFieldNumber;
+#endif // !_MSC_VER
+
+Counter::Counter()
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ // @@protoc_insertion_point(constructor:io.prometheus.client.Counter)
+}
+
+void Counter::InitAsDefaultInstance() {
+}
+
+Counter::Counter(const Counter& from)
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ MergeFrom(from);
+ // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Counter)
+}
+
+void Counter::SharedCtor() {
+ _cached_size_ = 0;
+ value_ = 0;
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+}
+
+Counter::~Counter() {
+ // @@protoc_insertion_point(destructor:io.prometheus.client.Counter)
+ SharedDtor();
+}
+
+void Counter::SharedDtor() {
+ if (this != default_instance_) {
+ }
+}
+
+void Counter::SetCachedSize(int size) const {
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+}
+const ::google::protobuf::Descriptor* Counter::descriptor() {
+ protobuf_AssignDescriptorsOnce();
+ return Counter_descriptor_;
+}
+
+const Counter& Counter::default_instance() {
+ if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto();
+ return *default_instance_;
+}
+
+Counter* Counter::default_instance_ = NULL;
+
+Counter* Counter::New() const {
+ return new Counter;
+}
+
+void Counter::Clear() {
+ value_ = 0;
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ mutable_unknown_fields()->Clear();
+}
+
+bool Counter::MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
+ ::google::protobuf::uint32 tag;
+ // @@protoc_insertion_point(parse_start:io.prometheus.client.Counter)
+ for (;;) {
+ ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
+ tag = p.first;
+ if (!p.second) goto handle_unusual;
+ switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+ // optional double value = 1;
+ case 1: {
+ if (tag == 9) {
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
+ input, &value_)));
+ set_has_value();
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectAtEnd()) goto success;
+ break;
+ }
+
+ default: {
+ handle_unusual:
+ if (tag == 0 ||
+ ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ goto success;
+ }
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, mutable_unknown_fields()));
+ break;
+ }
+ }
+ }
+success:
+ // @@protoc_insertion_point(parse_success:io.prometheus.client.Counter)
+ return true;
+failure:
+ // @@protoc_insertion_point(parse_failure:io.prometheus.client.Counter)
+ return false;
+#undef DO_
+}
+
+void Counter::SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const {
+ // @@protoc_insertion_point(serialize_start:io.prometheus.client.Counter)
+ // optional double value = 1;
+ if (has_value()) {
+ ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->value(), output);
+ }
+
+ if (!unknown_fields().empty()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ unknown_fields(), output);
+ }
+ // @@protoc_insertion_point(serialize_end:io.prometheus.client.Counter)
+}
+
+::google::protobuf::uint8* Counter::SerializeWithCachedSizesToArray(
+ ::google::protobuf::uint8* target) const {
+ // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Counter)
+ // optional double value = 1;
+ if (has_value()) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->value(), target);
+ }
+
+ if (!unknown_fields().empty()) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ unknown_fields(), target);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Counter)
+ return target;
+}
+
+int Counter::ByteSize() const {
+ int total_size = 0;
+
+ if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ // optional double value = 1;
+ if (has_value()) {
+ total_size += 1 + 8;
+ }
+
+ }
+ if (!unknown_fields().empty()) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ unknown_fields());
+ }
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = total_size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ return total_size;
+}
+
+void Counter::MergeFrom(const ::google::protobuf::Message& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ const Counter* source =
+ ::google::protobuf::internal::dynamic_cast_if_available(
+ &from);
+ if (source == NULL) {
+ ::google::protobuf::internal::ReflectionOps::Merge(from, this);
+ } else {
+ MergeFrom(*source);
+ }
+}
+
+void Counter::MergeFrom(const Counter& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ if (from.has_value()) {
+ set_value(from.value());
+ }
+ }
+ mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+}
+
+void Counter::CopyFrom(const ::google::protobuf::Message& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+void Counter::CopyFrom(const Counter& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool Counter::IsInitialized() const {
+
+ return true;
+}
+
+void Counter::Swap(Counter* other) {
+ if (other != this) {
+ std::swap(value_, other->value_);
+ std::swap(_has_bits_[0], other->_has_bits_[0]);
+ _unknown_fields_.Swap(&other->_unknown_fields_);
+ std::swap(_cached_size_, other->_cached_size_);
+ }
+}
+
+::google::protobuf::Metadata Counter::GetMetadata() const {
+ protobuf_AssignDescriptorsOnce();
+ ::google::protobuf::Metadata metadata;
+ metadata.descriptor = Counter_descriptor_;
+ metadata.reflection = Counter_reflection_;
+ return metadata;
+}
+
+
+// ===================================================================
+
+#ifndef _MSC_VER
+const int Quantile::kQuantileFieldNumber;
+const int Quantile::kValueFieldNumber;
+#endif // !_MSC_VER
+
+Quantile::Quantile()
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ // @@protoc_insertion_point(constructor:io.prometheus.client.Quantile)
+}
+
+void Quantile::InitAsDefaultInstance() {
+}
+
+Quantile::Quantile(const Quantile& from)
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ MergeFrom(from);
+ // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Quantile)
+}
+
+void Quantile::SharedCtor() {
+ _cached_size_ = 0;
+ quantile_ = 0;
+ value_ = 0;
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+}
+
+Quantile::~Quantile() {
+ // @@protoc_insertion_point(destructor:io.prometheus.client.Quantile)
+ SharedDtor();
+}
+
+void Quantile::SharedDtor() {
+ if (this != default_instance_) {
+ }
+}
+
+void Quantile::SetCachedSize(int size) const {
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+}
+const ::google::protobuf::Descriptor* Quantile::descriptor() {
+ protobuf_AssignDescriptorsOnce();
+ return Quantile_descriptor_;
+}
+
+const Quantile& Quantile::default_instance() {
+ if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto();
+ return *default_instance_;
+}
+
+Quantile* Quantile::default_instance_ = NULL;
+
+Quantile* Quantile::New() const {
+ return new Quantile;
+}
+
+void Quantile::Clear() {
+#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \
+ &reinterpret_cast(16)->f) - \
+ reinterpret_cast(16))
+
+#define ZR_(first, last) do { \
+ size_t f = OFFSET_OF_FIELD_(first); \
+ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \
+ ::memset(&first, 0, n); \
+ } while (0)
+
+ ZR_(quantile_, value_);
+
+#undef OFFSET_OF_FIELD_
+#undef ZR_
+
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ mutable_unknown_fields()->Clear();
+}
+
+bool Quantile::MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
+ ::google::protobuf::uint32 tag;
+ // @@protoc_insertion_point(parse_start:io.prometheus.client.Quantile)
+ for (;;) {
+ ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
+ tag = p.first;
+ if (!p.second) goto handle_unusual;
+ switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+ // optional double quantile = 1;
+ case 1: {
+ if (tag == 9) {
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
+ input, &quantile_)));
+ set_has_quantile();
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(17)) goto parse_value;
+ break;
+ }
+
+ // optional double value = 2;
+ case 2: {
+ if (tag == 17) {
+ parse_value:
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
+ input, &value_)));
+ set_has_value();
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectAtEnd()) goto success;
+ break;
+ }
+
+ default: {
+ handle_unusual:
+ if (tag == 0 ||
+ ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ goto success;
+ }
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, mutable_unknown_fields()));
+ break;
+ }
+ }
+ }
+success:
+ // @@protoc_insertion_point(parse_success:io.prometheus.client.Quantile)
+ return true;
+failure:
+ // @@protoc_insertion_point(parse_failure:io.prometheus.client.Quantile)
+ return false;
+#undef DO_
+}
+
+void Quantile::SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const {
+ // @@protoc_insertion_point(serialize_start:io.prometheus.client.Quantile)
+ // optional double quantile = 1;
+ if (has_quantile()) {
+ ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->quantile(), output);
+ }
+
+ // optional double value = 2;
+ if (has_value()) {
+ ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->value(), output);
+ }
+
+ if (!unknown_fields().empty()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ unknown_fields(), output);
+ }
+ // @@protoc_insertion_point(serialize_end:io.prometheus.client.Quantile)
+}
+
+::google::protobuf::uint8* Quantile::SerializeWithCachedSizesToArray(
+ ::google::protobuf::uint8* target) const {
+ // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Quantile)
+ // optional double quantile = 1;
+ if (has_quantile()) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->quantile(), target);
+ }
+
+ // optional double value = 2;
+ if (has_value()) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->value(), target);
+ }
+
+ if (!unknown_fields().empty()) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ unknown_fields(), target);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Quantile)
+ return target;
+}
+
+int Quantile::ByteSize() const {
+ int total_size = 0;
+
+ if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ // optional double quantile = 1;
+ if (has_quantile()) {
+ total_size += 1 + 8;
+ }
+
+ // optional double value = 2;
+ if (has_value()) {
+ total_size += 1 + 8;
+ }
+
+ }
+ if (!unknown_fields().empty()) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ unknown_fields());
+ }
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = total_size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ return total_size;
+}
+
+void Quantile::MergeFrom(const ::google::protobuf::Message& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ const Quantile* source =
+ ::google::protobuf::internal::dynamic_cast_if_available(
+ &from);
+ if (source == NULL) {
+ ::google::protobuf::internal::ReflectionOps::Merge(from, this);
+ } else {
+ MergeFrom(*source);
+ }
+}
+
+void Quantile::MergeFrom(const Quantile& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ if (from.has_quantile()) {
+ set_quantile(from.quantile());
+ }
+ if (from.has_value()) {
+ set_value(from.value());
+ }
+ }
+ mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+}
+
+void Quantile::CopyFrom(const ::google::protobuf::Message& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+void Quantile::CopyFrom(const Quantile& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool Quantile::IsInitialized() const {
+
+ return true;
+}
+
+void Quantile::Swap(Quantile* other) {
+ if (other != this) {
+ std::swap(quantile_, other->quantile_);
+ std::swap(value_, other->value_);
+ std::swap(_has_bits_[0], other->_has_bits_[0]);
+ _unknown_fields_.Swap(&other->_unknown_fields_);
+ std::swap(_cached_size_, other->_cached_size_);
+ }
+}
+
+::google::protobuf::Metadata Quantile::GetMetadata() const {
+ protobuf_AssignDescriptorsOnce();
+ ::google::protobuf::Metadata metadata;
+ metadata.descriptor = Quantile_descriptor_;
+ metadata.reflection = Quantile_reflection_;
+ return metadata;
+}
+
+
+// ===================================================================
+
+#ifndef _MSC_VER
+const int Summary::kSampleCountFieldNumber;
+const int Summary::kSampleSumFieldNumber;
+const int Summary::kQuantileFieldNumber;
+#endif // !_MSC_VER
+
+Summary::Summary()
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ // @@protoc_insertion_point(constructor:io.prometheus.client.Summary)
+}
+
+void Summary::InitAsDefaultInstance() {
+}
+
+Summary::Summary(const Summary& from)
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ MergeFrom(from);
+ // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Summary)
+}
+
+void Summary::SharedCtor() {
+ _cached_size_ = 0;
+ sample_count_ = GOOGLE_ULONGLONG(0);
+ sample_sum_ = 0;
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+}
+
+Summary::~Summary() {
+ // @@protoc_insertion_point(destructor:io.prometheus.client.Summary)
+ SharedDtor();
+}
+
+void Summary::SharedDtor() {
+ if (this != default_instance_) {
+ }
+}
+
+void Summary::SetCachedSize(int size) const {
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+}
+const ::google::protobuf::Descriptor* Summary::descriptor() {
+ protobuf_AssignDescriptorsOnce();
+ return Summary_descriptor_;
+}
+
+const Summary& Summary::default_instance() {
+ if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto();
+ return *default_instance_;
+}
+
+Summary* Summary::default_instance_ = NULL;
+
+Summary* Summary::New() const {
+ return new Summary;
+}
+
+void Summary::Clear() {
+#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \
+ &reinterpret_cast(16)->f) - \
+ reinterpret_cast(16))
+
+#define ZR_(first, last) do { \
+ size_t f = OFFSET_OF_FIELD_(first); \
+ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \
+ ::memset(&first, 0, n); \
+ } while (0)
+
+ ZR_(sample_count_, sample_sum_);
+
+#undef OFFSET_OF_FIELD_
+#undef ZR_
+
+ quantile_.Clear();
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ mutable_unknown_fields()->Clear();
+}
+
+bool Summary::MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
+ ::google::protobuf::uint32 tag;
+ // @@protoc_insertion_point(parse_start:io.prometheus.client.Summary)
+ for (;;) {
+ ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
+ tag = p.first;
+ if (!p.second) goto handle_unusual;
+ switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+ // optional uint64 sample_count = 1;
+ case 1: {
+ if (tag == 8) {
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
+ input, &sample_count_)));
+ set_has_sample_count();
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(17)) goto parse_sample_sum;
+ break;
+ }
+
+ // optional double sample_sum = 2;
+ case 2: {
+ if (tag == 17) {
+ parse_sample_sum:
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
+ input, &sample_sum_)));
+ set_has_sample_sum();
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(26)) goto parse_quantile;
+ break;
+ }
+
+ // repeated .io.prometheus.client.Quantile quantile = 3;
+ case 3: {
+ if (tag == 26) {
+ parse_quantile:
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ input, add_quantile()));
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(26)) goto parse_quantile;
+ if (input->ExpectAtEnd()) goto success;
+ break;
+ }
+
+ default: {
+ handle_unusual:
+ if (tag == 0 ||
+ ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ goto success;
+ }
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, mutable_unknown_fields()));
+ break;
+ }
+ }
+ }
+success:
+ // @@protoc_insertion_point(parse_success:io.prometheus.client.Summary)
+ return true;
+failure:
+ // @@protoc_insertion_point(parse_failure:io.prometheus.client.Summary)
+ return false;
+#undef DO_
+}
+
+void Summary::SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const {
+ // @@protoc_insertion_point(serialize_start:io.prometheus.client.Summary)
+ // optional uint64 sample_count = 1;
+ if (has_sample_count()) {
+ ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->sample_count(), output);
+ }
+
+ // optional double sample_sum = 2;
+ if (has_sample_sum()) {
+ ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->sample_sum(), output);
+ }
+
+ // repeated .io.prometheus.client.Quantile quantile = 3;
+ for (int i = 0; i < this->quantile_size(); i++) {
+ ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
+ 3, this->quantile(i), output);
+ }
+
+ if (!unknown_fields().empty()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ unknown_fields(), output);
+ }
+ // @@protoc_insertion_point(serialize_end:io.prometheus.client.Summary)
+}
+
+::google::protobuf::uint8* Summary::SerializeWithCachedSizesToArray(
+ ::google::protobuf::uint8* target) const {
+ // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Summary)
+ // optional uint64 sample_count = 1;
+ if (has_sample_count()) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->sample_count(), target);
+ }
+
+ // optional double sample_sum = 2;
+ if (has_sample_sum()) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->sample_sum(), target);
+ }
+
+ // repeated .io.prometheus.client.Quantile quantile = 3;
+ for (int i = 0; i < this->quantile_size(); i++) {
+ target = ::google::protobuf::internal::WireFormatLite::
+ WriteMessageNoVirtualToArray(
+ 3, this->quantile(i), target);
+ }
+
+ if (!unknown_fields().empty()) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ unknown_fields(), target);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Summary)
+ return target;
+}
+
+int Summary::ByteSize() const {
+ int total_size = 0;
+
+ if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ // optional uint64 sample_count = 1;
+ if (has_sample_count()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::UInt64Size(
+ this->sample_count());
+ }
+
+ // optional double sample_sum = 2;
+ if (has_sample_sum()) {
+ total_size += 1 + 8;
+ }
+
+ }
+ // repeated .io.prometheus.client.Quantile quantile = 3;
+ total_size += 1 * this->quantile_size();
+ for (int i = 0; i < this->quantile_size(); i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->quantile(i));
+ }
+
+ if (!unknown_fields().empty()) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ unknown_fields());
+ }
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = total_size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ return total_size;
+}
+
+void Summary::MergeFrom(const ::google::protobuf::Message& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ const Summary* source =
+ ::google::protobuf::internal::dynamic_cast_if_available(
+ &from);
+ if (source == NULL) {
+ ::google::protobuf::internal::ReflectionOps::Merge(from, this);
+ } else {
+ MergeFrom(*source);
+ }
+}
+
+void Summary::MergeFrom(const Summary& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ quantile_.MergeFrom(from.quantile_);
+ if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ if (from.has_sample_count()) {
+ set_sample_count(from.sample_count());
+ }
+ if (from.has_sample_sum()) {
+ set_sample_sum(from.sample_sum());
+ }
+ }
+ mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+}
+
+void Summary::CopyFrom(const ::google::protobuf::Message& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+void Summary::CopyFrom(const Summary& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool Summary::IsInitialized() const {
+
+ return true;
+}
+
+void Summary::Swap(Summary* other) {
+ if (other != this) {
+ std::swap(sample_count_, other->sample_count_);
+ std::swap(sample_sum_, other->sample_sum_);
+ quantile_.Swap(&other->quantile_);
+ std::swap(_has_bits_[0], other->_has_bits_[0]);
+ _unknown_fields_.Swap(&other->_unknown_fields_);
+ std::swap(_cached_size_, other->_cached_size_);
+ }
+}
+
+::google::protobuf::Metadata Summary::GetMetadata() const {
+ protobuf_AssignDescriptorsOnce();
+ ::google::protobuf::Metadata metadata;
+ metadata.descriptor = Summary_descriptor_;
+ metadata.reflection = Summary_reflection_;
+ return metadata;
+}
+
+
+// ===================================================================
+
+#ifndef _MSC_VER
+const int Untyped::kValueFieldNumber;
+#endif // !_MSC_VER
+
+Untyped::Untyped()
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ // @@protoc_insertion_point(constructor:io.prometheus.client.Untyped)
+}
+
+void Untyped::InitAsDefaultInstance() {
+}
+
+Untyped::Untyped(const Untyped& from)
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ MergeFrom(from);
+ // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Untyped)
+}
+
+void Untyped::SharedCtor() {
+ _cached_size_ = 0;
+ value_ = 0;
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+}
+
+Untyped::~Untyped() {
+ // @@protoc_insertion_point(destructor:io.prometheus.client.Untyped)
+ SharedDtor();
+}
+
+void Untyped::SharedDtor() {
+ if (this != default_instance_) {
+ }
+}
+
+void Untyped::SetCachedSize(int size) const {
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+}
+const ::google::protobuf::Descriptor* Untyped::descriptor() {
+ protobuf_AssignDescriptorsOnce();
+ return Untyped_descriptor_;
+}
+
+const Untyped& Untyped::default_instance() {
+ if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto();
+ return *default_instance_;
+}
+
+Untyped* Untyped::default_instance_ = NULL;
+
+Untyped* Untyped::New() const {
+ return new Untyped;
+}
+
+void Untyped::Clear() {
+ value_ = 0;
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ mutable_unknown_fields()->Clear();
+}
+
+bool Untyped::MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
+ ::google::protobuf::uint32 tag;
+ // @@protoc_insertion_point(parse_start:io.prometheus.client.Untyped)
+ for (;;) {
+ ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
+ tag = p.first;
+ if (!p.second) goto handle_unusual;
+ switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+ // optional double value = 1;
+ case 1: {
+ if (tag == 9) {
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
+ input, &value_)));
+ set_has_value();
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectAtEnd()) goto success;
+ break;
+ }
+
+ default: {
+ handle_unusual:
+ if (tag == 0 ||
+ ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ goto success;
+ }
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, mutable_unknown_fields()));
+ break;
+ }
+ }
+ }
+success:
+ // @@protoc_insertion_point(parse_success:io.prometheus.client.Untyped)
+ return true;
+failure:
+ // @@protoc_insertion_point(parse_failure:io.prometheus.client.Untyped)
+ return false;
+#undef DO_
+}
+
+void Untyped::SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const {
+ // @@protoc_insertion_point(serialize_start:io.prometheus.client.Untyped)
+ // optional double value = 1;
+ if (has_value()) {
+ ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->value(), output);
+ }
+
+ if (!unknown_fields().empty()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ unknown_fields(), output);
+ }
+ // @@protoc_insertion_point(serialize_end:io.prometheus.client.Untyped)
+}
+
+::google::protobuf::uint8* Untyped::SerializeWithCachedSizesToArray(
+ ::google::protobuf::uint8* target) const {
+ // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Untyped)
+ // optional double value = 1;
+ if (has_value()) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->value(), target);
+ }
+
+ if (!unknown_fields().empty()) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ unknown_fields(), target);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Untyped)
+ return target;
+}
+
+int Untyped::ByteSize() const {
+ int total_size = 0;
+
+ if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ // optional double value = 1;
+ if (has_value()) {
+ total_size += 1 + 8;
+ }
+
+ }
+ if (!unknown_fields().empty()) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ unknown_fields());
+ }
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = total_size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ return total_size;
+}
+
+void Untyped::MergeFrom(const ::google::protobuf::Message& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ const Untyped* source =
+ ::google::protobuf::internal::dynamic_cast_if_available(
+ &from);
+ if (source == NULL) {
+ ::google::protobuf::internal::ReflectionOps::Merge(from, this);
+ } else {
+ MergeFrom(*source);
+ }
+}
+
+void Untyped::MergeFrom(const Untyped& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ if (from.has_value()) {
+ set_value(from.value());
+ }
+ }
+ mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+}
+
+void Untyped::CopyFrom(const ::google::protobuf::Message& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+void Untyped::CopyFrom(const Untyped& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool Untyped::IsInitialized() const {
+
+ return true;
+}
+
+void Untyped::Swap(Untyped* other) {
+ if (other != this) {
+ std::swap(value_, other->value_);
+ std::swap(_has_bits_[0], other->_has_bits_[0]);
+ _unknown_fields_.Swap(&other->_unknown_fields_);
+ std::swap(_cached_size_, other->_cached_size_);
+ }
+}
+
+::google::protobuf::Metadata Untyped::GetMetadata() const {
+ protobuf_AssignDescriptorsOnce();
+ ::google::protobuf::Metadata metadata;
+ metadata.descriptor = Untyped_descriptor_;
+ metadata.reflection = Untyped_reflection_;
+ return metadata;
+}
+
+
+// ===================================================================
+
+#ifndef _MSC_VER
+const int Histogram::kSampleCountFieldNumber;
+const int Histogram::kSampleSumFieldNumber;
+const int Histogram::kBucketFieldNumber;
+#endif // !_MSC_VER
+
+Histogram::Histogram()
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ // @@protoc_insertion_point(constructor:io.prometheus.client.Histogram)
+}
+
+void Histogram::InitAsDefaultInstance() {
+}
+
+Histogram::Histogram(const Histogram& from)
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ MergeFrom(from);
+ // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Histogram)
+}
+
+void Histogram::SharedCtor() {
+ _cached_size_ = 0;
+ sample_count_ = GOOGLE_ULONGLONG(0);
+ sample_sum_ = 0;
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+}
+
+Histogram::~Histogram() {
+ // @@protoc_insertion_point(destructor:io.prometheus.client.Histogram)
+ SharedDtor();
+}
+
+void Histogram::SharedDtor() {
+ if (this != default_instance_) {
+ }
+}
+
+void Histogram::SetCachedSize(int size) const {
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+}
+const ::google::protobuf::Descriptor* Histogram::descriptor() {
+ protobuf_AssignDescriptorsOnce();
+ return Histogram_descriptor_;
+}
+
+const Histogram& Histogram::default_instance() {
+ if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto();
+ return *default_instance_;
+}
+
+Histogram* Histogram::default_instance_ = NULL;
+
+Histogram* Histogram::New() const {
+ return new Histogram;
+}
+
+void Histogram::Clear() {
+#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \
+ &reinterpret_cast(16)->f) - \
+ reinterpret_cast(16))
+
+#define ZR_(first, last) do { \
+ size_t f = OFFSET_OF_FIELD_(first); \
+ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \
+ ::memset(&first, 0, n); \
+ } while (0)
+
+ ZR_(sample_count_, sample_sum_);
+
+#undef OFFSET_OF_FIELD_
+#undef ZR_
+
+ bucket_.Clear();
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ mutable_unknown_fields()->Clear();
+}
+
+bool Histogram::MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
+ ::google::protobuf::uint32 tag;
+ // @@protoc_insertion_point(parse_start:io.prometheus.client.Histogram)
+ for (;;) {
+ ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
+ tag = p.first;
+ if (!p.second) goto handle_unusual;
+ switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+ // optional uint64 sample_count = 1;
+ case 1: {
+ if (tag == 8) {
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
+ input, &sample_count_)));
+ set_has_sample_count();
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(17)) goto parse_sample_sum;
+ break;
+ }
+
+ // optional double sample_sum = 2;
+ case 2: {
+ if (tag == 17) {
+ parse_sample_sum:
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
+ input, &sample_sum_)));
+ set_has_sample_sum();
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(26)) goto parse_bucket;
+ break;
+ }
+
+ // repeated .io.prometheus.client.Bucket bucket = 3;
+ case 3: {
+ if (tag == 26) {
+ parse_bucket:
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ input, add_bucket()));
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(26)) goto parse_bucket;
+ if (input->ExpectAtEnd()) goto success;
+ break;
+ }
+
+ default: {
+ handle_unusual:
+ if (tag == 0 ||
+ ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ goto success;
+ }
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, mutable_unknown_fields()));
+ break;
+ }
+ }
+ }
+success:
+ // @@protoc_insertion_point(parse_success:io.prometheus.client.Histogram)
+ return true;
+failure:
+ // @@protoc_insertion_point(parse_failure:io.prometheus.client.Histogram)
+ return false;
+#undef DO_
+}
+
+void Histogram::SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const {
+ // @@protoc_insertion_point(serialize_start:io.prometheus.client.Histogram)
+ // optional uint64 sample_count = 1;
+ if (has_sample_count()) {
+ ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->sample_count(), output);
+ }
+
+ // optional double sample_sum = 2;
+ if (has_sample_sum()) {
+ ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->sample_sum(), output);
+ }
+
+ // repeated .io.prometheus.client.Bucket bucket = 3;
+ for (int i = 0; i < this->bucket_size(); i++) {
+ ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
+ 3, this->bucket(i), output);
+ }
+
+ if (!unknown_fields().empty()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ unknown_fields(), output);
+ }
+ // @@protoc_insertion_point(serialize_end:io.prometheus.client.Histogram)
+}
+
+::google::protobuf::uint8* Histogram::SerializeWithCachedSizesToArray(
+ ::google::protobuf::uint8* target) const {
+ // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Histogram)
+ // optional uint64 sample_count = 1;
+ if (has_sample_count()) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->sample_count(), target);
+ }
+
+ // optional double sample_sum = 2;
+ if (has_sample_sum()) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->sample_sum(), target);
+ }
+
+ // repeated .io.prometheus.client.Bucket bucket = 3;
+ for (int i = 0; i < this->bucket_size(); i++) {
+ target = ::google::protobuf::internal::WireFormatLite::
+ WriteMessageNoVirtualToArray(
+ 3, this->bucket(i), target);
+ }
+
+ if (!unknown_fields().empty()) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ unknown_fields(), target);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Histogram)
+ return target;
+}
+
+int Histogram::ByteSize() const {
+ int total_size = 0;
+
+ if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ // optional uint64 sample_count = 1;
+ if (has_sample_count()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::UInt64Size(
+ this->sample_count());
+ }
+
+ // optional double sample_sum = 2;
+ if (has_sample_sum()) {
+ total_size += 1 + 8;
+ }
+
+ }
+ // repeated .io.prometheus.client.Bucket bucket = 3;
+ total_size += 1 * this->bucket_size();
+ for (int i = 0; i < this->bucket_size(); i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->bucket(i));
+ }
+
+ if (!unknown_fields().empty()) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ unknown_fields());
+ }
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = total_size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ return total_size;
+}
+
+void Histogram::MergeFrom(const ::google::protobuf::Message& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ const Histogram* source =
+ ::google::protobuf::internal::dynamic_cast_if_available(
+ &from);
+ if (source == NULL) {
+ ::google::protobuf::internal::ReflectionOps::Merge(from, this);
+ } else {
+ MergeFrom(*source);
+ }
+}
+
+void Histogram::MergeFrom(const Histogram& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ bucket_.MergeFrom(from.bucket_);
+ if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ if (from.has_sample_count()) {
+ set_sample_count(from.sample_count());
+ }
+ if (from.has_sample_sum()) {
+ set_sample_sum(from.sample_sum());
+ }
+ }
+ mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+}
+
+void Histogram::CopyFrom(const ::google::protobuf::Message& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+void Histogram::CopyFrom(const Histogram& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool Histogram::IsInitialized() const {
+
+ return true;
+}
+
+void Histogram::Swap(Histogram* other) {
+ if (other != this) {
+ std::swap(sample_count_, other->sample_count_);
+ std::swap(sample_sum_, other->sample_sum_);
+ bucket_.Swap(&other->bucket_);
+ std::swap(_has_bits_[0], other->_has_bits_[0]);
+ _unknown_fields_.Swap(&other->_unknown_fields_);
+ std::swap(_cached_size_, other->_cached_size_);
+ }
+}
+
+::google::protobuf::Metadata Histogram::GetMetadata() const {
+ protobuf_AssignDescriptorsOnce();
+ ::google::protobuf::Metadata metadata;
+ metadata.descriptor = Histogram_descriptor_;
+ metadata.reflection = Histogram_reflection_;
+ return metadata;
+}
+
+
+// ===================================================================
+
+#ifndef _MSC_VER
+const int Bucket::kCumulativeCountFieldNumber;
+const int Bucket::kUpperBoundFieldNumber;
+#endif // !_MSC_VER
+
+Bucket::Bucket()
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ // @@protoc_insertion_point(constructor:io.prometheus.client.Bucket)
+}
+
+void Bucket::InitAsDefaultInstance() {
+}
+
+Bucket::Bucket(const Bucket& from)
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ MergeFrom(from);
+ // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Bucket)
+}
+
+void Bucket::SharedCtor() {
+ _cached_size_ = 0;
+ cumulative_count_ = GOOGLE_ULONGLONG(0);
+ upper_bound_ = 0;
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+}
+
+Bucket::~Bucket() {
+ // @@protoc_insertion_point(destructor:io.prometheus.client.Bucket)
+ SharedDtor();
+}
+
+void Bucket::SharedDtor() {
+ if (this != default_instance_) {
+ }
+}
+
+void Bucket::SetCachedSize(int size) const {
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+}
+const ::google::protobuf::Descriptor* Bucket::descriptor() {
+ protobuf_AssignDescriptorsOnce();
+ return Bucket_descriptor_;
+}
+
+const Bucket& Bucket::default_instance() {
+ if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto();
+ return *default_instance_;
+}
+
+Bucket* Bucket::default_instance_ = NULL;
+
+Bucket* Bucket::New() const {
+ return new Bucket;
+}
+
+void Bucket::Clear() {
+#define OFFSET_OF_FIELD_(f) (reinterpret_cast( \
+ &reinterpret_cast(16)->f) - \
+ reinterpret_cast(16))
+
+#define ZR_(first, last) do { \
+ size_t f = OFFSET_OF_FIELD_(first); \
+ size_t n = OFFSET_OF_FIELD_(last) - f + sizeof(last); \
+ ::memset(&first, 0, n); \
+ } while (0)
+
+ ZR_(cumulative_count_, upper_bound_);
+
+#undef OFFSET_OF_FIELD_
+#undef ZR_
+
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ mutable_unknown_fields()->Clear();
+}
+
+bool Bucket::MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
+ ::google::protobuf::uint32 tag;
+ // @@protoc_insertion_point(parse_start:io.prometheus.client.Bucket)
+ for (;;) {
+ ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
+ tag = p.first;
+ if (!p.second) goto handle_unusual;
+ switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+ // optional uint64 cumulative_count = 1;
+ case 1: {
+ if (tag == 8) {
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_UINT64>(
+ input, &cumulative_count_)));
+ set_has_cumulative_count();
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(17)) goto parse_upper_bound;
+ break;
+ }
+
+ // optional double upper_bound = 2;
+ case 2: {
+ if (tag == 17) {
+ parse_upper_bound:
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>(
+ input, &upper_bound_)));
+ set_has_upper_bound();
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectAtEnd()) goto success;
+ break;
+ }
+
+ default: {
+ handle_unusual:
+ if (tag == 0 ||
+ ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ goto success;
+ }
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, mutable_unknown_fields()));
+ break;
+ }
+ }
+ }
+success:
+ // @@protoc_insertion_point(parse_success:io.prometheus.client.Bucket)
+ return true;
+failure:
+ // @@protoc_insertion_point(parse_failure:io.prometheus.client.Bucket)
+ return false;
+#undef DO_
+}
+
+void Bucket::SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const {
+ // @@protoc_insertion_point(serialize_start:io.prometheus.client.Bucket)
+ // optional uint64 cumulative_count = 1;
+ if (has_cumulative_count()) {
+ ::google::protobuf::internal::WireFormatLite::WriteUInt64(1, this->cumulative_count(), output);
+ }
+
+ // optional double upper_bound = 2;
+ if (has_upper_bound()) {
+ ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->upper_bound(), output);
+ }
+
+ if (!unknown_fields().empty()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ unknown_fields(), output);
+ }
+ // @@protoc_insertion_point(serialize_end:io.prometheus.client.Bucket)
+}
+
+::google::protobuf::uint8* Bucket::SerializeWithCachedSizesToArray(
+ ::google::protobuf::uint8* target) const {
+ // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Bucket)
+ // optional uint64 cumulative_count = 1;
+ if (has_cumulative_count()) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteUInt64ToArray(1, this->cumulative_count(), target);
+ }
+
+ // optional double upper_bound = 2;
+ if (has_upper_bound()) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->upper_bound(), target);
+ }
+
+ if (!unknown_fields().empty()) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ unknown_fields(), target);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Bucket)
+ return target;
+}
+
+int Bucket::ByteSize() const {
+ int total_size = 0;
+
+ if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ // optional uint64 cumulative_count = 1;
+ if (has_cumulative_count()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::UInt64Size(
+ this->cumulative_count());
+ }
+
+ // optional double upper_bound = 2;
+ if (has_upper_bound()) {
+ total_size += 1 + 8;
+ }
+
+ }
+ if (!unknown_fields().empty()) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ unknown_fields());
+ }
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = total_size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ return total_size;
+}
+
+void Bucket::MergeFrom(const ::google::protobuf::Message& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ const Bucket* source =
+ ::google::protobuf::internal::dynamic_cast_if_available(
+ &from);
+ if (source == NULL) {
+ ::google::protobuf::internal::ReflectionOps::Merge(from, this);
+ } else {
+ MergeFrom(*source);
+ }
+}
+
+void Bucket::MergeFrom(const Bucket& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ if (from.has_cumulative_count()) {
+ set_cumulative_count(from.cumulative_count());
+ }
+ if (from.has_upper_bound()) {
+ set_upper_bound(from.upper_bound());
+ }
+ }
+ mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+}
+
+void Bucket::CopyFrom(const ::google::protobuf::Message& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+void Bucket::CopyFrom(const Bucket& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool Bucket::IsInitialized() const {
+
+ return true;
+}
+
+void Bucket::Swap(Bucket* other) {
+ if (other != this) {
+ std::swap(cumulative_count_, other->cumulative_count_);
+ std::swap(upper_bound_, other->upper_bound_);
+ std::swap(_has_bits_[0], other->_has_bits_[0]);
+ _unknown_fields_.Swap(&other->_unknown_fields_);
+ std::swap(_cached_size_, other->_cached_size_);
+ }
+}
+
+::google::protobuf::Metadata Bucket::GetMetadata() const {
+ protobuf_AssignDescriptorsOnce();
+ ::google::protobuf::Metadata metadata;
+ metadata.descriptor = Bucket_descriptor_;
+ metadata.reflection = Bucket_reflection_;
+ return metadata;
+}
+
+
+// ===================================================================
+
+#ifndef _MSC_VER
+const int Metric::kLabelFieldNumber;
+const int Metric::kGaugeFieldNumber;
+const int Metric::kCounterFieldNumber;
+const int Metric::kSummaryFieldNumber;
+const int Metric::kUntypedFieldNumber;
+const int Metric::kHistogramFieldNumber;
+const int Metric::kTimestampMsFieldNumber;
+#endif // !_MSC_VER
+
+Metric::Metric()
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ // @@protoc_insertion_point(constructor:io.prometheus.client.Metric)
+}
+
+void Metric::InitAsDefaultInstance() {
+ gauge_ = const_cast< ::io::prometheus::client::Gauge*>(&::io::prometheus::client::Gauge::default_instance());
+ counter_ = const_cast< ::io::prometheus::client::Counter*>(&::io::prometheus::client::Counter::default_instance());
+ summary_ = const_cast< ::io::prometheus::client::Summary*>(&::io::prometheus::client::Summary::default_instance());
+ untyped_ = const_cast< ::io::prometheus::client::Untyped*>(&::io::prometheus::client::Untyped::default_instance());
+ histogram_ = const_cast< ::io::prometheus::client::Histogram*>(&::io::prometheus::client::Histogram::default_instance());
+}
+
+Metric::Metric(const Metric& from)
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ MergeFrom(from);
+ // @@protoc_insertion_point(copy_constructor:io.prometheus.client.Metric)
+}
+
+void Metric::SharedCtor() {
+ _cached_size_ = 0;
+ gauge_ = NULL;
+ counter_ = NULL;
+ summary_ = NULL;
+ untyped_ = NULL;
+ histogram_ = NULL;
+ timestamp_ms_ = GOOGLE_LONGLONG(0);
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+}
+
+Metric::~Metric() {
+ // @@protoc_insertion_point(destructor:io.prometheus.client.Metric)
+ SharedDtor();
+}
+
+void Metric::SharedDtor() {
+ if (this != default_instance_) {
+ delete gauge_;
+ delete counter_;
+ delete summary_;
+ delete untyped_;
+ delete histogram_;
+ }
+}
+
+void Metric::SetCachedSize(int size) const {
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+}
+const ::google::protobuf::Descriptor* Metric::descriptor() {
+ protobuf_AssignDescriptorsOnce();
+ return Metric_descriptor_;
+}
+
+const Metric& Metric::default_instance() {
+ if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto();
+ return *default_instance_;
+}
+
+Metric* Metric::default_instance_ = NULL;
+
+Metric* Metric::New() const {
+ return new Metric;
+}
+
+void Metric::Clear() {
+ if (_has_bits_[0 / 32] & 126) {
+ if (has_gauge()) {
+ if (gauge_ != NULL) gauge_->::io::prometheus::client::Gauge::Clear();
+ }
+ if (has_counter()) {
+ if (counter_ != NULL) counter_->::io::prometheus::client::Counter::Clear();
+ }
+ if (has_summary()) {
+ if (summary_ != NULL) summary_->::io::prometheus::client::Summary::Clear();
+ }
+ if (has_untyped()) {
+ if (untyped_ != NULL) untyped_->::io::prometheus::client::Untyped::Clear();
+ }
+ if (has_histogram()) {
+ if (histogram_ != NULL) histogram_->::io::prometheus::client::Histogram::Clear();
+ }
+ timestamp_ms_ = GOOGLE_LONGLONG(0);
+ }
+ label_.Clear();
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ mutable_unknown_fields()->Clear();
+}
+
+bool Metric::MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
+ ::google::protobuf::uint32 tag;
+ // @@protoc_insertion_point(parse_start:io.prometheus.client.Metric)
+ for (;;) {
+ ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
+ tag = p.first;
+ if (!p.second) goto handle_unusual;
+ switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+ // repeated .io.prometheus.client.LabelPair label = 1;
+ case 1: {
+ if (tag == 10) {
+ parse_label:
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ input, add_label()));
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(10)) goto parse_label;
+ if (input->ExpectTag(18)) goto parse_gauge;
+ break;
+ }
+
+ // optional .io.prometheus.client.Gauge gauge = 2;
+ case 2: {
+ if (tag == 18) {
+ parse_gauge:
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ input, mutable_gauge()));
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(26)) goto parse_counter;
+ break;
+ }
+
+ // optional .io.prometheus.client.Counter counter = 3;
+ case 3: {
+ if (tag == 26) {
+ parse_counter:
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ input, mutable_counter()));
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(34)) goto parse_summary;
+ break;
+ }
+
+ // optional .io.prometheus.client.Summary summary = 4;
+ case 4: {
+ if (tag == 34) {
+ parse_summary:
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ input, mutable_summary()));
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(42)) goto parse_untyped;
+ break;
+ }
+
+ // optional .io.prometheus.client.Untyped untyped = 5;
+ case 5: {
+ if (tag == 42) {
+ parse_untyped:
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ input, mutable_untyped()));
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(48)) goto parse_timestamp_ms;
+ break;
+ }
+
+ // optional int64 timestamp_ms = 6;
+ case 6: {
+ if (tag == 48) {
+ parse_timestamp_ms:
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
+ input, ×tamp_ms_)));
+ set_has_timestamp_ms();
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(58)) goto parse_histogram;
+ break;
+ }
+
+ // optional .io.prometheus.client.Histogram histogram = 7;
+ case 7: {
+ if (tag == 58) {
+ parse_histogram:
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ input, mutable_histogram()));
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectAtEnd()) goto success;
+ break;
+ }
+
+ default: {
+ handle_unusual:
+ if (tag == 0 ||
+ ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ goto success;
+ }
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, mutable_unknown_fields()));
+ break;
+ }
+ }
+ }
+success:
+ // @@protoc_insertion_point(parse_success:io.prometheus.client.Metric)
+ return true;
+failure:
+ // @@protoc_insertion_point(parse_failure:io.prometheus.client.Metric)
+ return false;
+#undef DO_
+}
+
+void Metric::SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const {
+ // @@protoc_insertion_point(serialize_start:io.prometheus.client.Metric)
+ // repeated .io.prometheus.client.LabelPair label = 1;
+ for (int i = 0; i < this->label_size(); i++) {
+ ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
+ 1, this->label(i), output);
+ }
+
+ // optional .io.prometheus.client.Gauge gauge = 2;
+ if (has_gauge()) {
+ ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
+ 2, this->gauge(), output);
+ }
+
+ // optional .io.prometheus.client.Counter counter = 3;
+ if (has_counter()) {
+ ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
+ 3, this->counter(), output);
+ }
+
+ // optional .io.prometheus.client.Summary summary = 4;
+ if (has_summary()) {
+ ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
+ 4, this->summary(), output);
+ }
+
+ // optional .io.prometheus.client.Untyped untyped = 5;
+ if (has_untyped()) {
+ ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
+ 5, this->untyped(), output);
+ }
+
+ // optional int64 timestamp_ms = 6;
+ if (has_timestamp_ms()) {
+ ::google::protobuf::internal::WireFormatLite::WriteInt64(6, this->timestamp_ms(), output);
+ }
+
+ // optional .io.prometheus.client.Histogram histogram = 7;
+ if (has_histogram()) {
+ ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
+ 7, this->histogram(), output);
+ }
+
+ if (!unknown_fields().empty()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ unknown_fields(), output);
+ }
+ // @@protoc_insertion_point(serialize_end:io.prometheus.client.Metric)
+}
+
+::google::protobuf::uint8* Metric::SerializeWithCachedSizesToArray(
+ ::google::protobuf::uint8* target) const {
+ // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.Metric)
+ // repeated .io.prometheus.client.LabelPair label = 1;
+ for (int i = 0; i < this->label_size(); i++) {
+ target = ::google::protobuf::internal::WireFormatLite::
+ WriteMessageNoVirtualToArray(
+ 1, this->label(i), target);
+ }
+
+ // optional .io.prometheus.client.Gauge gauge = 2;
+ if (has_gauge()) {
+ target = ::google::protobuf::internal::WireFormatLite::
+ WriteMessageNoVirtualToArray(
+ 2, this->gauge(), target);
+ }
+
+ // optional .io.prometheus.client.Counter counter = 3;
+ if (has_counter()) {
+ target = ::google::protobuf::internal::WireFormatLite::
+ WriteMessageNoVirtualToArray(
+ 3, this->counter(), target);
+ }
+
+ // optional .io.prometheus.client.Summary summary = 4;
+ if (has_summary()) {
+ target = ::google::protobuf::internal::WireFormatLite::
+ WriteMessageNoVirtualToArray(
+ 4, this->summary(), target);
+ }
+
+ // optional .io.prometheus.client.Untyped untyped = 5;
+ if (has_untyped()) {
+ target = ::google::protobuf::internal::WireFormatLite::
+ WriteMessageNoVirtualToArray(
+ 5, this->untyped(), target);
+ }
+
+ // optional int64 timestamp_ms = 6;
+ if (has_timestamp_ms()) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(6, this->timestamp_ms(), target);
+ }
+
+ // optional .io.prometheus.client.Histogram histogram = 7;
+ if (has_histogram()) {
+ target = ::google::protobuf::internal::WireFormatLite::
+ WriteMessageNoVirtualToArray(
+ 7, this->histogram(), target);
+ }
+
+ if (!unknown_fields().empty()) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ unknown_fields(), target);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.Metric)
+ return target;
+}
+
+int Metric::ByteSize() const {
+ int total_size = 0;
+
+ if (_has_bits_[1 / 32] & (0xffu << (1 % 32))) {
+ // optional .io.prometheus.client.Gauge gauge = 2;
+ if (has_gauge()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->gauge());
+ }
+
+ // optional .io.prometheus.client.Counter counter = 3;
+ if (has_counter()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->counter());
+ }
+
+ // optional .io.prometheus.client.Summary summary = 4;
+ if (has_summary()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->summary());
+ }
+
+ // optional .io.prometheus.client.Untyped untyped = 5;
+ if (has_untyped()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->untyped());
+ }
+
+ // optional .io.prometheus.client.Histogram histogram = 7;
+ if (has_histogram()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->histogram());
+ }
+
+ // optional int64 timestamp_ms = 6;
+ if (has_timestamp_ms()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::Int64Size(
+ this->timestamp_ms());
+ }
+
+ }
+ // repeated .io.prometheus.client.LabelPair label = 1;
+ total_size += 1 * this->label_size();
+ for (int i = 0; i < this->label_size(); i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->label(i));
+ }
+
+ if (!unknown_fields().empty()) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ unknown_fields());
+ }
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = total_size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ return total_size;
+}
+
+void Metric::MergeFrom(const ::google::protobuf::Message& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ const Metric* source =
+ ::google::protobuf::internal::dynamic_cast_if_available(
+ &from);
+ if (source == NULL) {
+ ::google::protobuf::internal::ReflectionOps::Merge(from, this);
+ } else {
+ MergeFrom(*source);
+ }
+}
+
+void Metric::MergeFrom(const Metric& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ label_.MergeFrom(from.label_);
+ if (from._has_bits_[1 / 32] & (0xffu << (1 % 32))) {
+ if (from.has_gauge()) {
+ mutable_gauge()->::io::prometheus::client::Gauge::MergeFrom(from.gauge());
+ }
+ if (from.has_counter()) {
+ mutable_counter()->::io::prometheus::client::Counter::MergeFrom(from.counter());
+ }
+ if (from.has_summary()) {
+ mutable_summary()->::io::prometheus::client::Summary::MergeFrom(from.summary());
+ }
+ if (from.has_untyped()) {
+ mutable_untyped()->::io::prometheus::client::Untyped::MergeFrom(from.untyped());
+ }
+ if (from.has_histogram()) {
+ mutable_histogram()->::io::prometheus::client::Histogram::MergeFrom(from.histogram());
+ }
+ if (from.has_timestamp_ms()) {
+ set_timestamp_ms(from.timestamp_ms());
+ }
+ }
+ mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+}
+
+void Metric::CopyFrom(const ::google::protobuf::Message& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+void Metric::CopyFrom(const Metric& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool Metric::IsInitialized() const {
+
+ return true;
+}
+
+void Metric::Swap(Metric* other) {
+ if (other != this) {
+ label_.Swap(&other->label_);
+ std::swap(gauge_, other->gauge_);
+ std::swap(counter_, other->counter_);
+ std::swap(summary_, other->summary_);
+ std::swap(untyped_, other->untyped_);
+ std::swap(histogram_, other->histogram_);
+ std::swap(timestamp_ms_, other->timestamp_ms_);
+ std::swap(_has_bits_[0], other->_has_bits_[0]);
+ _unknown_fields_.Swap(&other->_unknown_fields_);
+ std::swap(_cached_size_, other->_cached_size_);
+ }
+}
+
+::google::protobuf::Metadata Metric::GetMetadata() const {
+ protobuf_AssignDescriptorsOnce();
+ ::google::protobuf::Metadata metadata;
+ metadata.descriptor = Metric_descriptor_;
+ metadata.reflection = Metric_reflection_;
+ return metadata;
+}
+
+
+// ===================================================================
+
+#ifndef _MSC_VER
+const int MetricFamily::kNameFieldNumber;
+const int MetricFamily::kHelpFieldNumber;
+const int MetricFamily::kTypeFieldNumber;
+const int MetricFamily::kMetricFieldNumber;
+#endif // !_MSC_VER
+
+MetricFamily::MetricFamily()
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ // @@protoc_insertion_point(constructor:io.prometheus.client.MetricFamily)
+}
+
+void MetricFamily::InitAsDefaultInstance() {
+}
+
+MetricFamily::MetricFamily(const MetricFamily& from)
+ : ::google::protobuf::Message() {
+ SharedCtor();
+ MergeFrom(from);
+ // @@protoc_insertion_point(copy_constructor:io.prometheus.client.MetricFamily)
+}
+
+void MetricFamily::SharedCtor() {
+ ::google::protobuf::internal::GetEmptyString();
+ _cached_size_ = 0;
+ name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ help_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ type_ = 0;
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+}
+
+MetricFamily::~MetricFamily() {
+ // @@protoc_insertion_point(destructor:io.prometheus.client.MetricFamily)
+ SharedDtor();
+}
+
+void MetricFamily::SharedDtor() {
+ if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ delete name_;
+ }
+ if (help_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ delete help_;
+ }
+ if (this != default_instance_) {
+ }
+}
+
+void MetricFamily::SetCachedSize(int size) const {
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+}
+const ::google::protobuf::Descriptor* MetricFamily::descriptor() {
+ protobuf_AssignDescriptorsOnce();
+ return MetricFamily_descriptor_;
+}
+
+const MetricFamily& MetricFamily::default_instance() {
+ if (default_instance_ == NULL) protobuf_AddDesc_metrics_2eproto();
+ return *default_instance_;
+}
+
+MetricFamily* MetricFamily::default_instance_ = NULL;
+
+MetricFamily* MetricFamily::New() const {
+ return new MetricFamily;
+}
+
+void MetricFamily::Clear() {
+ if (_has_bits_[0 / 32] & 7) {
+ if (has_name()) {
+ if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ name_->clear();
+ }
+ }
+ if (has_help()) {
+ if (help_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ help_->clear();
+ }
+ }
+ type_ = 0;
+ }
+ metric_.Clear();
+ ::memset(_has_bits_, 0, sizeof(_has_bits_));
+ mutable_unknown_fields()->Clear();
+}
+
+bool MetricFamily::MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input) {
+#define DO_(EXPRESSION) if (!(EXPRESSION)) goto failure
+ ::google::protobuf::uint32 tag;
+ // @@protoc_insertion_point(parse_start:io.prometheus.client.MetricFamily)
+ for (;;) {
+ ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
+ tag = p.first;
+ if (!p.second) goto handle_unusual;
+ switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
+ // optional string name = 1;
+ case 1: {
+ if (tag == 10) {
+ DO_(::google::protobuf::internal::WireFormatLite::ReadString(
+ input, this->mutable_name()));
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->name().data(), this->name().length(),
+ ::google::protobuf::internal::WireFormat::PARSE,
+ "name");
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(18)) goto parse_help;
+ break;
+ }
+
+ // optional string help = 2;
+ case 2: {
+ if (tag == 18) {
+ parse_help:
+ DO_(::google::protobuf::internal::WireFormatLite::ReadString(
+ input, this->mutable_help()));
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->help().data(), this->help().length(),
+ ::google::protobuf::internal::WireFormat::PARSE,
+ "help");
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(24)) goto parse_type;
+ break;
+ }
+
+ // optional .io.prometheus.client.MetricType type = 3;
+ case 3: {
+ if (tag == 24) {
+ parse_type:
+ int value;
+ DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
+ int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
+ input, &value)));
+ if (::io::prometheus::client::MetricType_IsValid(value)) {
+ set_type(static_cast< ::io::prometheus::client::MetricType >(value));
+ } else {
+ mutable_unknown_fields()->AddVarint(3, value);
+ }
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(34)) goto parse_metric;
+ break;
+ }
+
+ // repeated .io.prometheus.client.Metric metric = 4;
+ case 4: {
+ if (tag == 34) {
+ parse_metric:
+ DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
+ input, add_metric()));
+ } else {
+ goto handle_unusual;
+ }
+ if (input->ExpectTag(34)) goto parse_metric;
+ if (input->ExpectAtEnd()) goto success;
+ break;
+ }
+
+ default: {
+ handle_unusual:
+ if (tag == 0 ||
+ ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
+ ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
+ goto success;
+ }
+ DO_(::google::protobuf::internal::WireFormat::SkipField(
+ input, tag, mutable_unknown_fields()));
+ break;
+ }
+ }
+ }
+success:
+ // @@protoc_insertion_point(parse_success:io.prometheus.client.MetricFamily)
+ return true;
+failure:
+ // @@protoc_insertion_point(parse_failure:io.prometheus.client.MetricFamily)
+ return false;
+#undef DO_
+}
+
+void MetricFamily::SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const {
+ // @@protoc_insertion_point(serialize_start:io.prometheus.client.MetricFamily)
+ // optional string name = 1;
+ if (has_name()) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->name().data(), this->name().length(),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "name");
+ ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
+ 1, this->name(), output);
+ }
+
+ // optional string help = 2;
+ if (has_help()) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->help().data(), this->help().length(),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "help");
+ ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased(
+ 2, this->help(), output);
+ }
+
+ // optional .io.prometheus.client.MetricType type = 3;
+ if (has_type()) {
+ ::google::protobuf::internal::WireFormatLite::WriteEnum(
+ 3, this->type(), output);
+ }
+
+ // repeated .io.prometheus.client.Metric metric = 4;
+ for (int i = 0; i < this->metric_size(); i++) {
+ ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
+ 4, this->metric(i), output);
+ }
+
+ if (!unknown_fields().empty()) {
+ ::google::protobuf::internal::WireFormat::SerializeUnknownFields(
+ unknown_fields(), output);
+ }
+ // @@protoc_insertion_point(serialize_end:io.prometheus.client.MetricFamily)
+}
+
+::google::protobuf::uint8* MetricFamily::SerializeWithCachedSizesToArray(
+ ::google::protobuf::uint8* target) const {
+ // @@protoc_insertion_point(serialize_to_array_start:io.prometheus.client.MetricFamily)
+ // optional string name = 1;
+ if (has_name()) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->name().data(), this->name().length(),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "name");
+ target =
+ ::google::protobuf::internal::WireFormatLite::WriteStringToArray(
+ 1, this->name(), target);
+ }
+
+ // optional string help = 2;
+ if (has_help()) {
+ ::google::protobuf::internal::WireFormat::VerifyUTF8StringNamedField(
+ this->help().data(), this->help().length(),
+ ::google::protobuf::internal::WireFormat::SERIALIZE,
+ "help");
+ target =
+ ::google::protobuf::internal::WireFormatLite::WriteStringToArray(
+ 2, this->help(), target);
+ }
+
+ // optional .io.prometheus.client.MetricType type = 3;
+ if (has_type()) {
+ target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
+ 3, this->type(), target);
+ }
+
+ // repeated .io.prometheus.client.Metric metric = 4;
+ for (int i = 0; i < this->metric_size(); i++) {
+ target = ::google::protobuf::internal::WireFormatLite::
+ WriteMessageNoVirtualToArray(
+ 4, this->metric(i), target);
+ }
+
+ if (!unknown_fields().empty()) {
+ target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
+ unknown_fields(), target);
+ }
+ // @@protoc_insertion_point(serialize_to_array_end:io.prometheus.client.MetricFamily)
+ return target;
+}
+
+int MetricFamily::ByteSize() const {
+ int total_size = 0;
+
+ if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ // optional string name = 1;
+ if (has_name()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::StringSize(
+ this->name());
+ }
+
+ // optional string help = 2;
+ if (has_help()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::StringSize(
+ this->help());
+ }
+
+ // optional .io.prometheus.client.MetricType type = 3;
+ if (has_type()) {
+ total_size += 1 +
+ ::google::protobuf::internal::WireFormatLite::EnumSize(this->type());
+ }
+
+ }
+ // repeated .io.prometheus.client.Metric metric = 4;
+ total_size += 1 * this->metric_size();
+ for (int i = 0; i < this->metric_size(); i++) {
+ total_size +=
+ ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
+ this->metric(i));
+ }
+
+ if (!unknown_fields().empty()) {
+ total_size +=
+ ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
+ unknown_fields());
+ }
+ GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
+ _cached_size_ = total_size;
+ GOOGLE_SAFE_CONCURRENT_WRITES_END();
+ return total_size;
+}
+
+void MetricFamily::MergeFrom(const ::google::protobuf::Message& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ const MetricFamily* source =
+ ::google::protobuf::internal::dynamic_cast_if_available(
+ &from);
+ if (source == NULL) {
+ ::google::protobuf::internal::ReflectionOps::Merge(from, this);
+ } else {
+ MergeFrom(*source);
+ }
+}
+
+void MetricFamily::MergeFrom(const MetricFamily& from) {
+ GOOGLE_CHECK_NE(&from, this);
+ metric_.MergeFrom(from.metric_);
+ if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
+ if (from.has_name()) {
+ set_name(from.name());
+ }
+ if (from.has_help()) {
+ set_help(from.help());
+ }
+ if (from.has_type()) {
+ set_type(from.type());
+ }
+ }
+ mutable_unknown_fields()->MergeFrom(from.unknown_fields());
+}
+
+void MetricFamily::CopyFrom(const ::google::protobuf::Message& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+void MetricFamily::CopyFrom(const MetricFamily& from) {
+ if (&from == this) return;
+ Clear();
+ MergeFrom(from);
+}
+
+bool MetricFamily::IsInitialized() const {
+
+ return true;
+}
+
+void MetricFamily::Swap(MetricFamily* other) {
+ if (other != this) {
+ std::swap(name_, other->name_);
+ std::swap(help_, other->help_);
+ std::swap(type_, other->type_);
+ metric_.Swap(&other->metric_);
+ std::swap(_has_bits_[0], other->_has_bits_[0]);
+ _unknown_fields_.Swap(&other->_unknown_fields_);
+ std::swap(_cached_size_, other->_cached_size_);
+ }
+}
+
+::google::protobuf::Metadata MetricFamily::GetMetadata() const {
+ protobuf_AssignDescriptorsOnce();
+ ::google::protobuf::Metadata metadata;
+ metadata.descriptor = MetricFamily_descriptor_;
+ metadata.reflection = MetricFamily_reflection_;
+ return metadata;
+}
+
+
+// @@protoc_insertion_point(namespace_scope)
+
+} // namespace client
+} // namespace prometheus
+} // namespace io
+
+// @@protoc_insertion_point(global_scope)
diff --git a/vendor/github.com/prometheus/client_model/cpp/metrics.pb.h b/vendor/github.com/prometheus/client_model/cpp/metrics.pb.h
new file mode 100644
index 0000000..206ba37
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/cpp/metrics.pb.h
@@ -0,0 +1,2072 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: metrics.proto
+
+#ifndef PROTOBUF_metrics_2eproto__INCLUDED
+#define PROTOBUF_metrics_2eproto__INCLUDED
+
+#include
+
+#include
+
+#if GOOGLE_PROTOBUF_VERSION < 2006000
+#error This file was generated by a newer version of protoc which is
+#error incompatible with your Protocol Buffer headers. Please update
+#error your headers.
+#endif
+#if 2006001 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
+#error This file was generated by an older version of protoc which is
+#error incompatible with your Protocol Buffer headers. Please
+#error regenerate this file with a newer version of protoc.
+#endif
+
+#include
+#include
+#include
+#include
+#include
+#include
+// @@protoc_insertion_point(includes)
+
+namespace io {
+namespace prometheus {
+namespace client {
+
+// Internal implementation detail -- do not call these.
+void protobuf_AddDesc_metrics_2eproto();
+void protobuf_AssignDesc_metrics_2eproto();
+void protobuf_ShutdownFile_metrics_2eproto();
+
+class LabelPair;
+class Gauge;
+class Counter;
+class Quantile;
+class Summary;
+class Untyped;
+class Histogram;
+class Bucket;
+class Metric;
+class MetricFamily;
+
+enum MetricType {
+ COUNTER = 0,
+ GAUGE = 1,
+ SUMMARY = 2,
+ UNTYPED = 3,
+ HISTOGRAM = 4
+};
+bool MetricType_IsValid(int value);
+const MetricType MetricType_MIN = COUNTER;
+const MetricType MetricType_MAX = HISTOGRAM;
+const int MetricType_ARRAYSIZE = MetricType_MAX + 1;
+
+const ::google::protobuf::EnumDescriptor* MetricType_descriptor();
+inline const ::std::string& MetricType_Name(MetricType value) {
+ return ::google::protobuf::internal::NameOfEnum(
+ MetricType_descriptor(), value);
+}
+inline bool MetricType_Parse(
+ const ::std::string& name, MetricType* value) {
+ return ::google::protobuf::internal::ParseNamedEnum(
+ MetricType_descriptor(), name, value);
+}
+// ===================================================================
+
+class LabelPair : public ::google::protobuf::Message {
+ public:
+ LabelPair();
+ virtual ~LabelPair();
+
+ LabelPair(const LabelPair& from);
+
+ inline LabelPair& operator=(const LabelPair& from) {
+ CopyFrom(from);
+ return *this;
+ }
+
+ inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
+ return _unknown_fields_;
+ }
+
+ inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
+ return &_unknown_fields_;
+ }
+
+ static const ::google::protobuf::Descriptor* descriptor();
+ static const LabelPair& default_instance();
+
+ void Swap(LabelPair* other);
+
+ // implements Message ----------------------------------------------
+
+ LabelPair* New() const;
+ void CopyFrom(const ::google::protobuf::Message& from);
+ void MergeFrom(const ::google::protobuf::Message& from);
+ void CopyFrom(const LabelPair& from);
+ void MergeFrom(const LabelPair& from);
+ void Clear();
+ bool IsInitialized() const;
+
+ int ByteSize() const;
+ bool MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input);
+ void SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const;
+ ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
+ int GetCachedSize() const { return _cached_size_; }
+ private:
+ void SharedCtor();
+ void SharedDtor();
+ void SetCachedSize(int size) const;
+ public:
+ ::google::protobuf::Metadata GetMetadata() const;
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ // optional string name = 1;
+ inline bool has_name() const;
+ inline void clear_name();
+ static const int kNameFieldNumber = 1;
+ inline const ::std::string& name() const;
+ inline void set_name(const ::std::string& value);
+ inline void set_name(const char* value);
+ inline void set_name(const char* value, size_t size);
+ inline ::std::string* mutable_name();
+ inline ::std::string* release_name();
+ inline void set_allocated_name(::std::string* name);
+
+ // optional string value = 2;
+ inline bool has_value() const;
+ inline void clear_value();
+ static const int kValueFieldNumber = 2;
+ inline const ::std::string& value() const;
+ inline void set_value(const ::std::string& value);
+ inline void set_value(const char* value);
+ inline void set_value(const char* value, size_t size);
+ inline ::std::string* mutable_value();
+ inline ::std::string* release_value();
+ inline void set_allocated_value(::std::string* value);
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.LabelPair)
+ private:
+ inline void set_has_name();
+ inline void clear_has_name();
+ inline void set_has_value();
+ inline void clear_has_value();
+
+ ::google::protobuf::UnknownFieldSet _unknown_fields_;
+
+ ::google::protobuf::uint32 _has_bits_[1];
+ mutable int _cached_size_;
+ ::std::string* name_;
+ ::std::string* value_;
+ friend void protobuf_AddDesc_metrics_2eproto();
+ friend void protobuf_AssignDesc_metrics_2eproto();
+ friend void protobuf_ShutdownFile_metrics_2eproto();
+
+ void InitAsDefaultInstance();
+ static LabelPair* default_instance_;
+};
+// -------------------------------------------------------------------
+
+class Gauge : public ::google::protobuf::Message {
+ public:
+ Gauge();
+ virtual ~Gauge();
+
+ Gauge(const Gauge& from);
+
+ inline Gauge& operator=(const Gauge& from) {
+ CopyFrom(from);
+ return *this;
+ }
+
+ inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
+ return _unknown_fields_;
+ }
+
+ inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
+ return &_unknown_fields_;
+ }
+
+ static const ::google::protobuf::Descriptor* descriptor();
+ static const Gauge& default_instance();
+
+ void Swap(Gauge* other);
+
+ // implements Message ----------------------------------------------
+
+ Gauge* New() const;
+ void CopyFrom(const ::google::protobuf::Message& from);
+ void MergeFrom(const ::google::protobuf::Message& from);
+ void CopyFrom(const Gauge& from);
+ void MergeFrom(const Gauge& from);
+ void Clear();
+ bool IsInitialized() const;
+
+ int ByteSize() const;
+ bool MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input);
+ void SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const;
+ ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
+ int GetCachedSize() const { return _cached_size_; }
+ private:
+ void SharedCtor();
+ void SharedDtor();
+ void SetCachedSize(int size) const;
+ public:
+ ::google::protobuf::Metadata GetMetadata() const;
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ // optional double value = 1;
+ inline bool has_value() const;
+ inline void clear_value();
+ static const int kValueFieldNumber = 1;
+ inline double value() const;
+ inline void set_value(double value);
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Gauge)
+ private:
+ inline void set_has_value();
+ inline void clear_has_value();
+
+ ::google::protobuf::UnknownFieldSet _unknown_fields_;
+
+ ::google::protobuf::uint32 _has_bits_[1];
+ mutable int _cached_size_;
+ double value_;
+ friend void protobuf_AddDesc_metrics_2eproto();
+ friend void protobuf_AssignDesc_metrics_2eproto();
+ friend void protobuf_ShutdownFile_metrics_2eproto();
+
+ void InitAsDefaultInstance();
+ static Gauge* default_instance_;
+};
+// -------------------------------------------------------------------
+
+class Counter : public ::google::protobuf::Message {
+ public:
+ Counter();
+ virtual ~Counter();
+
+ Counter(const Counter& from);
+
+ inline Counter& operator=(const Counter& from) {
+ CopyFrom(from);
+ return *this;
+ }
+
+ inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
+ return _unknown_fields_;
+ }
+
+ inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
+ return &_unknown_fields_;
+ }
+
+ static const ::google::protobuf::Descriptor* descriptor();
+ static const Counter& default_instance();
+
+ void Swap(Counter* other);
+
+ // implements Message ----------------------------------------------
+
+ Counter* New() const;
+ void CopyFrom(const ::google::protobuf::Message& from);
+ void MergeFrom(const ::google::protobuf::Message& from);
+ void CopyFrom(const Counter& from);
+ void MergeFrom(const Counter& from);
+ void Clear();
+ bool IsInitialized() const;
+
+ int ByteSize() const;
+ bool MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input);
+ void SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const;
+ ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
+ int GetCachedSize() const { return _cached_size_; }
+ private:
+ void SharedCtor();
+ void SharedDtor();
+ void SetCachedSize(int size) const;
+ public:
+ ::google::protobuf::Metadata GetMetadata() const;
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ // optional double value = 1;
+ inline bool has_value() const;
+ inline void clear_value();
+ static const int kValueFieldNumber = 1;
+ inline double value() const;
+ inline void set_value(double value);
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Counter)
+ private:
+ inline void set_has_value();
+ inline void clear_has_value();
+
+ ::google::protobuf::UnknownFieldSet _unknown_fields_;
+
+ ::google::protobuf::uint32 _has_bits_[1];
+ mutable int _cached_size_;
+ double value_;
+ friend void protobuf_AddDesc_metrics_2eproto();
+ friend void protobuf_AssignDesc_metrics_2eproto();
+ friend void protobuf_ShutdownFile_metrics_2eproto();
+
+ void InitAsDefaultInstance();
+ static Counter* default_instance_;
+};
+// -------------------------------------------------------------------
+
+class Quantile : public ::google::protobuf::Message {
+ public:
+ Quantile();
+ virtual ~Quantile();
+
+ Quantile(const Quantile& from);
+
+ inline Quantile& operator=(const Quantile& from) {
+ CopyFrom(from);
+ return *this;
+ }
+
+ inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
+ return _unknown_fields_;
+ }
+
+ inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
+ return &_unknown_fields_;
+ }
+
+ static const ::google::protobuf::Descriptor* descriptor();
+ static const Quantile& default_instance();
+
+ void Swap(Quantile* other);
+
+ // implements Message ----------------------------------------------
+
+ Quantile* New() const;
+ void CopyFrom(const ::google::protobuf::Message& from);
+ void MergeFrom(const ::google::protobuf::Message& from);
+ void CopyFrom(const Quantile& from);
+ void MergeFrom(const Quantile& from);
+ void Clear();
+ bool IsInitialized() const;
+
+ int ByteSize() const;
+ bool MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input);
+ void SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const;
+ ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
+ int GetCachedSize() const { return _cached_size_; }
+ private:
+ void SharedCtor();
+ void SharedDtor();
+ void SetCachedSize(int size) const;
+ public:
+ ::google::protobuf::Metadata GetMetadata() const;
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ // optional double quantile = 1;
+ inline bool has_quantile() const;
+ inline void clear_quantile();
+ static const int kQuantileFieldNumber = 1;
+ inline double quantile() const;
+ inline void set_quantile(double value);
+
+ // optional double value = 2;
+ inline bool has_value() const;
+ inline void clear_value();
+ static const int kValueFieldNumber = 2;
+ inline double value() const;
+ inline void set_value(double value);
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Quantile)
+ private:
+ inline void set_has_quantile();
+ inline void clear_has_quantile();
+ inline void set_has_value();
+ inline void clear_has_value();
+
+ ::google::protobuf::UnknownFieldSet _unknown_fields_;
+
+ ::google::protobuf::uint32 _has_bits_[1];
+ mutable int _cached_size_;
+ double quantile_;
+ double value_;
+ friend void protobuf_AddDesc_metrics_2eproto();
+ friend void protobuf_AssignDesc_metrics_2eproto();
+ friend void protobuf_ShutdownFile_metrics_2eproto();
+
+ void InitAsDefaultInstance();
+ static Quantile* default_instance_;
+};
+// -------------------------------------------------------------------
+
+class Summary : public ::google::protobuf::Message {
+ public:
+ Summary();
+ virtual ~Summary();
+
+ Summary(const Summary& from);
+
+ inline Summary& operator=(const Summary& from) {
+ CopyFrom(from);
+ return *this;
+ }
+
+ inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
+ return _unknown_fields_;
+ }
+
+ inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
+ return &_unknown_fields_;
+ }
+
+ static const ::google::protobuf::Descriptor* descriptor();
+ static const Summary& default_instance();
+
+ void Swap(Summary* other);
+
+ // implements Message ----------------------------------------------
+
+ Summary* New() const;
+ void CopyFrom(const ::google::protobuf::Message& from);
+ void MergeFrom(const ::google::protobuf::Message& from);
+ void CopyFrom(const Summary& from);
+ void MergeFrom(const Summary& from);
+ void Clear();
+ bool IsInitialized() const;
+
+ int ByteSize() const;
+ bool MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input);
+ void SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const;
+ ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
+ int GetCachedSize() const { return _cached_size_; }
+ private:
+ void SharedCtor();
+ void SharedDtor();
+ void SetCachedSize(int size) const;
+ public:
+ ::google::protobuf::Metadata GetMetadata() const;
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ // optional uint64 sample_count = 1;
+ inline bool has_sample_count() const;
+ inline void clear_sample_count();
+ static const int kSampleCountFieldNumber = 1;
+ inline ::google::protobuf::uint64 sample_count() const;
+ inline void set_sample_count(::google::protobuf::uint64 value);
+
+ // optional double sample_sum = 2;
+ inline bool has_sample_sum() const;
+ inline void clear_sample_sum();
+ static const int kSampleSumFieldNumber = 2;
+ inline double sample_sum() const;
+ inline void set_sample_sum(double value);
+
+ // repeated .io.prometheus.client.Quantile quantile = 3;
+ inline int quantile_size() const;
+ inline void clear_quantile();
+ static const int kQuantileFieldNumber = 3;
+ inline const ::io::prometheus::client::Quantile& quantile(int index) const;
+ inline ::io::prometheus::client::Quantile* mutable_quantile(int index);
+ inline ::io::prometheus::client::Quantile* add_quantile();
+ inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile >&
+ quantile() const;
+ inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile >*
+ mutable_quantile();
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Summary)
+ private:
+ inline void set_has_sample_count();
+ inline void clear_has_sample_count();
+ inline void set_has_sample_sum();
+ inline void clear_has_sample_sum();
+
+ ::google::protobuf::UnknownFieldSet _unknown_fields_;
+
+ ::google::protobuf::uint32 _has_bits_[1];
+ mutable int _cached_size_;
+ ::google::protobuf::uint64 sample_count_;
+ double sample_sum_;
+ ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile > quantile_;
+ friend void protobuf_AddDesc_metrics_2eproto();
+ friend void protobuf_AssignDesc_metrics_2eproto();
+ friend void protobuf_ShutdownFile_metrics_2eproto();
+
+ void InitAsDefaultInstance();
+ static Summary* default_instance_;
+};
+// -------------------------------------------------------------------
+
+class Untyped : public ::google::protobuf::Message {
+ public:
+ Untyped();
+ virtual ~Untyped();
+
+ Untyped(const Untyped& from);
+
+ inline Untyped& operator=(const Untyped& from) {
+ CopyFrom(from);
+ return *this;
+ }
+
+ inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
+ return _unknown_fields_;
+ }
+
+ inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
+ return &_unknown_fields_;
+ }
+
+ static const ::google::protobuf::Descriptor* descriptor();
+ static const Untyped& default_instance();
+
+ void Swap(Untyped* other);
+
+ // implements Message ----------------------------------------------
+
+ Untyped* New() const;
+ void CopyFrom(const ::google::protobuf::Message& from);
+ void MergeFrom(const ::google::protobuf::Message& from);
+ void CopyFrom(const Untyped& from);
+ void MergeFrom(const Untyped& from);
+ void Clear();
+ bool IsInitialized() const;
+
+ int ByteSize() const;
+ bool MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input);
+ void SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const;
+ ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
+ int GetCachedSize() const { return _cached_size_; }
+ private:
+ void SharedCtor();
+ void SharedDtor();
+ void SetCachedSize(int size) const;
+ public:
+ ::google::protobuf::Metadata GetMetadata() const;
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ // optional double value = 1;
+ inline bool has_value() const;
+ inline void clear_value();
+ static const int kValueFieldNumber = 1;
+ inline double value() const;
+ inline void set_value(double value);
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Untyped)
+ private:
+ inline void set_has_value();
+ inline void clear_has_value();
+
+ ::google::protobuf::UnknownFieldSet _unknown_fields_;
+
+ ::google::protobuf::uint32 _has_bits_[1];
+ mutable int _cached_size_;
+ double value_;
+ friend void protobuf_AddDesc_metrics_2eproto();
+ friend void protobuf_AssignDesc_metrics_2eproto();
+ friend void protobuf_ShutdownFile_metrics_2eproto();
+
+ void InitAsDefaultInstance();
+ static Untyped* default_instance_;
+};
+// -------------------------------------------------------------------
+
+class Histogram : public ::google::protobuf::Message {
+ public:
+ Histogram();
+ virtual ~Histogram();
+
+ Histogram(const Histogram& from);
+
+ inline Histogram& operator=(const Histogram& from) {
+ CopyFrom(from);
+ return *this;
+ }
+
+ inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
+ return _unknown_fields_;
+ }
+
+ inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
+ return &_unknown_fields_;
+ }
+
+ static const ::google::protobuf::Descriptor* descriptor();
+ static const Histogram& default_instance();
+
+ void Swap(Histogram* other);
+
+ // implements Message ----------------------------------------------
+
+ Histogram* New() const;
+ void CopyFrom(const ::google::protobuf::Message& from);
+ void MergeFrom(const ::google::protobuf::Message& from);
+ void CopyFrom(const Histogram& from);
+ void MergeFrom(const Histogram& from);
+ void Clear();
+ bool IsInitialized() const;
+
+ int ByteSize() const;
+ bool MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input);
+ void SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const;
+ ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
+ int GetCachedSize() const { return _cached_size_; }
+ private:
+ void SharedCtor();
+ void SharedDtor();
+ void SetCachedSize(int size) const;
+ public:
+ ::google::protobuf::Metadata GetMetadata() const;
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ // optional uint64 sample_count = 1;
+ inline bool has_sample_count() const;
+ inline void clear_sample_count();
+ static const int kSampleCountFieldNumber = 1;
+ inline ::google::protobuf::uint64 sample_count() const;
+ inline void set_sample_count(::google::protobuf::uint64 value);
+
+ // optional double sample_sum = 2;
+ inline bool has_sample_sum() const;
+ inline void clear_sample_sum();
+ static const int kSampleSumFieldNumber = 2;
+ inline double sample_sum() const;
+ inline void set_sample_sum(double value);
+
+ // repeated .io.prometheus.client.Bucket bucket = 3;
+ inline int bucket_size() const;
+ inline void clear_bucket();
+ static const int kBucketFieldNumber = 3;
+ inline const ::io::prometheus::client::Bucket& bucket(int index) const;
+ inline ::io::prometheus::client::Bucket* mutable_bucket(int index);
+ inline ::io::prometheus::client::Bucket* add_bucket();
+ inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket >&
+ bucket() const;
+ inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket >*
+ mutable_bucket();
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Histogram)
+ private:
+ inline void set_has_sample_count();
+ inline void clear_has_sample_count();
+ inline void set_has_sample_sum();
+ inline void clear_has_sample_sum();
+
+ ::google::protobuf::UnknownFieldSet _unknown_fields_;
+
+ ::google::protobuf::uint32 _has_bits_[1];
+ mutable int _cached_size_;
+ ::google::protobuf::uint64 sample_count_;
+ double sample_sum_;
+ ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket > bucket_;
+ friend void protobuf_AddDesc_metrics_2eproto();
+ friend void protobuf_AssignDesc_metrics_2eproto();
+ friend void protobuf_ShutdownFile_metrics_2eproto();
+
+ void InitAsDefaultInstance();
+ static Histogram* default_instance_;
+};
+// -------------------------------------------------------------------
+
+class Bucket : public ::google::protobuf::Message {
+ public:
+ Bucket();
+ virtual ~Bucket();
+
+ Bucket(const Bucket& from);
+
+ inline Bucket& operator=(const Bucket& from) {
+ CopyFrom(from);
+ return *this;
+ }
+
+ inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
+ return _unknown_fields_;
+ }
+
+ inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
+ return &_unknown_fields_;
+ }
+
+ static const ::google::protobuf::Descriptor* descriptor();
+ static const Bucket& default_instance();
+
+ void Swap(Bucket* other);
+
+ // implements Message ----------------------------------------------
+
+ Bucket* New() const;
+ void CopyFrom(const ::google::protobuf::Message& from);
+ void MergeFrom(const ::google::protobuf::Message& from);
+ void CopyFrom(const Bucket& from);
+ void MergeFrom(const Bucket& from);
+ void Clear();
+ bool IsInitialized() const;
+
+ int ByteSize() const;
+ bool MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input);
+ void SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const;
+ ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
+ int GetCachedSize() const { return _cached_size_; }
+ private:
+ void SharedCtor();
+ void SharedDtor();
+ void SetCachedSize(int size) const;
+ public:
+ ::google::protobuf::Metadata GetMetadata() const;
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ // optional uint64 cumulative_count = 1;
+ inline bool has_cumulative_count() const;
+ inline void clear_cumulative_count();
+ static const int kCumulativeCountFieldNumber = 1;
+ inline ::google::protobuf::uint64 cumulative_count() const;
+ inline void set_cumulative_count(::google::protobuf::uint64 value);
+
+ // optional double upper_bound = 2;
+ inline bool has_upper_bound() const;
+ inline void clear_upper_bound();
+ static const int kUpperBoundFieldNumber = 2;
+ inline double upper_bound() const;
+ inline void set_upper_bound(double value);
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Bucket)
+ private:
+ inline void set_has_cumulative_count();
+ inline void clear_has_cumulative_count();
+ inline void set_has_upper_bound();
+ inline void clear_has_upper_bound();
+
+ ::google::protobuf::UnknownFieldSet _unknown_fields_;
+
+ ::google::protobuf::uint32 _has_bits_[1];
+ mutable int _cached_size_;
+ ::google::protobuf::uint64 cumulative_count_;
+ double upper_bound_;
+ friend void protobuf_AddDesc_metrics_2eproto();
+ friend void protobuf_AssignDesc_metrics_2eproto();
+ friend void protobuf_ShutdownFile_metrics_2eproto();
+
+ void InitAsDefaultInstance();
+ static Bucket* default_instance_;
+};
+// -------------------------------------------------------------------
+
+class Metric : public ::google::protobuf::Message {
+ public:
+ Metric();
+ virtual ~Metric();
+
+ Metric(const Metric& from);
+
+ inline Metric& operator=(const Metric& from) {
+ CopyFrom(from);
+ return *this;
+ }
+
+ inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
+ return _unknown_fields_;
+ }
+
+ inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
+ return &_unknown_fields_;
+ }
+
+ static const ::google::protobuf::Descriptor* descriptor();
+ static const Metric& default_instance();
+
+ void Swap(Metric* other);
+
+ // implements Message ----------------------------------------------
+
+ Metric* New() const;
+ void CopyFrom(const ::google::protobuf::Message& from);
+ void MergeFrom(const ::google::protobuf::Message& from);
+ void CopyFrom(const Metric& from);
+ void MergeFrom(const Metric& from);
+ void Clear();
+ bool IsInitialized() const;
+
+ int ByteSize() const;
+ bool MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input);
+ void SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const;
+ ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
+ int GetCachedSize() const { return _cached_size_; }
+ private:
+ void SharedCtor();
+ void SharedDtor();
+ void SetCachedSize(int size) const;
+ public:
+ ::google::protobuf::Metadata GetMetadata() const;
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ // repeated .io.prometheus.client.LabelPair label = 1;
+ inline int label_size() const;
+ inline void clear_label();
+ static const int kLabelFieldNumber = 1;
+ inline const ::io::prometheus::client::LabelPair& label(int index) const;
+ inline ::io::prometheus::client::LabelPair* mutable_label(int index);
+ inline ::io::prometheus::client::LabelPair* add_label();
+ inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair >&
+ label() const;
+ inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair >*
+ mutable_label();
+
+ // optional .io.prometheus.client.Gauge gauge = 2;
+ inline bool has_gauge() const;
+ inline void clear_gauge();
+ static const int kGaugeFieldNumber = 2;
+ inline const ::io::prometheus::client::Gauge& gauge() const;
+ inline ::io::prometheus::client::Gauge* mutable_gauge();
+ inline ::io::prometheus::client::Gauge* release_gauge();
+ inline void set_allocated_gauge(::io::prometheus::client::Gauge* gauge);
+
+ // optional .io.prometheus.client.Counter counter = 3;
+ inline bool has_counter() const;
+ inline void clear_counter();
+ static const int kCounterFieldNumber = 3;
+ inline const ::io::prometheus::client::Counter& counter() const;
+ inline ::io::prometheus::client::Counter* mutable_counter();
+ inline ::io::prometheus::client::Counter* release_counter();
+ inline void set_allocated_counter(::io::prometheus::client::Counter* counter);
+
+ // optional .io.prometheus.client.Summary summary = 4;
+ inline bool has_summary() const;
+ inline void clear_summary();
+ static const int kSummaryFieldNumber = 4;
+ inline const ::io::prometheus::client::Summary& summary() const;
+ inline ::io::prometheus::client::Summary* mutable_summary();
+ inline ::io::prometheus::client::Summary* release_summary();
+ inline void set_allocated_summary(::io::prometheus::client::Summary* summary);
+
+ // optional .io.prometheus.client.Untyped untyped = 5;
+ inline bool has_untyped() const;
+ inline void clear_untyped();
+ static const int kUntypedFieldNumber = 5;
+ inline const ::io::prometheus::client::Untyped& untyped() const;
+ inline ::io::prometheus::client::Untyped* mutable_untyped();
+ inline ::io::prometheus::client::Untyped* release_untyped();
+ inline void set_allocated_untyped(::io::prometheus::client::Untyped* untyped);
+
+ // optional .io.prometheus.client.Histogram histogram = 7;
+ inline bool has_histogram() const;
+ inline void clear_histogram();
+ static const int kHistogramFieldNumber = 7;
+ inline const ::io::prometheus::client::Histogram& histogram() const;
+ inline ::io::prometheus::client::Histogram* mutable_histogram();
+ inline ::io::prometheus::client::Histogram* release_histogram();
+ inline void set_allocated_histogram(::io::prometheus::client::Histogram* histogram);
+
+ // optional int64 timestamp_ms = 6;
+ inline bool has_timestamp_ms() const;
+ inline void clear_timestamp_ms();
+ static const int kTimestampMsFieldNumber = 6;
+ inline ::google::protobuf::int64 timestamp_ms() const;
+ inline void set_timestamp_ms(::google::protobuf::int64 value);
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Metric)
+ private:
+ inline void set_has_gauge();
+ inline void clear_has_gauge();
+ inline void set_has_counter();
+ inline void clear_has_counter();
+ inline void set_has_summary();
+ inline void clear_has_summary();
+ inline void set_has_untyped();
+ inline void clear_has_untyped();
+ inline void set_has_histogram();
+ inline void clear_has_histogram();
+ inline void set_has_timestamp_ms();
+ inline void clear_has_timestamp_ms();
+
+ ::google::protobuf::UnknownFieldSet _unknown_fields_;
+
+ ::google::protobuf::uint32 _has_bits_[1];
+ mutable int _cached_size_;
+ ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair > label_;
+ ::io::prometheus::client::Gauge* gauge_;
+ ::io::prometheus::client::Counter* counter_;
+ ::io::prometheus::client::Summary* summary_;
+ ::io::prometheus::client::Untyped* untyped_;
+ ::io::prometheus::client::Histogram* histogram_;
+ ::google::protobuf::int64 timestamp_ms_;
+ friend void protobuf_AddDesc_metrics_2eproto();
+ friend void protobuf_AssignDesc_metrics_2eproto();
+ friend void protobuf_ShutdownFile_metrics_2eproto();
+
+ void InitAsDefaultInstance();
+ static Metric* default_instance_;
+};
+// -------------------------------------------------------------------
+
+class MetricFamily : public ::google::protobuf::Message {
+ public:
+ MetricFamily();
+ virtual ~MetricFamily();
+
+ MetricFamily(const MetricFamily& from);
+
+ inline MetricFamily& operator=(const MetricFamily& from) {
+ CopyFrom(from);
+ return *this;
+ }
+
+ inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
+ return _unknown_fields_;
+ }
+
+ inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
+ return &_unknown_fields_;
+ }
+
+ static const ::google::protobuf::Descriptor* descriptor();
+ static const MetricFamily& default_instance();
+
+ void Swap(MetricFamily* other);
+
+ // implements Message ----------------------------------------------
+
+ MetricFamily* New() const;
+ void CopyFrom(const ::google::protobuf::Message& from);
+ void MergeFrom(const ::google::protobuf::Message& from);
+ void CopyFrom(const MetricFamily& from);
+ void MergeFrom(const MetricFamily& from);
+ void Clear();
+ bool IsInitialized() const;
+
+ int ByteSize() const;
+ bool MergePartialFromCodedStream(
+ ::google::protobuf::io::CodedInputStream* input);
+ void SerializeWithCachedSizes(
+ ::google::protobuf::io::CodedOutputStream* output) const;
+ ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output) const;
+ int GetCachedSize() const { return _cached_size_; }
+ private:
+ void SharedCtor();
+ void SharedDtor();
+ void SetCachedSize(int size) const;
+ public:
+ ::google::protobuf::Metadata GetMetadata() const;
+
+ // nested types ----------------------------------------------------
+
+ // accessors -------------------------------------------------------
+
+ // optional string name = 1;
+ inline bool has_name() const;
+ inline void clear_name();
+ static const int kNameFieldNumber = 1;
+ inline const ::std::string& name() const;
+ inline void set_name(const ::std::string& value);
+ inline void set_name(const char* value);
+ inline void set_name(const char* value, size_t size);
+ inline ::std::string* mutable_name();
+ inline ::std::string* release_name();
+ inline void set_allocated_name(::std::string* name);
+
+ // optional string help = 2;
+ inline bool has_help() const;
+ inline void clear_help();
+ static const int kHelpFieldNumber = 2;
+ inline const ::std::string& help() const;
+ inline void set_help(const ::std::string& value);
+ inline void set_help(const char* value);
+ inline void set_help(const char* value, size_t size);
+ inline ::std::string* mutable_help();
+ inline ::std::string* release_help();
+ inline void set_allocated_help(::std::string* help);
+
+ // optional .io.prometheus.client.MetricType type = 3;
+ inline bool has_type() const;
+ inline void clear_type();
+ static const int kTypeFieldNumber = 3;
+ inline ::io::prometheus::client::MetricType type() const;
+ inline void set_type(::io::prometheus::client::MetricType value);
+
+ // repeated .io.prometheus.client.Metric metric = 4;
+ inline int metric_size() const;
+ inline void clear_metric();
+ static const int kMetricFieldNumber = 4;
+ inline const ::io::prometheus::client::Metric& metric(int index) const;
+ inline ::io::prometheus::client::Metric* mutable_metric(int index);
+ inline ::io::prometheus::client::Metric* add_metric();
+ inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric >&
+ metric() const;
+ inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric >*
+ mutable_metric();
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.MetricFamily)
+ private:
+ inline void set_has_name();
+ inline void clear_has_name();
+ inline void set_has_help();
+ inline void clear_has_help();
+ inline void set_has_type();
+ inline void clear_has_type();
+
+ ::google::protobuf::UnknownFieldSet _unknown_fields_;
+
+ ::google::protobuf::uint32 _has_bits_[1];
+ mutable int _cached_size_;
+ ::std::string* name_;
+ ::std::string* help_;
+ ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric > metric_;
+ int type_;
+ friend void protobuf_AddDesc_metrics_2eproto();
+ friend void protobuf_AssignDesc_metrics_2eproto();
+ friend void protobuf_ShutdownFile_metrics_2eproto();
+
+ void InitAsDefaultInstance();
+ static MetricFamily* default_instance_;
+};
+// ===================================================================
+
+
+// ===================================================================
+
+// LabelPair
+
+// optional string name = 1;
+inline bool LabelPair::has_name() const {
+ return (_has_bits_[0] & 0x00000001u) != 0;
+}
+inline void LabelPair::set_has_name() {
+ _has_bits_[0] |= 0x00000001u;
+}
+inline void LabelPair::clear_has_name() {
+ _has_bits_[0] &= ~0x00000001u;
+}
+inline void LabelPair::clear_name() {
+ if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ name_->clear();
+ }
+ clear_has_name();
+}
+inline const ::std::string& LabelPair::name() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.LabelPair.name)
+ return *name_;
+}
+inline void LabelPair::set_name(const ::std::string& value) {
+ set_has_name();
+ if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ name_ = new ::std::string;
+ }
+ name_->assign(value);
+ // @@protoc_insertion_point(field_set:io.prometheus.client.LabelPair.name)
+}
+inline void LabelPair::set_name(const char* value) {
+ set_has_name();
+ if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ name_ = new ::std::string;
+ }
+ name_->assign(value);
+ // @@protoc_insertion_point(field_set_char:io.prometheus.client.LabelPair.name)
+}
+inline void LabelPair::set_name(const char* value, size_t size) {
+ set_has_name();
+ if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ name_ = new ::std::string;
+ }
+ name_->assign(reinterpret_cast(value), size);
+ // @@protoc_insertion_point(field_set_pointer:io.prometheus.client.LabelPair.name)
+}
+inline ::std::string* LabelPair::mutable_name() {
+ set_has_name();
+ if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ name_ = new ::std::string;
+ }
+ // @@protoc_insertion_point(field_mutable:io.prometheus.client.LabelPair.name)
+ return name_;
+}
+inline ::std::string* LabelPair::release_name() {
+ clear_has_name();
+ if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ return NULL;
+ } else {
+ ::std::string* temp = name_;
+ name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return temp;
+ }
+}
+inline void LabelPair::set_allocated_name(::std::string* name) {
+ if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ delete name_;
+ }
+ if (name) {
+ set_has_name();
+ name_ = name;
+ } else {
+ clear_has_name();
+ name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ }
+ // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.LabelPair.name)
+}
+
+// optional string value = 2;
+inline bool LabelPair::has_value() const {
+ return (_has_bits_[0] & 0x00000002u) != 0;
+}
+inline void LabelPair::set_has_value() {
+ _has_bits_[0] |= 0x00000002u;
+}
+inline void LabelPair::clear_has_value() {
+ _has_bits_[0] &= ~0x00000002u;
+}
+inline void LabelPair::clear_value() {
+ if (value_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ value_->clear();
+ }
+ clear_has_value();
+}
+inline const ::std::string& LabelPair::value() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.LabelPair.value)
+ return *value_;
+}
+inline void LabelPair::set_value(const ::std::string& value) {
+ set_has_value();
+ if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ value_ = new ::std::string;
+ }
+ value_->assign(value);
+ // @@protoc_insertion_point(field_set:io.prometheus.client.LabelPair.value)
+}
+inline void LabelPair::set_value(const char* value) {
+ set_has_value();
+ if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ value_ = new ::std::string;
+ }
+ value_->assign(value);
+ // @@protoc_insertion_point(field_set_char:io.prometheus.client.LabelPair.value)
+}
+inline void LabelPair::set_value(const char* value, size_t size) {
+ set_has_value();
+ if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ value_ = new ::std::string;
+ }
+ value_->assign(reinterpret_cast(value), size);
+ // @@protoc_insertion_point(field_set_pointer:io.prometheus.client.LabelPair.value)
+}
+inline ::std::string* LabelPair::mutable_value() {
+ set_has_value();
+ if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ value_ = new ::std::string;
+ }
+ // @@protoc_insertion_point(field_mutable:io.prometheus.client.LabelPair.value)
+ return value_;
+}
+inline ::std::string* LabelPair::release_value() {
+ clear_has_value();
+ if (value_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ return NULL;
+ } else {
+ ::std::string* temp = value_;
+ value_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return temp;
+ }
+}
+inline void LabelPair::set_allocated_value(::std::string* value) {
+ if (value_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ delete value_;
+ }
+ if (value) {
+ set_has_value();
+ value_ = value;
+ } else {
+ clear_has_value();
+ value_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ }
+ // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.LabelPair.value)
+}
+
+// -------------------------------------------------------------------
+
+// Gauge
+
+// optional double value = 1;
+inline bool Gauge::has_value() const {
+ return (_has_bits_[0] & 0x00000001u) != 0;
+}
+inline void Gauge::set_has_value() {
+ _has_bits_[0] |= 0x00000001u;
+}
+inline void Gauge::clear_has_value() {
+ _has_bits_[0] &= ~0x00000001u;
+}
+inline void Gauge::clear_value() {
+ value_ = 0;
+ clear_has_value();
+}
+inline double Gauge::value() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Gauge.value)
+ return value_;
+}
+inline void Gauge::set_value(double value) {
+ set_has_value();
+ value_ = value;
+ // @@protoc_insertion_point(field_set:io.prometheus.client.Gauge.value)
+}
+
+// -------------------------------------------------------------------
+
+// Counter
+
+// optional double value = 1;
+inline bool Counter::has_value() const {
+ return (_has_bits_[0] & 0x00000001u) != 0;
+}
+inline void Counter::set_has_value() {
+ _has_bits_[0] |= 0x00000001u;
+}
+inline void Counter::clear_has_value() {
+ _has_bits_[0] &= ~0x00000001u;
+}
+inline void Counter::clear_value() {
+ value_ = 0;
+ clear_has_value();
+}
+inline double Counter::value() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Counter.value)
+ return value_;
+}
+inline void Counter::set_value(double value) {
+ set_has_value();
+ value_ = value;
+ // @@protoc_insertion_point(field_set:io.prometheus.client.Counter.value)
+}
+
+// -------------------------------------------------------------------
+
+// Quantile
+
+// optional double quantile = 1;
+inline bool Quantile::has_quantile() const {
+ return (_has_bits_[0] & 0x00000001u) != 0;
+}
+inline void Quantile::set_has_quantile() {
+ _has_bits_[0] |= 0x00000001u;
+}
+inline void Quantile::clear_has_quantile() {
+ _has_bits_[0] &= ~0x00000001u;
+}
+inline void Quantile::clear_quantile() {
+ quantile_ = 0;
+ clear_has_quantile();
+}
+inline double Quantile::quantile() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Quantile.quantile)
+ return quantile_;
+}
+inline void Quantile::set_quantile(double value) {
+ set_has_quantile();
+ quantile_ = value;
+ // @@protoc_insertion_point(field_set:io.prometheus.client.Quantile.quantile)
+}
+
+// optional double value = 2;
+inline bool Quantile::has_value() const {
+ return (_has_bits_[0] & 0x00000002u) != 0;
+}
+inline void Quantile::set_has_value() {
+ _has_bits_[0] |= 0x00000002u;
+}
+inline void Quantile::clear_has_value() {
+ _has_bits_[0] &= ~0x00000002u;
+}
+inline void Quantile::clear_value() {
+ value_ = 0;
+ clear_has_value();
+}
+inline double Quantile::value() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Quantile.value)
+ return value_;
+}
+inline void Quantile::set_value(double value) {
+ set_has_value();
+ value_ = value;
+ // @@protoc_insertion_point(field_set:io.prometheus.client.Quantile.value)
+}
+
+// -------------------------------------------------------------------
+
+// Summary
+
+// optional uint64 sample_count = 1;
+inline bool Summary::has_sample_count() const {
+ return (_has_bits_[0] & 0x00000001u) != 0;
+}
+inline void Summary::set_has_sample_count() {
+ _has_bits_[0] |= 0x00000001u;
+}
+inline void Summary::clear_has_sample_count() {
+ _has_bits_[0] &= ~0x00000001u;
+}
+inline void Summary::clear_sample_count() {
+ sample_count_ = GOOGLE_ULONGLONG(0);
+ clear_has_sample_count();
+}
+inline ::google::protobuf::uint64 Summary::sample_count() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Summary.sample_count)
+ return sample_count_;
+}
+inline void Summary::set_sample_count(::google::protobuf::uint64 value) {
+ set_has_sample_count();
+ sample_count_ = value;
+ // @@protoc_insertion_point(field_set:io.prometheus.client.Summary.sample_count)
+}
+
+// optional double sample_sum = 2;
+inline bool Summary::has_sample_sum() const {
+ return (_has_bits_[0] & 0x00000002u) != 0;
+}
+inline void Summary::set_has_sample_sum() {
+ _has_bits_[0] |= 0x00000002u;
+}
+inline void Summary::clear_has_sample_sum() {
+ _has_bits_[0] &= ~0x00000002u;
+}
+inline void Summary::clear_sample_sum() {
+ sample_sum_ = 0;
+ clear_has_sample_sum();
+}
+inline double Summary::sample_sum() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Summary.sample_sum)
+ return sample_sum_;
+}
+inline void Summary::set_sample_sum(double value) {
+ set_has_sample_sum();
+ sample_sum_ = value;
+ // @@protoc_insertion_point(field_set:io.prometheus.client.Summary.sample_sum)
+}
+
+// repeated .io.prometheus.client.Quantile quantile = 3;
+inline int Summary::quantile_size() const {
+ return quantile_.size();
+}
+inline void Summary::clear_quantile() {
+ quantile_.Clear();
+}
+inline const ::io::prometheus::client::Quantile& Summary::quantile(int index) const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Summary.quantile)
+ return quantile_.Get(index);
+}
+inline ::io::prometheus::client::Quantile* Summary::mutable_quantile(int index) {
+ // @@protoc_insertion_point(field_mutable:io.prometheus.client.Summary.quantile)
+ return quantile_.Mutable(index);
+}
+inline ::io::prometheus::client::Quantile* Summary::add_quantile() {
+ // @@protoc_insertion_point(field_add:io.prometheus.client.Summary.quantile)
+ return quantile_.Add();
+}
+inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile >&
+Summary::quantile() const {
+ // @@protoc_insertion_point(field_list:io.prometheus.client.Summary.quantile)
+ return quantile_;
+}
+inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Quantile >*
+Summary::mutable_quantile() {
+ // @@protoc_insertion_point(field_mutable_list:io.prometheus.client.Summary.quantile)
+ return &quantile_;
+}
+
+// -------------------------------------------------------------------
+
+// Untyped
+
+// optional double value = 1;
+inline bool Untyped::has_value() const {
+ return (_has_bits_[0] & 0x00000001u) != 0;
+}
+inline void Untyped::set_has_value() {
+ _has_bits_[0] |= 0x00000001u;
+}
+inline void Untyped::clear_has_value() {
+ _has_bits_[0] &= ~0x00000001u;
+}
+inline void Untyped::clear_value() {
+ value_ = 0;
+ clear_has_value();
+}
+inline double Untyped::value() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Untyped.value)
+ return value_;
+}
+inline void Untyped::set_value(double value) {
+ set_has_value();
+ value_ = value;
+ // @@protoc_insertion_point(field_set:io.prometheus.client.Untyped.value)
+}
+
+// -------------------------------------------------------------------
+
+// Histogram
+
+// optional uint64 sample_count = 1;
+inline bool Histogram::has_sample_count() const {
+ return (_has_bits_[0] & 0x00000001u) != 0;
+}
+inline void Histogram::set_has_sample_count() {
+ _has_bits_[0] |= 0x00000001u;
+}
+inline void Histogram::clear_has_sample_count() {
+ _has_bits_[0] &= ~0x00000001u;
+}
+inline void Histogram::clear_sample_count() {
+ sample_count_ = GOOGLE_ULONGLONG(0);
+ clear_has_sample_count();
+}
+inline ::google::protobuf::uint64 Histogram::sample_count() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Histogram.sample_count)
+ return sample_count_;
+}
+inline void Histogram::set_sample_count(::google::protobuf::uint64 value) {
+ set_has_sample_count();
+ sample_count_ = value;
+ // @@protoc_insertion_point(field_set:io.prometheus.client.Histogram.sample_count)
+}
+
+// optional double sample_sum = 2;
+inline bool Histogram::has_sample_sum() const {
+ return (_has_bits_[0] & 0x00000002u) != 0;
+}
+inline void Histogram::set_has_sample_sum() {
+ _has_bits_[0] |= 0x00000002u;
+}
+inline void Histogram::clear_has_sample_sum() {
+ _has_bits_[0] &= ~0x00000002u;
+}
+inline void Histogram::clear_sample_sum() {
+ sample_sum_ = 0;
+ clear_has_sample_sum();
+}
+inline double Histogram::sample_sum() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Histogram.sample_sum)
+ return sample_sum_;
+}
+inline void Histogram::set_sample_sum(double value) {
+ set_has_sample_sum();
+ sample_sum_ = value;
+ // @@protoc_insertion_point(field_set:io.prometheus.client.Histogram.sample_sum)
+}
+
+// repeated .io.prometheus.client.Bucket bucket = 3;
+inline int Histogram::bucket_size() const {
+ return bucket_.size();
+}
+inline void Histogram::clear_bucket() {
+ bucket_.Clear();
+}
+inline const ::io::prometheus::client::Bucket& Histogram::bucket(int index) const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Histogram.bucket)
+ return bucket_.Get(index);
+}
+inline ::io::prometheus::client::Bucket* Histogram::mutable_bucket(int index) {
+ // @@protoc_insertion_point(field_mutable:io.prometheus.client.Histogram.bucket)
+ return bucket_.Mutable(index);
+}
+inline ::io::prometheus::client::Bucket* Histogram::add_bucket() {
+ // @@protoc_insertion_point(field_add:io.prometheus.client.Histogram.bucket)
+ return bucket_.Add();
+}
+inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket >&
+Histogram::bucket() const {
+ // @@protoc_insertion_point(field_list:io.prometheus.client.Histogram.bucket)
+ return bucket_;
+}
+inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Bucket >*
+Histogram::mutable_bucket() {
+ // @@protoc_insertion_point(field_mutable_list:io.prometheus.client.Histogram.bucket)
+ return &bucket_;
+}
+
+// -------------------------------------------------------------------
+
+// Bucket
+
+// optional uint64 cumulative_count = 1;
+inline bool Bucket::has_cumulative_count() const {
+ return (_has_bits_[0] & 0x00000001u) != 0;
+}
+inline void Bucket::set_has_cumulative_count() {
+ _has_bits_[0] |= 0x00000001u;
+}
+inline void Bucket::clear_has_cumulative_count() {
+ _has_bits_[0] &= ~0x00000001u;
+}
+inline void Bucket::clear_cumulative_count() {
+ cumulative_count_ = GOOGLE_ULONGLONG(0);
+ clear_has_cumulative_count();
+}
+inline ::google::protobuf::uint64 Bucket::cumulative_count() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Bucket.cumulative_count)
+ return cumulative_count_;
+}
+inline void Bucket::set_cumulative_count(::google::protobuf::uint64 value) {
+ set_has_cumulative_count();
+ cumulative_count_ = value;
+ // @@protoc_insertion_point(field_set:io.prometheus.client.Bucket.cumulative_count)
+}
+
+// optional double upper_bound = 2;
+inline bool Bucket::has_upper_bound() const {
+ return (_has_bits_[0] & 0x00000002u) != 0;
+}
+inline void Bucket::set_has_upper_bound() {
+ _has_bits_[0] |= 0x00000002u;
+}
+inline void Bucket::clear_has_upper_bound() {
+ _has_bits_[0] &= ~0x00000002u;
+}
+inline void Bucket::clear_upper_bound() {
+ upper_bound_ = 0;
+ clear_has_upper_bound();
+}
+inline double Bucket::upper_bound() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Bucket.upper_bound)
+ return upper_bound_;
+}
+inline void Bucket::set_upper_bound(double value) {
+ set_has_upper_bound();
+ upper_bound_ = value;
+ // @@protoc_insertion_point(field_set:io.prometheus.client.Bucket.upper_bound)
+}
+
+// -------------------------------------------------------------------
+
+// Metric
+
+// repeated .io.prometheus.client.LabelPair label = 1;
+inline int Metric::label_size() const {
+ return label_.size();
+}
+inline void Metric::clear_label() {
+ label_.Clear();
+}
+inline const ::io::prometheus::client::LabelPair& Metric::label(int index) const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.label)
+ return label_.Get(index);
+}
+inline ::io::prometheus::client::LabelPair* Metric::mutable_label(int index) {
+ // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.label)
+ return label_.Mutable(index);
+}
+inline ::io::prometheus::client::LabelPair* Metric::add_label() {
+ // @@protoc_insertion_point(field_add:io.prometheus.client.Metric.label)
+ return label_.Add();
+}
+inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair >&
+Metric::label() const {
+ // @@protoc_insertion_point(field_list:io.prometheus.client.Metric.label)
+ return label_;
+}
+inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::LabelPair >*
+Metric::mutable_label() {
+ // @@protoc_insertion_point(field_mutable_list:io.prometheus.client.Metric.label)
+ return &label_;
+}
+
+// optional .io.prometheus.client.Gauge gauge = 2;
+inline bool Metric::has_gauge() const {
+ return (_has_bits_[0] & 0x00000002u) != 0;
+}
+inline void Metric::set_has_gauge() {
+ _has_bits_[0] |= 0x00000002u;
+}
+inline void Metric::clear_has_gauge() {
+ _has_bits_[0] &= ~0x00000002u;
+}
+inline void Metric::clear_gauge() {
+ if (gauge_ != NULL) gauge_->::io::prometheus::client::Gauge::Clear();
+ clear_has_gauge();
+}
+inline const ::io::prometheus::client::Gauge& Metric::gauge() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.gauge)
+ return gauge_ != NULL ? *gauge_ : *default_instance_->gauge_;
+}
+inline ::io::prometheus::client::Gauge* Metric::mutable_gauge() {
+ set_has_gauge();
+ if (gauge_ == NULL) gauge_ = new ::io::prometheus::client::Gauge;
+ // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.gauge)
+ return gauge_;
+}
+inline ::io::prometheus::client::Gauge* Metric::release_gauge() {
+ clear_has_gauge();
+ ::io::prometheus::client::Gauge* temp = gauge_;
+ gauge_ = NULL;
+ return temp;
+}
+inline void Metric::set_allocated_gauge(::io::prometheus::client::Gauge* gauge) {
+ delete gauge_;
+ gauge_ = gauge;
+ if (gauge) {
+ set_has_gauge();
+ } else {
+ clear_has_gauge();
+ }
+ // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.gauge)
+}
+
+// optional .io.prometheus.client.Counter counter = 3;
+inline bool Metric::has_counter() const {
+ return (_has_bits_[0] & 0x00000004u) != 0;
+}
+inline void Metric::set_has_counter() {
+ _has_bits_[0] |= 0x00000004u;
+}
+inline void Metric::clear_has_counter() {
+ _has_bits_[0] &= ~0x00000004u;
+}
+inline void Metric::clear_counter() {
+ if (counter_ != NULL) counter_->::io::prometheus::client::Counter::Clear();
+ clear_has_counter();
+}
+inline const ::io::prometheus::client::Counter& Metric::counter() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.counter)
+ return counter_ != NULL ? *counter_ : *default_instance_->counter_;
+}
+inline ::io::prometheus::client::Counter* Metric::mutable_counter() {
+ set_has_counter();
+ if (counter_ == NULL) counter_ = new ::io::prometheus::client::Counter;
+ // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.counter)
+ return counter_;
+}
+inline ::io::prometheus::client::Counter* Metric::release_counter() {
+ clear_has_counter();
+ ::io::prometheus::client::Counter* temp = counter_;
+ counter_ = NULL;
+ return temp;
+}
+inline void Metric::set_allocated_counter(::io::prometheus::client::Counter* counter) {
+ delete counter_;
+ counter_ = counter;
+ if (counter) {
+ set_has_counter();
+ } else {
+ clear_has_counter();
+ }
+ // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.counter)
+}
+
+// optional .io.prometheus.client.Summary summary = 4;
+inline bool Metric::has_summary() const {
+ return (_has_bits_[0] & 0x00000008u) != 0;
+}
+inline void Metric::set_has_summary() {
+ _has_bits_[0] |= 0x00000008u;
+}
+inline void Metric::clear_has_summary() {
+ _has_bits_[0] &= ~0x00000008u;
+}
+inline void Metric::clear_summary() {
+ if (summary_ != NULL) summary_->::io::prometheus::client::Summary::Clear();
+ clear_has_summary();
+}
+inline const ::io::prometheus::client::Summary& Metric::summary() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.summary)
+ return summary_ != NULL ? *summary_ : *default_instance_->summary_;
+}
+inline ::io::prometheus::client::Summary* Metric::mutable_summary() {
+ set_has_summary();
+ if (summary_ == NULL) summary_ = new ::io::prometheus::client::Summary;
+ // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.summary)
+ return summary_;
+}
+inline ::io::prometheus::client::Summary* Metric::release_summary() {
+ clear_has_summary();
+ ::io::prometheus::client::Summary* temp = summary_;
+ summary_ = NULL;
+ return temp;
+}
+inline void Metric::set_allocated_summary(::io::prometheus::client::Summary* summary) {
+ delete summary_;
+ summary_ = summary;
+ if (summary) {
+ set_has_summary();
+ } else {
+ clear_has_summary();
+ }
+ // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.summary)
+}
+
+// optional .io.prometheus.client.Untyped untyped = 5;
+inline bool Metric::has_untyped() const {
+ return (_has_bits_[0] & 0x00000010u) != 0;
+}
+inline void Metric::set_has_untyped() {
+ _has_bits_[0] |= 0x00000010u;
+}
+inline void Metric::clear_has_untyped() {
+ _has_bits_[0] &= ~0x00000010u;
+}
+inline void Metric::clear_untyped() {
+ if (untyped_ != NULL) untyped_->::io::prometheus::client::Untyped::Clear();
+ clear_has_untyped();
+}
+inline const ::io::prometheus::client::Untyped& Metric::untyped() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.untyped)
+ return untyped_ != NULL ? *untyped_ : *default_instance_->untyped_;
+}
+inline ::io::prometheus::client::Untyped* Metric::mutable_untyped() {
+ set_has_untyped();
+ if (untyped_ == NULL) untyped_ = new ::io::prometheus::client::Untyped;
+ // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.untyped)
+ return untyped_;
+}
+inline ::io::prometheus::client::Untyped* Metric::release_untyped() {
+ clear_has_untyped();
+ ::io::prometheus::client::Untyped* temp = untyped_;
+ untyped_ = NULL;
+ return temp;
+}
+inline void Metric::set_allocated_untyped(::io::prometheus::client::Untyped* untyped) {
+ delete untyped_;
+ untyped_ = untyped;
+ if (untyped) {
+ set_has_untyped();
+ } else {
+ clear_has_untyped();
+ }
+ // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.untyped)
+}
+
+// optional .io.prometheus.client.Histogram histogram = 7;
+inline bool Metric::has_histogram() const {
+ return (_has_bits_[0] & 0x00000020u) != 0;
+}
+inline void Metric::set_has_histogram() {
+ _has_bits_[0] |= 0x00000020u;
+}
+inline void Metric::clear_has_histogram() {
+ _has_bits_[0] &= ~0x00000020u;
+}
+inline void Metric::clear_histogram() {
+ if (histogram_ != NULL) histogram_->::io::prometheus::client::Histogram::Clear();
+ clear_has_histogram();
+}
+inline const ::io::prometheus::client::Histogram& Metric::histogram() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.histogram)
+ return histogram_ != NULL ? *histogram_ : *default_instance_->histogram_;
+}
+inline ::io::prometheus::client::Histogram* Metric::mutable_histogram() {
+ set_has_histogram();
+ if (histogram_ == NULL) histogram_ = new ::io::prometheus::client::Histogram;
+ // @@protoc_insertion_point(field_mutable:io.prometheus.client.Metric.histogram)
+ return histogram_;
+}
+inline ::io::prometheus::client::Histogram* Metric::release_histogram() {
+ clear_has_histogram();
+ ::io::prometheus::client::Histogram* temp = histogram_;
+ histogram_ = NULL;
+ return temp;
+}
+inline void Metric::set_allocated_histogram(::io::prometheus::client::Histogram* histogram) {
+ delete histogram_;
+ histogram_ = histogram;
+ if (histogram) {
+ set_has_histogram();
+ } else {
+ clear_has_histogram();
+ }
+ // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.Metric.histogram)
+}
+
+// optional int64 timestamp_ms = 6;
+inline bool Metric::has_timestamp_ms() const {
+ return (_has_bits_[0] & 0x00000040u) != 0;
+}
+inline void Metric::set_has_timestamp_ms() {
+ _has_bits_[0] |= 0x00000040u;
+}
+inline void Metric::clear_has_timestamp_ms() {
+ _has_bits_[0] &= ~0x00000040u;
+}
+inline void Metric::clear_timestamp_ms() {
+ timestamp_ms_ = GOOGLE_LONGLONG(0);
+ clear_has_timestamp_ms();
+}
+inline ::google::protobuf::int64 Metric::timestamp_ms() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.Metric.timestamp_ms)
+ return timestamp_ms_;
+}
+inline void Metric::set_timestamp_ms(::google::protobuf::int64 value) {
+ set_has_timestamp_ms();
+ timestamp_ms_ = value;
+ // @@protoc_insertion_point(field_set:io.prometheus.client.Metric.timestamp_ms)
+}
+
+// -------------------------------------------------------------------
+
+// MetricFamily
+
+// optional string name = 1;
+inline bool MetricFamily::has_name() const {
+ return (_has_bits_[0] & 0x00000001u) != 0;
+}
+inline void MetricFamily::set_has_name() {
+ _has_bits_[0] |= 0x00000001u;
+}
+inline void MetricFamily::clear_has_name() {
+ _has_bits_[0] &= ~0x00000001u;
+}
+inline void MetricFamily::clear_name() {
+ if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ name_->clear();
+ }
+ clear_has_name();
+}
+inline const ::std::string& MetricFamily::name() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.MetricFamily.name)
+ return *name_;
+}
+inline void MetricFamily::set_name(const ::std::string& value) {
+ set_has_name();
+ if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ name_ = new ::std::string;
+ }
+ name_->assign(value);
+ // @@protoc_insertion_point(field_set:io.prometheus.client.MetricFamily.name)
+}
+inline void MetricFamily::set_name(const char* value) {
+ set_has_name();
+ if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ name_ = new ::std::string;
+ }
+ name_->assign(value);
+ // @@protoc_insertion_point(field_set_char:io.prometheus.client.MetricFamily.name)
+}
+inline void MetricFamily::set_name(const char* value, size_t size) {
+ set_has_name();
+ if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ name_ = new ::std::string;
+ }
+ name_->assign(reinterpret_cast(value), size);
+ // @@protoc_insertion_point(field_set_pointer:io.prometheus.client.MetricFamily.name)
+}
+inline ::std::string* MetricFamily::mutable_name() {
+ set_has_name();
+ if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ name_ = new ::std::string;
+ }
+ // @@protoc_insertion_point(field_mutable:io.prometheus.client.MetricFamily.name)
+ return name_;
+}
+inline ::std::string* MetricFamily::release_name() {
+ clear_has_name();
+ if (name_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ return NULL;
+ } else {
+ ::std::string* temp = name_;
+ name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return temp;
+ }
+}
+inline void MetricFamily::set_allocated_name(::std::string* name) {
+ if (name_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ delete name_;
+ }
+ if (name) {
+ set_has_name();
+ name_ = name;
+ } else {
+ clear_has_name();
+ name_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ }
+ // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.MetricFamily.name)
+}
+
+// optional string help = 2;
+inline bool MetricFamily::has_help() const {
+ return (_has_bits_[0] & 0x00000002u) != 0;
+}
+inline void MetricFamily::set_has_help() {
+ _has_bits_[0] |= 0x00000002u;
+}
+inline void MetricFamily::clear_has_help() {
+ _has_bits_[0] &= ~0x00000002u;
+}
+inline void MetricFamily::clear_help() {
+ if (help_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ help_->clear();
+ }
+ clear_has_help();
+}
+inline const ::std::string& MetricFamily::help() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.MetricFamily.help)
+ return *help_;
+}
+inline void MetricFamily::set_help(const ::std::string& value) {
+ set_has_help();
+ if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ help_ = new ::std::string;
+ }
+ help_->assign(value);
+ // @@protoc_insertion_point(field_set:io.prometheus.client.MetricFamily.help)
+}
+inline void MetricFamily::set_help(const char* value) {
+ set_has_help();
+ if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ help_ = new ::std::string;
+ }
+ help_->assign(value);
+ // @@protoc_insertion_point(field_set_char:io.prometheus.client.MetricFamily.help)
+}
+inline void MetricFamily::set_help(const char* value, size_t size) {
+ set_has_help();
+ if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ help_ = new ::std::string;
+ }
+ help_->assign(reinterpret_cast(value), size);
+ // @@protoc_insertion_point(field_set_pointer:io.prometheus.client.MetricFamily.help)
+}
+inline ::std::string* MetricFamily::mutable_help() {
+ set_has_help();
+ if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ help_ = new ::std::string;
+ }
+ // @@protoc_insertion_point(field_mutable:io.prometheus.client.MetricFamily.help)
+ return help_;
+}
+inline ::std::string* MetricFamily::release_help() {
+ clear_has_help();
+ if (help_ == &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ return NULL;
+ } else {
+ ::std::string* temp = help_;
+ help_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ return temp;
+ }
+}
+inline void MetricFamily::set_allocated_help(::std::string* help) {
+ if (help_ != &::google::protobuf::internal::GetEmptyStringAlreadyInited()) {
+ delete help_;
+ }
+ if (help) {
+ set_has_help();
+ help_ = help;
+ } else {
+ clear_has_help();
+ help_ = const_cast< ::std::string*>(&::google::protobuf::internal::GetEmptyStringAlreadyInited());
+ }
+ // @@protoc_insertion_point(field_set_allocated:io.prometheus.client.MetricFamily.help)
+}
+
+// optional .io.prometheus.client.MetricType type = 3;
+inline bool MetricFamily::has_type() const {
+ return (_has_bits_[0] & 0x00000004u) != 0;
+}
+inline void MetricFamily::set_has_type() {
+ _has_bits_[0] |= 0x00000004u;
+}
+inline void MetricFamily::clear_has_type() {
+ _has_bits_[0] &= ~0x00000004u;
+}
+inline void MetricFamily::clear_type() {
+ type_ = 0;
+ clear_has_type();
+}
+inline ::io::prometheus::client::MetricType MetricFamily::type() const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.MetricFamily.type)
+ return static_cast< ::io::prometheus::client::MetricType >(type_);
+}
+inline void MetricFamily::set_type(::io::prometheus::client::MetricType value) {
+ assert(::io::prometheus::client::MetricType_IsValid(value));
+ set_has_type();
+ type_ = value;
+ // @@protoc_insertion_point(field_set:io.prometheus.client.MetricFamily.type)
+}
+
+// repeated .io.prometheus.client.Metric metric = 4;
+inline int MetricFamily::metric_size() const {
+ return metric_.size();
+}
+inline void MetricFamily::clear_metric() {
+ metric_.Clear();
+}
+inline const ::io::prometheus::client::Metric& MetricFamily::metric(int index) const {
+ // @@protoc_insertion_point(field_get:io.prometheus.client.MetricFamily.metric)
+ return metric_.Get(index);
+}
+inline ::io::prometheus::client::Metric* MetricFamily::mutable_metric(int index) {
+ // @@protoc_insertion_point(field_mutable:io.prometheus.client.MetricFamily.metric)
+ return metric_.Mutable(index);
+}
+inline ::io::prometheus::client::Metric* MetricFamily::add_metric() {
+ // @@protoc_insertion_point(field_add:io.prometheus.client.MetricFamily.metric)
+ return metric_.Add();
+}
+inline const ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric >&
+MetricFamily::metric() const {
+ // @@protoc_insertion_point(field_list:io.prometheus.client.MetricFamily.metric)
+ return metric_;
+}
+inline ::google::protobuf::RepeatedPtrField< ::io::prometheus::client::Metric >*
+MetricFamily::mutable_metric() {
+ // @@protoc_insertion_point(field_mutable_list:io.prometheus.client.MetricFamily.metric)
+ return &metric_;
+}
+
+
+// @@protoc_insertion_point(namespace_scope)
+
+} // namespace client
+} // namespace prometheus
+} // namespace io
+
+#ifndef SWIG
+namespace google {
+namespace protobuf {
+
+template <> struct is_proto_enum< ::io::prometheus::client::MetricType> : ::google::protobuf::internal::true_type {};
+template <>
+inline const EnumDescriptor* GetEnumDescriptor< ::io::prometheus::client::MetricType>() {
+ return ::io::prometheus::client::MetricType_descriptor();
+}
+
+} // namespace google
+} // namespace protobuf
+#endif // SWIG
+
+// @@protoc_insertion_point(global_scope)
+
+#endif // PROTOBUF_metrics_2eproto__INCLUDED
diff --git a/vendor/github.com/prometheus/client_model/metrics.proto b/vendor/github.com/prometheus/client_model/metrics.proto
new file mode 100644
index 0000000..0b84af9
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/metrics.proto
@@ -0,0 +1,81 @@
+// Copyright 2013 Prometheus Team
+// 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.
+
+syntax = "proto2";
+
+package io.prometheus.client;
+option java_package = "io.prometheus.client";
+
+message LabelPair {
+ optional string name = 1;
+ optional string value = 2;
+}
+
+enum MetricType {
+ COUNTER = 0;
+ GAUGE = 1;
+ SUMMARY = 2;
+ UNTYPED = 3;
+ HISTOGRAM = 4;
+}
+
+message Gauge {
+ optional double value = 1;
+}
+
+message Counter {
+ optional double value = 1;
+}
+
+message Quantile {
+ optional double quantile = 1;
+ optional double value = 2;
+}
+
+message Summary {
+ optional uint64 sample_count = 1;
+ optional double sample_sum = 2;
+ repeated Quantile quantile = 3;
+}
+
+message Untyped {
+ optional double value = 1;
+}
+
+message Histogram {
+ optional uint64 sample_count = 1;
+ optional double sample_sum = 2;
+ repeated Bucket bucket = 3; // Ordered in increasing order of upper_bound, +Inf bucket is optional.
+}
+
+message Bucket {
+ optional uint64 cumulative_count = 1; // Cumulative in increasing order.
+ optional double upper_bound = 2; // Inclusive.
+}
+
+message Metric {
+ repeated LabelPair label = 1;
+ optional Gauge gauge = 2;
+ optional Counter counter = 3;
+ optional Summary summary = 4;
+ optional Untyped untyped = 5;
+ optional Histogram histogram = 7;
+ optional int64 timestamp_ms = 6;
+}
+
+message MetricFamily {
+ optional string name = 1;
+ optional string help = 2;
+ optional MetricType type = 3;
+ repeated Metric metric = 4;
+}
diff --git a/vendor/github.com/prometheus/client_model/pom.xml b/vendor/github.com/prometheus/client_model/pom.xml
new file mode 100644
index 0000000..4d34c90
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/pom.xml
@@ -0,0 +1,130 @@
+
+
+ 4.0.0
+
+ io.prometheus.client
+ model
+ 0.0.3-SNAPSHOT
+
+
+ org.sonatype.oss
+ oss-parent
+ 7
+
+
+ Prometheus Client Data Model
+ http://github.com/prometheus/client_model
+
+ Prometheus Client Data Model: Generated Protocol Buffer Assets
+
+
+
+
+ The Apache Software License, Version 2.0
+ http://www.apache.org/licenses/LICENSE-2.0.txt
+ repo
+
+
+
+
+ scm:git:git@github.com:prometheus/client_model.git
+ scm:git:git@github.com:prometheus/client_model.git
+ git@github.com:prometheus/client_model.git
+
+
+
+
+ mtp
+ Matt T. Proud
+ matt.proud@gmail.com
+
+
+
+
+
+ com.google.protobuf
+ protobuf-java
+ 2.5.0
+
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-javadoc-plugin
+ 2.8
+
+ UTF-8
+ UTF-8
+ true
+
+
+
+ generate-javadoc-site-report
+ site
+
+ javadoc
+
+
+
+ attach-javadocs
+
+ jar
+
+
+
+
+
+ maven-compiler-plugin
+
+
+ 1.6
+
+ 3.1
+
+
+ org.apache.maven.plugins
+ maven-source-plugin
+ 2.2.1
+
+
+ attach-sources
+
+ jar
+
+
+
+
+
+
+
+
+ release-sign-artifacts
+
+
+ performRelease
+ true
+
+
+
+
+
+ org.apache.maven.plugins
+ maven-gpg-plugin
+ 1.4
+
+
+ sign-artifacts
+ verify
+
+ sign
+
+
+
+
+
+
+
+
+
diff --git a/vendor/github.com/prometheus/client_model/python/prometheus/__init__.py b/vendor/github.com/prometheus/client_model/python/prometheus/__init__.py
new file mode 100644
index 0000000..617c0ce
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/python/prometheus/__init__.py
@@ -0,0 +1,12 @@
+ # Copyright 2013 Prometheus Team
+ # 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/prometheus/client_model/python/prometheus/client/__init__.py b/vendor/github.com/prometheus/client_model/python/prometheus/client/__init__.py
new file mode 100644
index 0000000..617c0ce
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/python/prometheus/client/__init__.py
@@ -0,0 +1,12 @@
+ # Copyright 2013 Prometheus Team
+ # 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/prometheus/client_model/python/prometheus/client/model/__init__.py b/vendor/github.com/prometheus/client_model/python/prometheus/client/model/__init__.py
new file mode 100644
index 0000000..d40327c
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/python/prometheus/client/model/__init__.py
@@ -0,0 +1,14 @@
+ # Copyright 2013 Prometheus Team
+ # 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.
+
+__all__ = ['metrics_pb2']
diff --git a/vendor/github.com/prometheus/client_model/python/prometheus/client/model/metrics_pb2.py b/vendor/github.com/prometheus/client_model/python/prometheus/client/model/metrics_pb2.py
new file mode 100644
index 0000000..8c239ac
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/python/prometheus/client/model/metrics_pb2.py
@@ -0,0 +1,575 @@
+# Generated by the protocol buffer compiler. DO NOT EDIT!
+# source: metrics.proto
+
+import sys
+_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
+from google.protobuf.internal import enum_type_wrapper
+from google.protobuf import descriptor as _descriptor
+from google.protobuf import message as _message
+from google.protobuf import reflection as _reflection
+from google.protobuf import symbol_database as _symbol_database
+from google.protobuf import descriptor_pb2
+# @@protoc_insertion_point(imports)
+
+_sym_db = _symbol_database.Default()
+
+
+
+
+DESCRIPTOR = _descriptor.FileDescriptor(
+ name='metrics.proto',
+ package='io.prometheus.client',
+ serialized_pb=_b('\n\rmetrics.proto\x12\x14io.prometheus.client\"(\n\tLabelPair\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t\"\x16\n\x05Gauge\x12\r\n\x05value\x18\x01 \x01(\x01\"\x18\n\x07\x43ounter\x12\r\n\x05value\x18\x01 \x01(\x01\"+\n\x08Quantile\x12\x10\n\x08quantile\x18\x01 \x01(\x01\x12\r\n\x05value\x18\x02 \x01(\x01\"e\n\x07Summary\x12\x14\n\x0csample_count\x18\x01 \x01(\x04\x12\x12\n\nsample_sum\x18\x02 \x01(\x01\x12\x30\n\x08quantile\x18\x03 \x03(\x0b\x32\x1e.io.prometheus.client.Quantile\"\x18\n\x07Untyped\x12\r\n\x05value\x18\x01 \x01(\x01\"c\n\tHistogram\x12\x14\n\x0csample_count\x18\x01 \x01(\x04\x12\x12\n\nsample_sum\x18\x02 \x01(\x01\x12,\n\x06\x62ucket\x18\x03 \x03(\x0b\x32\x1c.io.prometheus.client.Bucket\"7\n\x06\x42ucket\x12\x18\n\x10\x63umulative_count\x18\x01 \x01(\x04\x12\x13\n\x0bupper_bound\x18\x02 \x01(\x01\"\xbe\x02\n\x06Metric\x12.\n\x05label\x18\x01 \x03(\x0b\x32\x1f.io.prometheus.client.LabelPair\x12*\n\x05gauge\x18\x02 \x01(\x0b\x32\x1b.io.prometheus.client.Gauge\x12.\n\x07\x63ounter\x18\x03 \x01(\x0b\x32\x1d.io.prometheus.client.Counter\x12.\n\x07summary\x18\x04 \x01(\x0b\x32\x1d.io.prometheus.client.Summary\x12.\n\x07untyped\x18\x05 \x01(\x0b\x32\x1d.io.prometheus.client.Untyped\x12\x32\n\thistogram\x18\x07 \x01(\x0b\x32\x1f.io.prometheus.client.Histogram\x12\x14\n\x0ctimestamp_ms\x18\x06 \x01(\x03\"\x88\x01\n\x0cMetricFamily\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0c\n\x04help\x18\x02 \x01(\t\x12.\n\x04type\x18\x03 \x01(\x0e\x32 .io.prometheus.client.MetricType\x12,\n\x06metric\x18\x04 \x03(\x0b\x32\x1c.io.prometheus.client.Metric*M\n\nMetricType\x12\x0b\n\x07\x43OUNTER\x10\x00\x12\t\n\x05GAUGE\x10\x01\x12\x0b\n\x07SUMMARY\x10\x02\x12\x0b\n\x07UNTYPED\x10\x03\x12\r\n\tHISTOGRAM\x10\x04\x42\x16\n\x14io.prometheus.client')
+)
+_sym_db.RegisterFileDescriptor(DESCRIPTOR)
+
+_METRICTYPE = _descriptor.EnumDescriptor(
+ name='MetricType',
+ full_name='io.prometheus.client.MetricType',
+ filename=None,
+ file=DESCRIPTOR,
+ values=[
+ _descriptor.EnumValueDescriptor(
+ name='COUNTER', index=0, number=0,
+ options=None,
+ type=None),
+ _descriptor.EnumValueDescriptor(
+ name='GAUGE', index=1, number=1,
+ options=None,
+ type=None),
+ _descriptor.EnumValueDescriptor(
+ name='SUMMARY', index=2, number=2,
+ options=None,
+ type=None),
+ _descriptor.EnumValueDescriptor(
+ name='UNTYPED', index=3, number=3,
+ options=None,
+ type=None),
+ _descriptor.EnumValueDescriptor(
+ name='HISTOGRAM', index=4, number=4,
+ options=None,
+ type=None),
+ ],
+ containing_type=None,
+ options=None,
+ serialized_start=923,
+ serialized_end=1000,
+)
+_sym_db.RegisterEnumDescriptor(_METRICTYPE)
+
+MetricType = enum_type_wrapper.EnumTypeWrapper(_METRICTYPE)
+COUNTER = 0
+GAUGE = 1
+SUMMARY = 2
+UNTYPED = 3
+HISTOGRAM = 4
+
+
+
+_LABELPAIR = _descriptor.Descriptor(
+ name='LabelPair',
+ full_name='io.prometheus.client.LabelPair',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='name', full_name='io.prometheus.client.LabelPair.name', index=0,
+ number=1, type=9, cpp_type=9, label=1,
+ has_default_value=False, default_value=_b("").decode('utf-8'),
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='value', full_name='io.prometheus.client.LabelPair.value', index=1,
+ number=2, type=9, cpp_type=9, label=1,
+ has_default_value=False, default_value=_b("").decode('utf-8'),
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=39,
+ serialized_end=79,
+)
+
+
+_GAUGE = _descriptor.Descriptor(
+ name='Gauge',
+ full_name='io.prometheus.client.Gauge',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='value', full_name='io.prometheus.client.Gauge.value', index=0,
+ number=1, type=1, cpp_type=5, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=81,
+ serialized_end=103,
+)
+
+
+_COUNTER = _descriptor.Descriptor(
+ name='Counter',
+ full_name='io.prometheus.client.Counter',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='value', full_name='io.prometheus.client.Counter.value', index=0,
+ number=1, type=1, cpp_type=5, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=105,
+ serialized_end=129,
+)
+
+
+_QUANTILE = _descriptor.Descriptor(
+ name='Quantile',
+ full_name='io.prometheus.client.Quantile',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='quantile', full_name='io.prometheus.client.Quantile.quantile', index=0,
+ number=1, type=1, cpp_type=5, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='value', full_name='io.prometheus.client.Quantile.value', index=1,
+ number=2, type=1, cpp_type=5, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=131,
+ serialized_end=174,
+)
+
+
+_SUMMARY = _descriptor.Descriptor(
+ name='Summary',
+ full_name='io.prometheus.client.Summary',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='sample_count', full_name='io.prometheus.client.Summary.sample_count', index=0,
+ number=1, type=4, cpp_type=4, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='sample_sum', full_name='io.prometheus.client.Summary.sample_sum', index=1,
+ number=2, type=1, cpp_type=5, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='quantile', full_name='io.prometheus.client.Summary.quantile', index=2,
+ number=3, type=11, cpp_type=10, label=3,
+ has_default_value=False, default_value=[],
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=176,
+ serialized_end=277,
+)
+
+
+_UNTYPED = _descriptor.Descriptor(
+ name='Untyped',
+ full_name='io.prometheus.client.Untyped',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='value', full_name='io.prometheus.client.Untyped.value', index=0,
+ number=1, type=1, cpp_type=5, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=279,
+ serialized_end=303,
+)
+
+
+_HISTOGRAM = _descriptor.Descriptor(
+ name='Histogram',
+ full_name='io.prometheus.client.Histogram',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='sample_count', full_name='io.prometheus.client.Histogram.sample_count', index=0,
+ number=1, type=4, cpp_type=4, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='sample_sum', full_name='io.prometheus.client.Histogram.sample_sum', index=1,
+ number=2, type=1, cpp_type=5, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='bucket', full_name='io.prometheus.client.Histogram.bucket', index=2,
+ number=3, type=11, cpp_type=10, label=3,
+ has_default_value=False, default_value=[],
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=305,
+ serialized_end=404,
+)
+
+
+_BUCKET = _descriptor.Descriptor(
+ name='Bucket',
+ full_name='io.prometheus.client.Bucket',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='cumulative_count', full_name='io.prometheus.client.Bucket.cumulative_count', index=0,
+ number=1, type=4, cpp_type=4, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='upper_bound', full_name='io.prometheus.client.Bucket.upper_bound', index=1,
+ number=2, type=1, cpp_type=5, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=406,
+ serialized_end=461,
+)
+
+
+_METRIC = _descriptor.Descriptor(
+ name='Metric',
+ full_name='io.prometheus.client.Metric',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='label', full_name='io.prometheus.client.Metric.label', index=0,
+ number=1, type=11, cpp_type=10, label=3,
+ has_default_value=False, default_value=[],
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='gauge', full_name='io.prometheus.client.Metric.gauge', index=1,
+ number=2, type=11, cpp_type=10, label=1,
+ has_default_value=False, default_value=None,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='counter', full_name='io.prometheus.client.Metric.counter', index=2,
+ number=3, type=11, cpp_type=10, label=1,
+ has_default_value=False, default_value=None,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='summary', full_name='io.prometheus.client.Metric.summary', index=3,
+ number=4, type=11, cpp_type=10, label=1,
+ has_default_value=False, default_value=None,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='untyped', full_name='io.prometheus.client.Metric.untyped', index=4,
+ number=5, type=11, cpp_type=10, label=1,
+ has_default_value=False, default_value=None,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='histogram', full_name='io.prometheus.client.Metric.histogram', index=5,
+ number=7, type=11, cpp_type=10, label=1,
+ has_default_value=False, default_value=None,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='timestamp_ms', full_name='io.prometheus.client.Metric.timestamp_ms', index=6,
+ number=6, type=3, cpp_type=2, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=464,
+ serialized_end=782,
+)
+
+
+_METRICFAMILY = _descriptor.Descriptor(
+ name='MetricFamily',
+ full_name='io.prometheus.client.MetricFamily',
+ filename=None,
+ file=DESCRIPTOR,
+ containing_type=None,
+ fields=[
+ _descriptor.FieldDescriptor(
+ name='name', full_name='io.prometheus.client.MetricFamily.name', index=0,
+ number=1, type=9, cpp_type=9, label=1,
+ has_default_value=False, default_value=_b("").decode('utf-8'),
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='help', full_name='io.prometheus.client.MetricFamily.help', index=1,
+ number=2, type=9, cpp_type=9, label=1,
+ has_default_value=False, default_value=_b("").decode('utf-8'),
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='type', full_name='io.prometheus.client.MetricFamily.type', index=2,
+ number=3, type=14, cpp_type=8, label=1,
+ has_default_value=False, default_value=0,
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ _descriptor.FieldDescriptor(
+ name='metric', full_name='io.prometheus.client.MetricFamily.metric', index=3,
+ number=4, type=11, cpp_type=10, label=3,
+ has_default_value=False, default_value=[],
+ message_type=None, enum_type=None, containing_type=None,
+ is_extension=False, extension_scope=None,
+ options=None),
+ ],
+ extensions=[
+ ],
+ nested_types=[],
+ enum_types=[
+ ],
+ options=None,
+ is_extendable=False,
+ extension_ranges=[],
+ oneofs=[
+ ],
+ serialized_start=785,
+ serialized_end=921,
+)
+
+_SUMMARY.fields_by_name['quantile'].message_type = _QUANTILE
+_HISTOGRAM.fields_by_name['bucket'].message_type = _BUCKET
+_METRIC.fields_by_name['label'].message_type = _LABELPAIR
+_METRIC.fields_by_name['gauge'].message_type = _GAUGE
+_METRIC.fields_by_name['counter'].message_type = _COUNTER
+_METRIC.fields_by_name['summary'].message_type = _SUMMARY
+_METRIC.fields_by_name['untyped'].message_type = _UNTYPED
+_METRIC.fields_by_name['histogram'].message_type = _HISTOGRAM
+_METRICFAMILY.fields_by_name['type'].enum_type = _METRICTYPE
+_METRICFAMILY.fields_by_name['metric'].message_type = _METRIC
+DESCRIPTOR.message_types_by_name['LabelPair'] = _LABELPAIR
+DESCRIPTOR.message_types_by_name['Gauge'] = _GAUGE
+DESCRIPTOR.message_types_by_name['Counter'] = _COUNTER
+DESCRIPTOR.message_types_by_name['Quantile'] = _QUANTILE
+DESCRIPTOR.message_types_by_name['Summary'] = _SUMMARY
+DESCRIPTOR.message_types_by_name['Untyped'] = _UNTYPED
+DESCRIPTOR.message_types_by_name['Histogram'] = _HISTOGRAM
+DESCRIPTOR.message_types_by_name['Bucket'] = _BUCKET
+DESCRIPTOR.message_types_by_name['Metric'] = _METRIC
+DESCRIPTOR.message_types_by_name['MetricFamily'] = _METRICFAMILY
+DESCRIPTOR.enum_types_by_name['MetricType'] = _METRICTYPE
+
+LabelPair = _reflection.GeneratedProtocolMessageType('LabelPair', (_message.Message,), dict(
+ DESCRIPTOR = _LABELPAIR,
+ __module__ = 'metrics_pb2'
+ # @@protoc_insertion_point(class_scope:io.prometheus.client.LabelPair)
+ ))
+_sym_db.RegisterMessage(LabelPair)
+
+Gauge = _reflection.GeneratedProtocolMessageType('Gauge', (_message.Message,), dict(
+ DESCRIPTOR = _GAUGE,
+ __module__ = 'metrics_pb2'
+ # @@protoc_insertion_point(class_scope:io.prometheus.client.Gauge)
+ ))
+_sym_db.RegisterMessage(Gauge)
+
+Counter = _reflection.GeneratedProtocolMessageType('Counter', (_message.Message,), dict(
+ DESCRIPTOR = _COUNTER,
+ __module__ = 'metrics_pb2'
+ # @@protoc_insertion_point(class_scope:io.prometheus.client.Counter)
+ ))
+_sym_db.RegisterMessage(Counter)
+
+Quantile = _reflection.GeneratedProtocolMessageType('Quantile', (_message.Message,), dict(
+ DESCRIPTOR = _QUANTILE,
+ __module__ = 'metrics_pb2'
+ # @@protoc_insertion_point(class_scope:io.prometheus.client.Quantile)
+ ))
+_sym_db.RegisterMessage(Quantile)
+
+Summary = _reflection.GeneratedProtocolMessageType('Summary', (_message.Message,), dict(
+ DESCRIPTOR = _SUMMARY,
+ __module__ = 'metrics_pb2'
+ # @@protoc_insertion_point(class_scope:io.prometheus.client.Summary)
+ ))
+_sym_db.RegisterMessage(Summary)
+
+Untyped = _reflection.GeneratedProtocolMessageType('Untyped', (_message.Message,), dict(
+ DESCRIPTOR = _UNTYPED,
+ __module__ = 'metrics_pb2'
+ # @@protoc_insertion_point(class_scope:io.prometheus.client.Untyped)
+ ))
+_sym_db.RegisterMessage(Untyped)
+
+Histogram = _reflection.GeneratedProtocolMessageType('Histogram', (_message.Message,), dict(
+ DESCRIPTOR = _HISTOGRAM,
+ __module__ = 'metrics_pb2'
+ # @@protoc_insertion_point(class_scope:io.prometheus.client.Histogram)
+ ))
+_sym_db.RegisterMessage(Histogram)
+
+Bucket = _reflection.GeneratedProtocolMessageType('Bucket', (_message.Message,), dict(
+ DESCRIPTOR = _BUCKET,
+ __module__ = 'metrics_pb2'
+ # @@protoc_insertion_point(class_scope:io.prometheus.client.Bucket)
+ ))
+_sym_db.RegisterMessage(Bucket)
+
+Metric = _reflection.GeneratedProtocolMessageType('Metric', (_message.Message,), dict(
+ DESCRIPTOR = _METRIC,
+ __module__ = 'metrics_pb2'
+ # @@protoc_insertion_point(class_scope:io.prometheus.client.Metric)
+ ))
+_sym_db.RegisterMessage(Metric)
+
+MetricFamily = _reflection.GeneratedProtocolMessageType('MetricFamily', (_message.Message,), dict(
+ DESCRIPTOR = _METRICFAMILY,
+ __module__ = 'metrics_pb2'
+ # @@protoc_insertion_point(class_scope:io.prometheus.client.MetricFamily)
+ ))
+_sym_db.RegisterMessage(MetricFamily)
+
+
+DESCRIPTOR.has_options = True
+DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\024io.prometheus.client'))
+# @@protoc_insertion_point(module_scope)
diff --git a/vendor/github.com/prometheus/client_model/ruby/.gitignore b/vendor/github.com/prometheus/client_model/ruby/.gitignore
new file mode 100644
index 0000000..8442a47
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/ruby/.gitignore
@@ -0,0 +1,5 @@
+*.gem
+.bundle
+Gemfile.lock
+pkg
+vendor/bundle
diff --git a/vendor/github.com/prometheus/client_model/ruby/Gemfile b/vendor/github.com/prometheus/client_model/ruby/Gemfile
new file mode 100644
index 0000000..1ff638c
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/ruby/Gemfile
@@ -0,0 +1,4 @@
+source 'https://rubygems.org'
+
+# Specify your gem's dependencies in prometheus-client-model.gemspec
+gemspec
diff --git a/vendor/github.com/prometheus/client_model/ruby/LICENSE b/vendor/github.com/prometheus/client_model/ruby/LICENSE
new file mode 100644
index 0000000..11069ed
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/ruby/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+END OF TERMS AND CONDITIONS
+
+APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+Copyright [yyyy] [name of copyright owner]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/vendor/github.com/prometheus/client_model/ruby/Makefile b/vendor/github.com/prometheus/client_model/ruby/Makefile
new file mode 100644
index 0000000..09d544b
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/ruby/Makefile
@@ -0,0 +1,17 @@
+VENDOR_BUNDLE = vendor/bundle
+
+build: $(VENDOR_BUNDLE)/.bundled
+ BEEFCAKE_NAMESPACE=Prometheus::Client protoc --beefcake_out lib/prometheus/client/model -I .. ../metrics.proto
+
+$(VENDOR_BUNDLE):
+ mkdir -p $@
+
+$(VENDOR_BUNDLE)/.bundled: $(VENDOR_BUNDLE) Gemfile
+ bundle install --quiet --path $<
+ @touch $@
+
+clean:
+ -rm -f lib/prometheus/client/model/metrics.pb.rb
+ -rm -rf $(VENDOR_BUNDLE)
+
+.PHONY: build clean
diff --git a/vendor/github.com/prometheus/client_model/ruby/README.md b/vendor/github.com/prometheus/client_model/ruby/README.md
new file mode 100644
index 0000000..c45fcc7
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/ruby/README.md
@@ -0,0 +1,31 @@
+# Prometheus Ruby client model
+
+Data model artifacts for the [Prometheus Ruby client][1].
+
+## Installation
+
+ gem install prometheus-client-model
+
+## Usage
+
+Build the artifacts from the protobuf specification:
+
+ make build
+
+While this Gem's main purpose is to define the Prometheus data types for the
+[client][1], it's possible to use it without the client to decode a stream of
+delimited protobuf messages:
+
+```ruby
+require 'open-uri'
+require 'prometheus/client/model'
+
+CONTENT_TYPE = 'application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited'
+
+stream = open('http://localhost:9090/metrics', 'Accept' => CONTENT_TYPE).read
+while family = Prometheus::Client::MetricFamily.read_delimited(stream)
+ puts family
+end
+```
+
+[1]: https://github.com/prometheus/client_ruby
diff --git a/vendor/github.com/prometheus/client_model/ruby/Rakefile b/vendor/github.com/prometheus/client_model/ruby/Rakefile
new file mode 100644
index 0000000..2995527
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/ruby/Rakefile
@@ -0,0 +1 @@
+require "bundler/gem_tasks"
diff --git a/vendor/github.com/prometheus/client_model/ruby/lib/prometheus/client/model.rb b/vendor/github.com/prometheus/client_model/ruby/lib/prometheus/client/model.rb
new file mode 100644
index 0000000..b5303bf
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/ruby/lib/prometheus/client/model.rb
@@ -0,0 +1,2 @@
+require 'prometheus/client/model/metrics.pb'
+require 'prometheus/client/model/version'
diff --git a/vendor/github.com/prometheus/client_model/ruby/lib/prometheus/client/model/metrics.pb.rb b/vendor/github.com/prometheus/client_model/ruby/lib/prometheus/client/model/metrics.pb.rb
new file mode 100644
index 0000000..a72114b
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/ruby/lib/prometheus/client/model/metrics.pb.rb
@@ -0,0 +1,111 @@
+## Generated from metrics.proto for io.prometheus.client
+require "beefcake"
+
+module Prometheus
+ module Client
+
+ module MetricType
+ COUNTER = 0
+ GAUGE = 1
+ SUMMARY = 2
+ UNTYPED = 3
+ HISTOGRAM = 4
+ end
+
+ class LabelPair
+ include Beefcake::Message
+ end
+
+ class Gauge
+ include Beefcake::Message
+ end
+
+ class Counter
+ include Beefcake::Message
+ end
+
+ class Quantile
+ include Beefcake::Message
+ end
+
+ class Summary
+ include Beefcake::Message
+ end
+
+ class Untyped
+ include Beefcake::Message
+ end
+
+ class Histogram
+ include Beefcake::Message
+ end
+
+ class Bucket
+ include Beefcake::Message
+ end
+
+ class Metric
+ include Beefcake::Message
+ end
+
+ class MetricFamily
+ include Beefcake::Message
+ end
+
+ class LabelPair
+ optional :name, :string, 1
+ optional :value, :string, 2
+ end
+
+ class Gauge
+ optional :value, :double, 1
+ end
+
+ class Counter
+ optional :value, :double, 1
+ end
+
+ class Quantile
+ optional :quantile, :double, 1
+ optional :value, :double, 2
+ end
+
+ class Summary
+ optional :sample_count, :uint64, 1
+ optional :sample_sum, :double, 2
+ repeated :quantile, Quantile, 3
+ end
+
+ class Untyped
+ optional :value, :double, 1
+ end
+
+ class Histogram
+ optional :sample_count, :uint64, 1
+ optional :sample_sum, :double, 2
+ repeated :bucket, Bucket, 3
+ end
+
+ class Bucket
+ optional :cumulative_count, :uint64, 1
+ optional :upper_bound, :double, 2
+ end
+
+ class Metric
+ repeated :label, LabelPair, 1
+ optional :gauge, Gauge, 2
+ optional :counter, Counter, 3
+ optional :summary, Summary, 4
+ optional :untyped, Untyped, 5
+ optional :histogram, Histogram, 7
+ optional :timestamp_ms, :int64, 6
+ end
+
+ class MetricFamily
+ optional :name, :string, 1
+ optional :help, :string, 2
+ optional :type, MetricType, 3
+ repeated :metric, Metric, 4
+ end
+ end
+end
diff --git a/vendor/github.com/prometheus/client_model/ruby/lib/prometheus/client/model/version.rb b/vendor/github.com/prometheus/client_model/ruby/lib/prometheus/client/model/version.rb
new file mode 100644
index 0000000..00b5e86
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/ruby/lib/prometheus/client/model/version.rb
@@ -0,0 +1,7 @@
+module Prometheus
+ module Client
+ module Model
+ VERSION = '0.1.0'
+ end
+ end
+end
diff --git a/vendor/github.com/prometheus/client_model/ruby/prometheus-client-model.gemspec b/vendor/github.com/prometheus/client_model/ruby/prometheus-client-model.gemspec
new file mode 100644
index 0000000..438ba12
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/ruby/prometheus-client-model.gemspec
@@ -0,0 +1,22 @@
+# coding: utf-8
+lib = File.expand_path('../lib', __FILE__)
+$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
+require 'prometheus/client/model/version'
+
+Gem::Specification.new do |spec|
+ spec.name = 'prometheus-client-model'
+ spec.version = Prometheus::Client::Model::VERSION
+ spec.authors = ['Tobias Schmidt']
+ spec.email = ['tobidt@gmail.com']
+ spec.summary = 'Data model artifacts for the Prometheus Ruby client'
+ spec.homepage = 'https://github.com/prometheus/client_model/tree/master/ruby'
+ spec.license = 'Apache 2.0'
+
+ spec.files = %w[README.md LICENSE] + Dir.glob('{lib/**/*}')
+ spec.require_paths = ['lib']
+
+ spec.add_dependency 'beefcake', '>= 0.4.0'
+
+ spec.add_development_dependency 'bundler', '~> 1.3'
+ spec.add_development_dependency 'rake'
+end
diff --git a/vendor/github.com/prometheus/client_model/setup.py b/vendor/github.com/prometheus/client_model/setup.py
new file mode 100644
index 0000000..67b9f20
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/setup.py
@@ -0,0 +1,23 @@
+#!/usr/bin/python
+
+from setuptools import setup
+
+setup(
+ name = 'prometheus_client_model',
+ version = '0.0.1',
+ author = 'Matt T. Proud',
+ author_email = 'matt.proud@gmail.com',
+ description = 'Data model artifacts for the Prometheus client.',
+ license = 'Apache License 2.0',
+ url = 'http://github.com/prometheus/client_model',
+ packages = ['prometheus', 'prometheus/client', 'prometheus/client/model'],
+ package_dir = {'': 'python'},
+ requires = ['protobuf(==2.4.1)'],
+ platforms = 'Platform Independent',
+ classifiers = ['Development Status :: 3 - Alpha',
+ 'Intended Audience :: Developers',
+ 'Intended Audience :: System Administrators',
+ 'License :: OSI Approved :: Apache Software License',
+ 'Operating System :: OS Independent',
+ 'Topic :: Software Development :: Testing',
+ 'Topic :: System :: Monitoring'])
diff --git a/vendor/github.com/prometheus/client_model/src/main/java/io/prometheus/client/Metrics.java b/vendor/github.com/prometheus/client_model/src/main/java/io/prometheus/client/Metrics.java
new file mode 100644
index 0000000..fb6218e
--- /dev/null
+++ b/vendor/github.com/prometheus/client_model/src/main/java/io/prometheus/client/Metrics.java
@@ -0,0 +1,7683 @@
+// Generated by the protocol buffer compiler. DO NOT EDIT!
+// source: metrics.proto
+
+package io.prometheus.client;
+
+public final class Metrics {
+ private Metrics() {}
+ public static void registerAllExtensions(
+ com.google.protobuf.ExtensionRegistry registry) {
+ }
+ /**
+ * Protobuf enum {@code io.prometheus.client.MetricType}
+ */
+ public enum MetricType
+ implements com.google.protobuf.ProtocolMessageEnum {
+ /**
+ * COUNTER = 0;
+ */
+ COUNTER(0, 0),
+ /**
+ * GAUGE = 1;
+ */
+ GAUGE(1, 1),
+ /**
+ * SUMMARY = 2;
+ */
+ SUMMARY(2, 2),
+ /**
+ * UNTYPED = 3;
+ */
+ UNTYPED(3, 3),
+ /**
+ * HISTOGRAM = 4;
+ */
+ HISTOGRAM(4, 4),
+ ;
+
+ /**
+ * COUNTER = 0;
+ */
+ public static final int COUNTER_VALUE = 0;
+ /**
+ * GAUGE = 1;
+ */
+ public static final int GAUGE_VALUE = 1;
+ /**
+ * SUMMARY = 2;
+ */
+ public static final int SUMMARY_VALUE = 2;
+ /**
+ * UNTYPED = 3;
+ */
+ public static final int UNTYPED_VALUE = 3;
+ /**
+ * HISTOGRAM = 4;
+ */
+ public static final int HISTOGRAM_VALUE = 4;
+
+
+ public final int getNumber() { return value; }
+
+ public static MetricType valueOf(int value) {
+ switch (value) {
+ case 0: return COUNTER;
+ case 1: return GAUGE;
+ case 2: return SUMMARY;
+ case 3: return UNTYPED;
+ case 4: return HISTOGRAM;
+ default: return null;
+ }
+ }
+
+ public static com.google.protobuf.Internal.EnumLiteMap
+ internalGetValueMap() {
+ return internalValueMap;
+ }
+ private static com.google.protobuf.Internal.EnumLiteMap
+ internalValueMap =
+ new com.google.protobuf.Internal.EnumLiteMap() {
+ public MetricType findValueByNumber(int number) {
+ return MetricType.valueOf(number);
+ }
+ };
+
+ public final com.google.protobuf.Descriptors.EnumValueDescriptor
+ getValueDescriptor() {
+ return getDescriptor().getValues().get(index);
+ }
+ public final com.google.protobuf.Descriptors.EnumDescriptor
+ getDescriptorForType() {
+ return getDescriptor();
+ }
+ public static final com.google.protobuf.Descriptors.EnumDescriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.getDescriptor().getEnumTypes().get(0);
+ }
+
+ private static final MetricType[] VALUES = values();
+
+ public static MetricType valueOf(
+ com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
+ if (desc.getType() != getDescriptor()) {
+ throw new java.lang.IllegalArgumentException(
+ "EnumValueDescriptor is not for this type.");
+ }
+ return VALUES[desc.getIndex()];
+ }
+
+ private final int index;
+ private final int value;
+
+ private MetricType(int index, int value) {
+ this.index = index;
+ this.value = value;
+ }
+
+ // @@protoc_insertion_point(enum_scope:io.prometheus.client.MetricType)
+ }
+
+ public interface LabelPairOrBuilder extends
+ // @@protoc_insertion_point(interface_extends:io.prometheus.client.LabelPair)
+ com.google.protobuf.MessageOrBuilder {
+
+ /**
+ * optional string name = 1;
+ */
+ boolean hasName();
+ /**
+ * optional string name = 1;
+ */
+ java.lang.String getName();
+ /**
+ * optional string name = 1;
+ */
+ com.google.protobuf.ByteString
+ getNameBytes();
+
+ /**
+ * optional string value = 2;
+ */
+ boolean hasValue();
+ /**
+ * optional string value = 2;
+ */
+ java.lang.String getValue();
+ /**
+ * optional string value = 2;
+ */
+ com.google.protobuf.ByteString
+ getValueBytes();
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.LabelPair}
+ */
+ public static final class LabelPair extends
+ com.google.protobuf.GeneratedMessage implements
+ // @@protoc_insertion_point(message_implements:io.prometheus.client.LabelPair)
+ LabelPairOrBuilder {
+ // Use LabelPair.newBuilder() to construct.
+ private LabelPair(com.google.protobuf.GeneratedMessage.Builder> builder) {
+ super(builder);
+ this.unknownFields = builder.getUnknownFields();
+ }
+ private LabelPair(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+ private static final LabelPair defaultInstance;
+ public static LabelPair getDefaultInstance() {
+ return defaultInstance;
+ }
+
+ public LabelPair getDefaultInstanceForType() {
+ return defaultInstance;
+ }
+
+ private final com.google.protobuf.UnknownFieldSet unknownFields;
+ @java.lang.Override
+ public final com.google.protobuf.UnknownFieldSet
+ getUnknownFields() {
+ return this.unknownFields;
+ }
+ private LabelPair(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ initFields();
+ int mutable_bitField0_ = 0;
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder();
+ try {
+ boolean done = false;
+ while (!done) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ done = true;
+ break;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ done = true;
+ }
+ break;
+ }
+ case 10: {
+ com.google.protobuf.ByteString bs = input.readBytes();
+ bitField0_ |= 0x00000001;
+ name_ = bs;
+ break;
+ }
+ case 18: {
+ com.google.protobuf.ByteString bs = input.readBytes();
+ bitField0_ |= 0x00000002;
+ value_ = bs;
+ break;
+ }
+ }
+ }
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(this);
+ } catch (java.io.IOException e) {
+ throw new com.google.protobuf.InvalidProtocolBufferException(
+ e.getMessage()).setUnfinishedMessage(this);
+ } finally {
+ this.unknownFields = unknownFields.build();
+ makeExtensionsImmutable();
+ }
+ }
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_LabelPair_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_LabelPair_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.LabelPair.class, io.prometheus.client.Metrics.LabelPair.Builder.class);
+ }
+
+ public static com.google.protobuf.Parser PARSER =
+ new com.google.protobuf.AbstractParser() {
+ public LabelPair parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new LabelPair(input, extensionRegistry);
+ }
+ };
+
+ @java.lang.Override
+ public com.google.protobuf.Parser getParserForType() {
+ return PARSER;
+ }
+
+ private int bitField0_;
+ public static final int NAME_FIELD_NUMBER = 1;
+ private java.lang.Object name_;
+ /**
+ * optional string name = 1;
+ */
+ public boolean hasName() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional string name = 1;
+ */
+ public java.lang.String getName() {
+ java.lang.Object ref = name_;
+ if (ref instanceof java.lang.String) {
+ return (java.lang.String) ref;
+ } else {
+ com.google.protobuf.ByteString bs =
+ (com.google.protobuf.ByteString) ref;
+ java.lang.String s = bs.toStringUtf8();
+ if (bs.isValidUtf8()) {
+ name_ = s;
+ }
+ return s;
+ }
+ }
+ /**
+ * optional string name = 1;
+ */
+ public com.google.protobuf.ByteString
+ getNameBytes() {
+ java.lang.Object ref = name_;
+ if (ref instanceof java.lang.String) {
+ com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString.copyFromUtf8(
+ (java.lang.String) ref);
+ name_ = b;
+ return b;
+ } else {
+ return (com.google.protobuf.ByteString) ref;
+ }
+ }
+
+ public static final int VALUE_FIELD_NUMBER = 2;
+ private java.lang.Object value_;
+ /**
+ * optional string value = 2;
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional string value = 2;
+ */
+ public java.lang.String getValue() {
+ java.lang.Object ref = value_;
+ if (ref instanceof java.lang.String) {
+ return (java.lang.String) ref;
+ } else {
+ com.google.protobuf.ByteString bs =
+ (com.google.protobuf.ByteString) ref;
+ java.lang.String s = bs.toStringUtf8();
+ if (bs.isValidUtf8()) {
+ value_ = s;
+ }
+ return s;
+ }
+ }
+ /**
+ * optional string value = 2;
+ */
+ public com.google.protobuf.ByteString
+ getValueBytes() {
+ java.lang.Object ref = value_;
+ if (ref instanceof java.lang.String) {
+ com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString.copyFromUtf8(
+ (java.lang.String) ref);
+ value_ = b;
+ return b;
+ } else {
+ return (com.google.protobuf.ByteString) ref;
+ }
+ }
+
+ private void initFields() {
+ name_ = "";
+ value_ = "";
+ }
+ private byte memoizedIsInitialized = -1;
+ public final boolean isInitialized() {
+ byte isInitialized = memoizedIsInitialized;
+ if (isInitialized == 1) return true;
+ if (isInitialized == 0) return false;
+
+ memoizedIsInitialized = 1;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ output.writeBytes(1, getNameBytes());
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ output.writeBytes(2, getValueBytes());
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBytesSize(1, getNameBytes());
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBytesSize(2, getValueBytes());
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ private static final long serialVersionUID = 0L;
+ @java.lang.Override
+ protected java.lang.Object writeReplace()
+ throws java.io.ObjectStreamException {
+ return super.writeReplace();
+ }
+
+ public static io.prometheus.client.Metrics.LabelPair parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.LabelPair parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.LabelPair parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.LabelPair parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.LabelPair parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.LabelPair parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.LabelPair parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input);
+ }
+ public static io.prometheus.client.Metrics.LabelPair parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.LabelPair parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.LabelPair parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static Builder newBuilder() { return Builder.create(); }
+ public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder newBuilder(io.prometheus.client.Metrics.LabelPair prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() { return newBuilder(this); }
+
+ @java.lang.Override
+ protected Builder newBuilderForType(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ Builder builder = new Builder(parent);
+ return builder;
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.LabelPair}
+ */
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder implements
+ // @@protoc_insertion_point(builder_implements:io.prometheus.client.LabelPair)
+ io.prometheus.client.Metrics.LabelPairOrBuilder {
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_LabelPair_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_LabelPair_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.LabelPair.class, io.prometheus.client.Metrics.LabelPair.Builder.class);
+ }
+
+ // Construct using io.prometheus.client.Metrics.LabelPair.newBuilder()
+ private Builder() {
+ maybeForceBuilderInitialization();
+ }
+
+ private Builder(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ super(parent);
+ maybeForceBuilderInitialization();
+ }
+ private void maybeForceBuilderInitialization() {
+ if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ }
+ }
+ private static Builder create() {
+ return new Builder();
+ }
+
+ public Builder clear() {
+ super.clear();
+ name_ = "";
+ bitField0_ = (bitField0_ & ~0x00000001);
+ value_ = "";
+ bitField0_ = (bitField0_ & ~0x00000002);
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(buildPartial());
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_LabelPair_descriptor;
+ }
+
+ public io.prometheus.client.Metrics.LabelPair getDefaultInstanceForType() {
+ return io.prometheus.client.Metrics.LabelPair.getDefaultInstance();
+ }
+
+ public io.prometheus.client.Metrics.LabelPair build() {
+ io.prometheus.client.Metrics.LabelPair result = buildPartial();
+ if (!result.isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return result;
+ }
+
+ public io.prometheus.client.Metrics.LabelPair buildPartial() {
+ io.prometheus.client.Metrics.LabelPair result = new io.prometheus.client.Metrics.LabelPair(this);
+ int from_bitField0_ = bitField0_;
+ int to_bitField0_ = 0;
+ if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+ to_bitField0_ |= 0x00000001;
+ }
+ result.name_ = name_;
+ if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
+ to_bitField0_ |= 0x00000002;
+ }
+ result.value_ = value_;
+ result.bitField0_ = to_bitField0_;
+ onBuilt();
+ return result;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof io.prometheus.client.Metrics.LabelPair) {
+ return mergeFrom((io.prometheus.client.Metrics.LabelPair)other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(io.prometheus.client.Metrics.LabelPair other) {
+ if (other == io.prometheus.client.Metrics.LabelPair.getDefaultInstance()) return this;
+ if (other.hasName()) {
+ bitField0_ |= 0x00000001;
+ name_ = other.name_;
+ onChanged();
+ }
+ if (other.hasValue()) {
+ bitField0_ |= 0x00000002;
+ value_ = other.value_;
+ onChanged();
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public final boolean isInitialized() {
+ return true;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ io.prometheus.client.Metrics.LabelPair parsedMessage = null;
+ try {
+ parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ parsedMessage = (io.prometheus.client.Metrics.LabelPair) e.getUnfinishedMessage();
+ throw e;
+ } finally {
+ if (parsedMessage != null) {
+ mergeFrom(parsedMessage);
+ }
+ }
+ return this;
+ }
+ private int bitField0_;
+
+ private java.lang.Object name_ = "";
+ /**
+ * optional string name = 1;
+ */
+ public boolean hasName() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional string name = 1;
+ */
+ public java.lang.String getName() {
+ java.lang.Object ref = name_;
+ if (!(ref instanceof java.lang.String)) {
+ com.google.protobuf.ByteString bs =
+ (com.google.protobuf.ByteString) ref;
+ java.lang.String s = bs.toStringUtf8();
+ if (bs.isValidUtf8()) {
+ name_ = s;
+ }
+ return s;
+ } else {
+ return (java.lang.String) ref;
+ }
+ }
+ /**
+ * optional string name = 1;
+ */
+ public com.google.protobuf.ByteString
+ getNameBytes() {
+ java.lang.Object ref = name_;
+ if (ref instanceof String) {
+ com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString.copyFromUtf8(
+ (java.lang.String) ref);
+ name_ = b;
+ return b;
+ } else {
+ return (com.google.protobuf.ByteString) ref;
+ }
+ }
+ /**
+ * optional string name = 1;
+ */
+ public Builder setName(
+ java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000001;
+ name_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional string name = 1;
+ */
+ public Builder clearName() {
+ bitField0_ = (bitField0_ & ~0x00000001);
+ name_ = getDefaultInstance().getName();
+ onChanged();
+ return this;
+ }
+ /**
+ * optional string name = 1;
+ */
+ public Builder setNameBytes(
+ com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000001;
+ name_ = value;
+ onChanged();
+ return this;
+ }
+
+ private java.lang.Object value_ = "";
+ /**
+ * optional string value = 2;
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional string value = 2;
+ */
+ public java.lang.String getValue() {
+ java.lang.Object ref = value_;
+ if (!(ref instanceof java.lang.String)) {
+ com.google.protobuf.ByteString bs =
+ (com.google.protobuf.ByteString) ref;
+ java.lang.String s = bs.toStringUtf8();
+ if (bs.isValidUtf8()) {
+ value_ = s;
+ }
+ return s;
+ } else {
+ return (java.lang.String) ref;
+ }
+ }
+ /**
+ * optional string value = 2;
+ */
+ public com.google.protobuf.ByteString
+ getValueBytes() {
+ java.lang.Object ref = value_;
+ if (ref instanceof String) {
+ com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString.copyFromUtf8(
+ (java.lang.String) ref);
+ value_ = b;
+ return b;
+ } else {
+ return (com.google.protobuf.ByteString) ref;
+ }
+ }
+ /**
+ * optional string value = 2;
+ */
+ public Builder setValue(
+ java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000002;
+ value_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional string value = 2;
+ */
+ public Builder clearValue() {
+ bitField0_ = (bitField0_ & ~0x00000002);
+ value_ = getDefaultInstance().getValue();
+ onChanged();
+ return this;
+ }
+ /**
+ * optional string value = 2;
+ */
+ public Builder setValueBytes(
+ com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000002;
+ value_ = value;
+ onChanged();
+ return this;
+ }
+
+ // @@protoc_insertion_point(builder_scope:io.prometheus.client.LabelPair)
+ }
+
+ static {
+ defaultInstance = new LabelPair(true);
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.LabelPair)
+ }
+
+ public interface GaugeOrBuilder extends
+ // @@protoc_insertion_point(interface_extends:io.prometheus.client.Gauge)
+ com.google.protobuf.MessageOrBuilder {
+
+ /**
+ * optional double value = 1;
+ */
+ boolean hasValue();
+ /**
+ * optional double value = 1;
+ */
+ double getValue();
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Gauge}
+ */
+ public static final class Gauge extends
+ com.google.protobuf.GeneratedMessage implements
+ // @@protoc_insertion_point(message_implements:io.prometheus.client.Gauge)
+ GaugeOrBuilder {
+ // Use Gauge.newBuilder() to construct.
+ private Gauge(com.google.protobuf.GeneratedMessage.Builder> builder) {
+ super(builder);
+ this.unknownFields = builder.getUnknownFields();
+ }
+ private Gauge(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+ private static final Gauge defaultInstance;
+ public static Gauge getDefaultInstance() {
+ return defaultInstance;
+ }
+
+ public Gauge getDefaultInstanceForType() {
+ return defaultInstance;
+ }
+
+ private final com.google.protobuf.UnknownFieldSet unknownFields;
+ @java.lang.Override
+ public final com.google.protobuf.UnknownFieldSet
+ getUnknownFields() {
+ return this.unknownFields;
+ }
+ private Gauge(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ initFields();
+ int mutable_bitField0_ = 0;
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder();
+ try {
+ boolean done = false;
+ while (!done) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ done = true;
+ break;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ done = true;
+ }
+ break;
+ }
+ case 9: {
+ bitField0_ |= 0x00000001;
+ value_ = input.readDouble();
+ break;
+ }
+ }
+ }
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(this);
+ } catch (java.io.IOException e) {
+ throw new com.google.protobuf.InvalidProtocolBufferException(
+ e.getMessage()).setUnfinishedMessage(this);
+ } finally {
+ this.unknownFields = unknownFields.build();
+ makeExtensionsImmutable();
+ }
+ }
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Gauge_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Gauge_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Gauge.class, io.prometheus.client.Metrics.Gauge.Builder.class);
+ }
+
+ public static com.google.protobuf.Parser PARSER =
+ new com.google.protobuf.AbstractParser() {
+ public Gauge parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new Gauge(input, extensionRegistry);
+ }
+ };
+
+ @java.lang.Override
+ public com.google.protobuf.Parser getParserForType() {
+ return PARSER;
+ }
+
+ private int bitField0_;
+ public static final int VALUE_FIELD_NUMBER = 1;
+ private double value_;
+ /**
+ * optional double value = 1;
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional double value = 1;
+ */
+ public double getValue() {
+ return value_;
+ }
+
+ private void initFields() {
+ value_ = 0D;
+ }
+ private byte memoizedIsInitialized = -1;
+ public final boolean isInitialized() {
+ byte isInitialized = memoizedIsInitialized;
+ if (isInitialized == 1) return true;
+ if (isInitialized == 0) return false;
+
+ memoizedIsInitialized = 1;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ output.writeDouble(1, value_);
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeDoubleSize(1, value_);
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ private static final long serialVersionUID = 0L;
+ @java.lang.Override
+ protected java.lang.Object writeReplace()
+ throws java.io.ObjectStreamException {
+ return super.writeReplace();
+ }
+
+ public static io.prometheus.client.Metrics.Gauge parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Gauge parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Gauge parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Gauge parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Gauge parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Gauge parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Gauge parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Gauge parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Gauge parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Gauge parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static Builder newBuilder() { return Builder.create(); }
+ public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder newBuilder(io.prometheus.client.Metrics.Gauge prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() { return newBuilder(this); }
+
+ @java.lang.Override
+ protected Builder newBuilderForType(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ Builder builder = new Builder(parent);
+ return builder;
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Gauge}
+ */
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder implements
+ // @@protoc_insertion_point(builder_implements:io.prometheus.client.Gauge)
+ io.prometheus.client.Metrics.GaugeOrBuilder {
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Gauge_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Gauge_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Gauge.class, io.prometheus.client.Metrics.Gauge.Builder.class);
+ }
+
+ // Construct using io.prometheus.client.Metrics.Gauge.newBuilder()
+ private Builder() {
+ maybeForceBuilderInitialization();
+ }
+
+ private Builder(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ super(parent);
+ maybeForceBuilderInitialization();
+ }
+ private void maybeForceBuilderInitialization() {
+ if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ }
+ }
+ private static Builder create() {
+ return new Builder();
+ }
+
+ public Builder clear() {
+ super.clear();
+ value_ = 0D;
+ bitField0_ = (bitField0_ & ~0x00000001);
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(buildPartial());
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Gauge_descriptor;
+ }
+
+ public io.prometheus.client.Metrics.Gauge getDefaultInstanceForType() {
+ return io.prometheus.client.Metrics.Gauge.getDefaultInstance();
+ }
+
+ public io.prometheus.client.Metrics.Gauge build() {
+ io.prometheus.client.Metrics.Gauge result = buildPartial();
+ if (!result.isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return result;
+ }
+
+ public io.prometheus.client.Metrics.Gauge buildPartial() {
+ io.prometheus.client.Metrics.Gauge result = new io.prometheus.client.Metrics.Gauge(this);
+ int from_bitField0_ = bitField0_;
+ int to_bitField0_ = 0;
+ if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+ to_bitField0_ |= 0x00000001;
+ }
+ result.value_ = value_;
+ result.bitField0_ = to_bitField0_;
+ onBuilt();
+ return result;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof io.prometheus.client.Metrics.Gauge) {
+ return mergeFrom((io.prometheus.client.Metrics.Gauge)other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(io.prometheus.client.Metrics.Gauge other) {
+ if (other == io.prometheus.client.Metrics.Gauge.getDefaultInstance()) return this;
+ if (other.hasValue()) {
+ setValue(other.getValue());
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public final boolean isInitialized() {
+ return true;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ io.prometheus.client.Metrics.Gauge parsedMessage = null;
+ try {
+ parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ parsedMessage = (io.prometheus.client.Metrics.Gauge) e.getUnfinishedMessage();
+ throw e;
+ } finally {
+ if (parsedMessage != null) {
+ mergeFrom(parsedMessage);
+ }
+ }
+ return this;
+ }
+ private int bitField0_;
+
+ private double value_ ;
+ /**
+ * optional double value = 1;
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional double value = 1;
+ */
+ public double getValue() {
+ return value_;
+ }
+ /**
+ * optional double value = 1;
+ */
+ public Builder setValue(double value) {
+ bitField0_ |= 0x00000001;
+ value_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional double value = 1;
+ */
+ public Builder clearValue() {
+ bitField0_ = (bitField0_ & ~0x00000001);
+ value_ = 0D;
+ onChanged();
+ return this;
+ }
+
+ // @@protoc_insertion_point(builder_scope:io.prometheus.client.Gauge)
+ }
+
+ static {
+ defaultInstance = new Gauge(true);
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Gauge)
+ }
+
+ public interface CounterOrBuilder extends
+ // @@protoc_insertion_point(interface_extends:io.prometheus.client.Counter)
+ com.google.protobuf.MessageOrBuilder {
+
+ /**
+ * optional double value = 1;
+ */
+ boolean hasValue();
+ /**
+ * optional double value = 1;
+ */
+ double getValue();
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Counter}
+ */
+ public static final class Counter extends
+ com.google.protobuf.GeneratedMessage implements
+ // @@protoc_insertion_point(message_implements:io.prometheus.client.Counter)
+ CounterOrBuilder {
+ // Use Counter.newBuilder() to construct.
+ private Counter(com.google.protobuf.GeneratedMessage.Builder> builder) {
+ super(builder);
+ this.unknownFields = builder.getUnknownFields();
+ }
+ private Counter(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+ private static final Counter defaultInstance;
+ public static Counter getDefaultInstance() {
+ return defaultInstance;
+ }
+
+ public Counter getDefaultInstanceForType() {
+ return defaultInstance;
+ }
+
+ private final com.google.protobuf.UnknownFieldSet unknownFields;
+ @java.lang.Override
+ public final com.google.protobuf.UnknownFieldSet
+ getUnknownFields() {
+ return this.unknownFields;
+ }
+ private Counter(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ initFields();
+ int mutable_bitField0_ = 0;
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder();
+ try {
+ boolean done = false;
+ while (!done) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ done = true;
+ break;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ done = true;
+ }
+ break;
+ }
+ case 9: {
+ bitField0_ |= 0x00000001;
+ value_ = input.readDouble();
+ break;
+ }
+ }
+ }
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(this);
+ } catch (java.io.IOException e) {
+ throw new com.google.protobuf.InvalidProtocolBufferException(
+ e.getMessage()).setUnfinishedMessage(this);
+ } finally {
+ this.unknownFields = unknownFields.build();
+ makeExtensionsImmutable();
+ }
+ }
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Counter_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Counter_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Counter.class, io.prometheus.client.Metrics.Counter.Builder.class);
+ }
+
+ public static com.google.protobuf.Parser PARSER =
+ new com.google.protobuf.AbstractParser() {
+ public Counter parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new Counter(input, extensionRegistry);
+ }
+ };
+
+ @java.lang.Override
+ public com.google.protobuf.Parser getParserForType() {
+ return PARSER;
+ }
+
+ private int bitField0_;
+ public static final int VALUE_FIELD_NUMBER = 1;
+ private double value_;
+ /**
+ * optional double value = 1;
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional double value = 1;
+ */
+ public double getValue() {
+ return value_;
+ }
+
+ private void initFields() {
+ value_ = 0D;
+ }
+ private byte memoizedIsInitialized = -1;
+ public final boolean isInitialized() {
+ byte isInitialized = memoizedIsInitialized;
+ if (isInitialized == 1) return true;
+ if (isInitialized == 0) return false;
+
+ memoizedIsInitialized = 1;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ output.writeDouble(1, value_);
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeDoubleSize(1, value_);
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ private static final long serialVersionUID = 0L;
+ @java.lang.Override
+ protected java.lang.Object writeReplace()
+ throws java.io.ObjectStreamException {
+ return super.writeReplace();
+ }
+
+ public static io.prometheus.client.Metrics.Counter parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Counter parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Counter parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Counter parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Counter parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Counter parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Counter parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Counter parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Counter parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Counter parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static Builder newBuilder() { return Builder.create(); }
+ public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder newBuilder(io.prometheus.client.Metrics.Counter prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() { return newBuilder(this); }
+
+ @java.lang.Override
+ protected Builder newBuilderForType(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ Builder builder = new Builder(parent);
+ return builder;
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Counter}
+ */
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder implements
+ // @@protoc_insertion_point(builder_implements:io.prometheus.client.Counter)
+ io.prometheus.client.Metrics.CounterOrBuilder {
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Counter_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Counter_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Counter.class, io.prometheus.client.Metrics.Counter.Builder.class);
+ }
+
+ // Construct using io.prometheus.client.Metrics.Counter.newBuilder()
+ private Builder() {
+ maybeForceBuilderInitialization();
+ }
+
+ private Builder(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ super(parent);
+ maybeForceBuilderInitialization();
+ }
+ private void maybeForceBuilderInitialization() {
+ if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ }
+ }
+ private static Builder create() {
+ return new Builder();
+ }
+
+ public Builder clear() {
+ super.clear();
+ value_ = 0D;
+ bitField0_ = (bitField0_ & ~0x00000001);
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(buildPartial());
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Counter_descriptor;
+ }
+
+ public io.prometheus.client.Metrics.Counter getDefaultInstanceForType() {
+ return io.prometheus.client.Metrics.Counter.getDefaultInstance();
+ }
+
+ public io.prometheus.client.Metrics.Counter build() {
+ io.prometheus.client.Metrics.Counter result = buildPartial();
+ if (!result.isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return result;
+ }
+
+ public io.prometheus.client.Metrics.Counter buildPartial() {
+ io.prometheus.client.Metrics.Counter result = new io.prometheus.client.Metrics.Counter(this);
+ int from_bitField0_ = bitField0_;
+ int to_bitField0_ = 0;
+ if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+ to_bitField0_ |= 0x00000001;
+ }
+ result.value_ = value_;
+ result.bitField0_ = to_bitField0_;
+ onBuilt();
+ return result;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof io.prometheus.client.Metrics.Counter) {
+ return mergeFrom((io.prometheus.client.Metrics.Counter)other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(io.prometheus.client.Metrics.Counter other) {
+ if (other == io.prometheus.client.Metrics.Counter.getDefaultInstance()) return this;
+ if (other.hasValue()) {
+ setValue(other.getValue());
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public final boolean isInitialized() {
+ return true;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ io.prometheus.client.Metrics.Counter parsedMessage = null;
+ try {
+ parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ parsedMessage = (io.prometheus.client.Metrics.Counter) e.getUnfinishedMessage();
+ throw e;
+ } finally {
+ if (parsedMessage != null) {
+ mergeFrom(parsedMessage);
+ }
+ }
+ return this;
+ }
+ private int bitField0_;
+
+ private double value_ ;
+ /**
+ * optional double value = 1;
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional double value = 1;
+ */
+ public double getValue() {
+ return value_;
+ }
+ /**
+ * optional double value = 1;
+ */
+ public Builder setValue(double value) {
+ bitField0_ |= 0x00000001;
+ value_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional double value = 1;
+ */
+ public Builder clearValue() {
+ bitField0_ = (bitField0_ & ~0x00000001);
+ value_ = 0D;
+ onChanged();
+ return this;
+ }
+
+ // @@protoc_insertion_point(builder_scope:io.prometheus.client.Counter)
+ }
+
+ static {
+ defaultInstance = new Counter(true);
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Counter)
+ }
+
+ public interface QuantileOrBuilder extends
+ // @@protoc_insertion_point(interface_extends:io.prometheus.client.Quantile)
+ com.google.protobuf.MessageOrBuilder {
+
+ /**
+ * optional double quantile = 1;
+ */
+ boolean hasQuantile();
+ /**
+ * optional double quantile = 1;
+ */
+ double getQuantile();
+
+ /**
+ * optional double value = 2;
+ */
+ boolean hasValue();
+ /**
+ * optional double value = 2;
+ */
+ double getValue();
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Quantile}
+ */
+ public static final class Quantile extends
+ com.google.protobuf.GeneratedMessage implements
+ // @@protoc_insertion_point(message_implements:io.prometheus.client.Quantile)
+ QuantileOrBuilder {
+ // Use Quantile.newBuilder() to construct.
+ private Quantile(com.google.protobuf.GeneratedMessage.Builder> builder) {
+ super(builder);
+ this.unknownFields = builder.getUnknownFields();
+ }
+ private Quantile(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+ private static final Quantile defaultInstance;
+ public static Quantile getDefaultInstance() {
+ return defaultInstance;
+ }
+
+ public Quantile getDefaultInstanceForType() {
+ return defaultInstance;
+ }
+
+ private final com.google.protobuf.UnknownFieldSet unknownFields;
+ @java.lang.Override
+ public final com.google.protobuf.UnknownFieldSet
+ getUnknownFields() {
+ return this.unknownFields;
+ }
+ private Quantile(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ initFields();
+ int mutable_bitField0_ = 0;
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder();
+ try {
+ boolean done = false;
+ while (!done) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ done = true;
+ break;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ done = true;
+ }
+ break;
+ }
+ case 9: {
+ bitField0_ |= 0x00000001;
+ quantile_ = input.readDouble();
+ break;
+ }
+ case 17: {
+ bitField0_ |= 0x00000002;
+ value_ = input.readDouble();
+ break;
+ }
+ }
+ }
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(this);
+ } catch (java.io.IOException e) {
+ throw new com.google.protobuf.InvalidProtocolBufferException(
+ e.getMessage()).setUnfinishedMessage(this);
+ } finally {
+ this.unknownFields = unknownFields.build();
+ makeExtensionsImmutable();
+ }
+ }
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Quantile_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Quantile_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Quantile.class, io.prometheus.client.Metrics.Quantile.Builder.class);
+ }
+
+ public static com.google.protobuf.Parser PARSER =
+ new com.google.protobuf.AbstractParser() {
+ public Quantile parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new Quantile(input, extensionRegistry);
+ }
+ };
+
+ @java.lang.Override
+ public com.google.protobuf.Parser getParserForType() {
+ return PARSER;
+ }
+
+ private int bitField0_;
+ public static final int QUANTILE_FIELD_NUMBER = 1;
+ private double quantile_;
+ /**
+ * optional double quantile = 1;
+ */
+ public boolean hasQuantile() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional double quantile = 1;
+ */
+ public double getQuantile() {
+ return quantile_;
+ }
+
+ public static final int VALUE_FIELD_NUMBER = 2;
+ private double value_;
+ /**
+ * optional double value = 2;
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional double value = 2;
+ */
+ public double getValue() {
+ return value_;
+ }
+
+ private void initFields() {
+ quantile_ = 0D;
+ value_ = 0D;
+ }
+ private byte memoizedIsInitialized = -1;
+ public final boolean isInitialized() {
+ byte isInitialized = memoizedIsInitialized;
+ if (isInitialized == 1) return true;
+ if (isInitialized == 0) return false;
+
+ memoizedIsInitialized = 1;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ output.writeDouble(1, quantile_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ output.writeDouble(2, value_);
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeDoubleSize(1, quantile_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeDoubleSize(2, value_);
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ private static final long serialVersionUID = 0L;
+ @java.lang.Override
+ protected java.lang.Object writeReplace()
+ throws java.io.ObjectStreamException {
+ return super.writeReplace();
+ }
+
+ public static io.prometheus.client.Metrics.Quantile parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Quantile parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Quantile parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Quantile parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Quantile parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Quantile parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Quantile parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Quantile parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Quantile parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Quantile parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static Builder newBuilder() { return Builder.create(); }
+ public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder newBuilder(io.prometheus.client.Metrics.Quantile prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() { return newBuilder(this); }
+
+ @java.lang.Override
+ protected Builder newBuilderForType(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ Builder builder = new Builder(parent);
+ return builder;
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Quantile}
+ */
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder implements
+ // @@protoc_insertion_point(builder_implements:io.prometheus.client.Quantile)
+ io.prometheus.client.Metrics.QuantileOrBuilder {
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Quantile_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Quantile_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Quantile.class, io.prometheus.client.Metrics.Quantile.Builder.class);
+ }
+
+ // Construct using io.prometheus.client.Metrics.Quantile.newBuilder()
+ private Builder() {
+ maybeForceBuilderInitialization();
+ }
+
+ private Builder(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ super(parent);
+ maybeForceBuilderInitialization();
+ }
+ private void maybeForceBuilderInitialization() {
+ if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ }
+ }
+ private static Builder create() {
+ return new Builder();
+ }
+
+ public Builder clear() {
+ super.clear();
+ quantile_ = 0D;
+ bitField0_ = (bitField0_ & ~0x00000001);
+ value_ = 0D;
+ bitField0_ = (bitField0_ & ~0x00000002);
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(buildPartial());
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Quantile_descriptor;
+ }
+
+ public io.prometheus.client.Metrics.Quantile getDefaultInstanceForType() {
+ return io.prometheus.client.Metrics.Quantile.getDefaultInstance();
+ }
+
+ public io.prometheus.client.Metrics.Quantile build() {
+ io.prometheus.client.Metrics.Quantile result = buildPartial();
+ if (!result.isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return result;
+ }
+
+ public io.prometheus.client.Metrics.Quantile buildPartial() {
+ io.prometheus.client.Metrics.Quantile result = new io.prometheus.client.Metrics.Quantile(this);
+ int from_bitField0_ = bitField0_;
+ int to_bitField0_ = 0;
+ if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+ to_bitField0_ |= 0x00000001;
+ }
+ result.quantile_ = quantile_;
+ if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
+ to_bitField0_ |= 0x00000002;
+ }
+ result.value_ = value_;
+ result.bitField0_ = to_bitField0_;
+ onBuilt();
+ return result;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof io.prometheus.client.Metrics.Quantile) {
+ return mergeFrom((io.prometheus.client.Metrics.Quantile)other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(io.prometheus.client.Metrics.Quantile other) {
+ if (other == io.prometheus.client.Metrics.Quantile.getDefaultInstance()) return this;
+ if (other.hasQuantile()) {
+ setQuantile(other.getQuantile());
+ }
+ if (other.hasValue()) {
+ setValue(other.getValue());
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public final boolean isInitialized() {
+ return true;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ io.prometheus.client.Metrics.Quantile parsedMessage = null;
+ try {
+ parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ parsedMessage = (io.prometheus.client.Metrics.Quantile) e.getUnfinishedMessage();
+ throw e;
+ } finally {
+ if (parsedMessage != null) {
+ mergeFrom(parsedMessage);
+ }
+ }
+ return this;
+ }
+ private int bitField0_;
+
+ private double quantile_ ;
+ /**
+ * optional double quantile = 1;
+ */
+ public boolean hasQuantile() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional double quantile = 1;
+ */
+ public double getQuantile() {
+ return quantile_;
+ }
+ /**
+ * optional double quantile = 1;
+ */
+ public Builder setQuantile(double value) {
+ bitField0_ |= 0x00000001;
+ quantile_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional double quantile = 1;
+ */
+ public Builder clearQuantile() {
+ bitField0_ = (bitField0_ & ~0x00000001);
+ quantile_ = 0D;
+ onChanged();
+ return this;
+ }
+
+ private double value_ ;
+ /**
+ * optional double value = 2;
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional double value = 2;
+ */
+ public double getValue() {
+ return value_;
+ }
+ /**
+ * optional double value = 2;
+ */
+ public Builder setValue(double value) {
+ bitField0_ |= 0x00000002;
+ value_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional double value = 2;
+ */
+ public Builder clearValue() {
+ bitField0_ = (bitField0_ & ~0x00000002);
+ value_ = 0D;
+ onChanged();
+ return this;
+ }
+
+ // @@protoc_insertion_point(builder_scope:io.prometheus.client.Quantile)
+ }
+
+ static {
+ defaultInstance = new Quantile(true);
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Quantile)
+ }
+
+ public interface SummaryOrBuilder extends
+ // @@protoc_insertion_point(interface_extends:io.prometheus.client.Summary)
+ com.google.protobuf.MessageOrBuilder {
+
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ boolean hasSampleCount();
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ long getSampleCount();
+
+ /**
+ * optional double sample_sum = 2;
+ */
+ boolean hasSampleSum();
+ /**
+ * optional double sample_sum = 2;
+ */
+ double getSampleSum();
+
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ java.util.List
+ getQuantileList();
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ io.prometheus.client.Metrics.Quantile getQuantile(int index);
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ int getQuantileCount();
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ java.util.List extends io.prometheus.client.Metrics.QuantileOrBuilder>
+ getQuantileOrBuilderList();
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ io.prometheus.client.Metrics.QuantileOrBuilder getQuantileOrBuilder(
+ int index);
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Summary}
+ */
+ public static final class Summary extends
+ com.google.protobuf.GeneratedMessage implements
+ // @@protoc_insertion_point(message_implements:io.prometheus.client.Summary)
+ SummaryOrBuilder {
+ // Use Summary.newBuilder() to construct.
+ private Summary(com.google.protobuf.GeneratedMessage.Builder> builder) {
+ super(builder);
+ this.unknownFields = builder.getUnknownFields();
+ }
+ private Summary(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+ private static final Summary defaultInstance;
+ public static Summary getDefaultInstance() {
+ return defaultInstance;
+ }
+
+ public Summary getDefaultInstanceForType() {
+ return defaultInstance;
+ }
+
+ private final com.google.protobuf.UnknownFieldSet unknownFields;
+ @java.lang.Override
+ public final com.google.protobuf.UnknownFieldSet
+ getUnknownFields() {
+ return this.unknownFields;
+ }
+ private Summary(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ initFields();
+ int mutable_bitField0_ = 0;
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder();
+ try {
+ boolean done = false;
+ while (!done) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ done = true;
+ break;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ done = true;
+ }
+ break;
+ }
+ case 8: {
+ bitField0_ |= 0x00000001;
+ sampleCount_ = input.readUInt64();
+ break;
+ }
+ case 17: {
+ bitField0_ |= 0x00000002;
+ sampleSum_ = input.readDouble();
+ break;
+ }
+ case 26: {
+ if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
+ quantile_ = new java.util.ArrayList();
+ mutable_bitField0_ |= 0x00000004;
+ }
+ quantile_.add(input.readMessage(io.prometheus.client.Metrics.Quantile.PARSER, extensionRegistry));
+ break;
+ }
+ }
+ }
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(this);
+ } catch (java.io.IOException e) {
+ throw new com.google.protobuf.InvalidProtocolBufferException(
+ e.getMessage()).setUnfinishedMessage(this);
+ } finally {
+ if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
+ quantile_ = java.util.Collections.unmodifiableList(quantile_);
+ }
+ this.unknownFields = unknownFields.build();
+ makeExtensionsImmutable();
+ }
+ }
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Summary_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Summary_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Summary.class, io.prometheus.client.Metrics.Summary.Builder.class);
+ }
+
+ public static com.google.protobuf.Parser PARSER =
+ new com.google.protobuf.AbstractParser() {
+ public Summary parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new Summary(input, extensionRegistry);
+ }
+ };
+
+ @java.lang.Override
+ public com.google.protobuf.Parser getParserForType() {
+ return PARSER;
+ }
+
+ private int bitField0_;
+ public static final int SAMPLE_COUNT_FIELD_NUMBER = 1;
+ private long sampleCount_;
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ public boolean hasSampleCount() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ public long getSampleCount() {
+ return sampleCount_;
+ }
+
+ public static final int SAMPLE_SUM_FIELD_NUMBER = 2;
+ private double sampleSum_;
+ /**
+ * optional double sample_sum = 2;
+ */
+ public boolean hasSampleSum() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional double sample_sum = 2;
+ */
+ public double getSampleSum() {
+ return sampleSum_;
+ }
+
+ public static final int QUANTILE_FIELD_NUMBER = 3;
+ private java.util.List quantile_;
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public java.util.List getQuantileList() {
+ return quantile_;
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public java.util.List extends io.prometheus.client.Metrics.QuantileOrBuilder>
+ getQuantileOrBuilderList() {
+ return quantile_;
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public int getQuantileCount() {
+ return quantile_.size();
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public io.prometheus.client.Metrics.Quantile getQuantile(int index) {
+ return quantile_.get(index);
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public io.prometheus.client.Metrics.QuantileOrBuilder getQuantileOrBuilder(
+ int index) {
+ return quantile_.get(index);
+ }
+
+ private void initFields() {
+ sampleCount_ = 0L;
+ sampleSum_ = 0D;
+ quantile_ = java.util.Collections.emptyList();
+ }
+ private byte memoizedIsInitialized = -1;
+ public final boolean isInitialized() {
+ byte isInitialized = memoizedIsInitialized;
+ if (isInitialized == 1) return true;
+ if (isInitialized == 0) return false;
+
+ memoizedIsInitialized = 1;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ output.writeUInt64(1, sampleCount_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ output.writeDouble(2, sampleSum_);
+ }
+ for (int i = 0; i < quantile_.size(); i++) {
+ output.writeMessage(3, quantile_.get(i));
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeUInt64Size(1, sampleCount_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeDoubleSize(2, sampleSum_);
+ }
+ for (int i = 0; i < quantile_.size(); i++) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeMessageSize(3, quantile_.get(i));
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ private static final long serialVersionUID = 0L;
+ @java.lang.Override
+ protected java.lang.Object writeReplace()
+ throws java.io.ObjectStreamException {
+ return super.writeReplace();
+ }
+
+ public static io.prometheus.client.Metrics.Summary parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Summary parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Summary parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Summary parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Summary parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Summary parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Summary parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Summary parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Summary parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Summary parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static Builder newBuilder() { return Builder.create(); }
+ public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder newBuilder(io.prometheus.client.Metrics.Summary prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() { return newBuilder(this); }
+
+ @java.lang.Override
+ protected Builder newBuilderForType(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ Builder builder = new Builder(parent);
+ return builder;
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Summary}
+ */
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder implements
+ // @@protoc_insertion_point(builder_implements:io.prometheus.client.Summary)
+ io.prometheus.client.Metrics.SummaryOrBuilder {
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Summary_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Summary_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Summary.class, io.prometheus.client.Metrics.Summary.Builder.class);
+ }
+
+ // Construct using io.prometheus.client.Metrics.Summary.newBuilder()
+ private Builder() {
+ maybeForceBuilderInitialization();
+ }
+
+ private Builder(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ super(parent);
+ maybeForceBuilderInitialization();
+ }
+ private void maybeForceBuilderInitialization() {
+ if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ getQuantileFieldBuilder();
+ }
+ }
+ private static Builder create() {
+ return new Builder();
+ }
+
+ public Builder clear() {
+ super.clear();
+ sampleCount_ = 0L;
+ bitField0_ = (bitField0_ & ~0x00000001);
+ sampleSum_ = 0D;
+ bitField0_ = (bitField0_ & ~0x00000002);
+ if (quantileBuilder_ == null) {
+ quantile_ = java.util.Collections.emptyList();
+ bitField0_ = (bitField0_ & ~0x00000004);
+ } else {
+ quantileBuilder_.clear();
+ }
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(buildPartial());
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Summary_descriptor;
+ }
+
+ public io.prometheus.client.Metrics.Summary getDefaultInstanceForType() {
+ return io.prometheus.client.Metrics.Summary.getDefaultInstance();
+ }
+
+ public io.prometheus.client.Metrics.Summary build() {
+ io.prometheus.client.Metrics.Summary result = buildPartial();
+ if (!result.isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return result;
+ }
+
+ public io.prometheus.client.Metrics.Summary buildPartial() {
+ io.prometheus.client.Metrics.Summary result = new io.prometheus.client.Metrics.Summary(this);
+ int from_bitField0_ = bitField0_;
+ int to_bitField0_ = 0;
+ if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+ to_bitField0_ |= 0x00000001;
+ }
+ result.sampleCount_ = sampleCount_;
+ if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
+ to_bitField0_ |= 0x00000002;
+ }
+ result.sampleSum_ = sampleSum_;
+ if (quantileBuilder_ == null) {
+ if (((bitField0_ & 0x00000004) == 0x00000004)) {
+ quantile_ = java.util.Collections.unmodifiableList(quantile_);
+ bitField0_ = (bitField0_ & ~0x00000004);
+ }
+ result.quantile_ = quantile_;
+ } else {
+ result.quantile_ = quantileBuilder_.build();
+ }
+ result.bitField0_ = to_bitField0_;
+ onBuilt();
+ return result;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof io.prometheus.client.Metrics.Summary) {
+ return mergeFrom((io.prometheus.client.Metrics.Summary)other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(io.prometheus.client.Metrics.Summary other) {
+ if (other == io.prometheus.client.Metrics.Summary.getDefaultInstance()) return this;
+ if (other.hasSampleCount()) {
+ setSampleCount(other.getSampleCount());
+ }
+ if (other.hasSampleSum()) {
+ setSampleSum(other.getSampleSum());
+ }
+ if (quantileBuilder_ == null) {
+ if (!other.quantile_.isEmpty()) {
+ if (quantile_.isEmpty()) {
+ quantile_ = other.quantile_;
+ bitField0_ = (bitField0_ & ~0x00000004);
+ } else {
+ ensureQuantileIsMutable();
+ quantile_.addAll(other.quantile_);
+ }
+ onChanged();
+ }
+ } else {
+ if (!other.quantile_.isEmpty()) {
+ if (quantileBuilder_.isEmpty()) {
+ quantileBuilder_.dispose();
+ quantileBuilder_ = null;
+ quantile_ = other.quantile_;
+ bitField0_ = (bitField0_ & ~0x00000004);
+ quantileBuilder_ =
+ com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
+ getQuantileFieldBuilder() : null;
+ } else {
+ quantileBuilder_.addAllMessages(other.quantile_);
+ }
+ }
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public final boolean isInitialized() {
+ return true;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ io.prometheus.client.Metrics.Summary parsedMessage = null;
+ try {
+ parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ parsedMessage = (io.prometheus.client.Metrics.Summary) e.getUnfinishedMessage();
+ throw e;
+ } finally {
+ if (parsedMessage != null) {
+ mergeFrom(parsedMessage);
+ }
+ }
+ return this;
+ }
+ private int bitField0_;
+
+ private long sampleCount_ ;
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ public boolean hasSampleCount() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ public long getSampleCount() {
+ return sampleCount_;
+ }
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ public Builder setSampleCount(long value) {
+ bitField0_ |= 0x00000001;
+ sampleCount_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ public Builder clearSampleCount() {
+ bitField0_ = (bitField0_ & ~0x00000001);
+ sampleCount_ = 0L;
+ onChanged();
+ return this;
+ }
+
+ private double sampleSum_ ;
+ /**
+ * optional double sample_sum = 2;
+ */
+ public boolean hasSampleSum() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional double sample_sum = 2;
+ */
+ public double getSampleSum() {
+ return sampleSum_;
+ }
+ /**
+ * optional double sample_sum = 2;
+ */
+ public Builder setSampleSum(double value) {
+ bitField0_ |= 0x00000002;
+ sampleSum_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional double sample_sum = 2;
+ */
+ public Builder clearSampleSum() {
+ bitField0_ = (bitField0_ & ~0x00000002);
+ sampleSum_ = 0D;
+ onChanged();
+ return this;
+ }
+
+ private java.util.List quantile_ =
+ java.util.Collections.emptyList();
+ private void ensureQuantileIsMutable() {
+ if (!((bitField0_ & 0x00000004) == 0x00000004)) {
+ quantile_ = new java.util.ArrayList(quantile_);
+ bitField0_ |= 0x00000004;
+ }
+ }
+
+ private com.google.protobuf.RepeatedFieldBuilder<
+ io.prometheus.client.Metrics.Quantile, io.prometheus.client.Metrics.Quantile.Builder, io.prometheus.client.Metrics.QuantileOrBuilder> quantileBuilder_;
+
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public java.util.List getQuantileList() {
+ if (quantileBuilder_ == null) {
+ return java.util.Collections.unmodifiableList(quantile_);
+ } else {
+ return quantileBuilder_.getMessageList();
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public int getQuantileCount() {
+ if (quantileBuilder_ == null) {
+ return quantile_.size();
+ } else {
+ return quantileBuilder_.getCount();
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public io.prometheus.client.Metrics.Quantile getQuantile(int index) {
+ if (quantileBuilder_ == null) {
+ return quantile_.get(index);
+ } else {
+ return quantileBuilder_.getMessage(index);
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public Builder setQuantile(
+ int index, io.prometheus.client.Metrics.Quantile value) {
+ if (quantileBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ ensureQuantileIsMutable();
+ quantile_.set(index, value);
+ onChanged();
+ } else {
+ quantileBuilder_.setMessage(index, value);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public Builder setQuantile(
+ int index, io.prometheus.client.Metrics.Quantile.Builder builderForValue) {
+ if (quantileBuilder_ == null) {
+ ensureQuantileIsMutable();
+ quantile_.set(index, builderForValue.build());
+ onChanged();
+ } else {
+ quantileBuilder_.setMessage(index, builderForValue.build());
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public Builder addQuantile(io.prometheus.client.Metrics.Quantile value) {
+ if (quantileBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ ensureQuantileIsMutable();
+ quantile_.add(value);
+ onChanged();
+ } else {
+ quantileBuilder_.addMessage(value);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public Builder addQuantile(
+ int index, io.prometheus.client.Metrics.Quantile value) {
+ if (quantileBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ ensureQuantileIsMutable();
+ quantile_.add(index, value);
+ onChanged();
+ } else {
+ quantileBuilder_.addMessage(index, value);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public Builder addQuantile(
+ io.prometheus.client.Metrics.Quantile.Builder builderForValue) {
+ if (quantileBuilder_ == null) {
+ ensureQuantileIsMutable();
+ quantile_.add(builderForValue.build());
+ onChanged();
+ } else {
+ quantileBuilder_.addMessage(builderForValue.build());
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public Builder addQuantile(
+ int index, io.prometheus.client.Metrics.Quantile.Builder builderForValue) {
+ if (quantileBuilder_ == null) {
+ ensureQuantileIsMutable();
+ quantile_.add(index, builderForValue.build());
+ onChanged();
+ } else {
+ quantileBuilder_.addMessage(index, builderForValue.build());
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public Builder addAllQuantile(
+ java.lang.Iterable extends io.prometheus.client.Metrics.Quantile> values) {
+ if (quantileBuilder_ == null) {
+ ensureQuantileIsMutable();
+ com.google.protobuf.AbstractMessageLite.Builder.addAll(
+ values, quantile_);
+ onChanged();
+ } else {
+ quantileBuilder_.addAllMessages(values);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public Builder clearQuantile() {
+ if (quantileBuilder_ == null) {
+ quantile_ = java.util.Collections.emptyList();
+ bitField0_ = (bitField0_ & ~0x00000004);
+ onChanged();
+ } else {
+ quantileBuilder_.clear();
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public Builder removeQuantile(int index) {
+ if (quantileBuilder_ == null) {
+ ensureQuantileIsMutable();
+ quantile_.remove(index);
+ onChanged();
+ } else {
+ quantileBuilder_.remove(index);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public io.prometheus.client.Metrics.Quantile.Builder getQuantileBuilder(
+ int index) {
+ return getQuantileFieldBuilder().getBuilder(index);
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public io.prometheus.client.Metrics.QuantileOrBuilder getQuantileOrBuilder(
+ int index) {
+ if (quantileBuilder_ == null) {
+ return quantile_.get(index); } else {
+ return quantileBuilder_.getMessageOrBuilder(index);
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public java.util.List extends io.prometheus.client.Metrics.QuantileOrBuilder>
+ getQuantileOrBuilderList() {
+ if (quantileBuilder_ != null) {
+ return quantileBuilder_.getMessageOrBuilderList();
+ } else {
+ return java.util.Collections.unmodifiableList(quantile_);
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public io.prometheus.client.Metrics.Quantile.Builder addQuantileBuilder() {
+ return getQuantileFieldBuilder().addBuilder(
+ io.prometheus.client.Metrics.Quantile.getDefaultInstance());
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public io.prometheus.client.Metrics.Quantile.Builder addQuantileBuilder(
+ int index) {
+ return getQuantileFieldBuilder().addBuilder(
+ index, io.prometheus.client.Metrics.Quantile.getDefaultInstance());
+ }
+ /**
+ * repeated .io.prometheus.client.Quantile quantile = 3;
+ */
+ public java.util.List
+ getQuantileBuilderList() {
+ return getQuantileFieldBuilder().getBuilderList();
+ }
+ private com.google.protobuf.RepeatedFieldBuilder<
+ io.prometheus.client.Metrics.Quantile, io.prometheus.client.Metrics.Quantile.Builder, io.prometheus.client.Metrics.QuantileOrBuilder>
+ getQuantileFieldBuilder() {
+ if (quantileBuilder_ == null) {
+ quantileBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
+ io.prometheus.client.Metrics.Quantile, io.prometheus.client.Metrics.Quantile.Builder, io.prometheus.client.Metrics.QuantileOrBuilder>(
+ quantile_,
+ ((bitField0_ & 0x00000004) == 0x00000004),
+ getParentForChildren(),
+ isClean());
+ quantile_ = null;
+ }
+ return quantileBuilder_;
+ }
+
+ // @@protoc_insertion_point(builder_scope:io.prometheus.client.Summary)
+ }
+
+ static {
+ defaultInstance = new Summary(true);
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Summary)
+ }
+
+ public interface UntypedOrBuilder extends
+ // @@protoc_insertion_point(interface_extends:io.prometheus.client.Untyped)
+ com.google.protobuf.MessageOrBuilder {
+
+ /**
+ * optional double value = 1;
+ */
+ boolean hasValue();
+ /**
+ * optional double value = 1;
+ */
+ double getValue();
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Untyped}
+ */
+ public static final class Untyped extends
+ com.google.protobuf.GeneratedMessage implements
+ // @@protoc_insertion_point(message_implements:io.prometheus.client.Untyped)
+ UntypedOrBuilder {
+ // Use Untyped.newBuilder() to construct.
+ private Untyped(com.google.protobuf.GeneratedMessage.Builder> builder) {
+ super(builder);
+ this.unknownFields = builder.getUnknownFields();
+ }
+ private Untyped(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+ private static final Untyped defaultInstance;
+ public static Untyped getDefaultInstance() {
+ return defaultInstance;
+ }
+
+ public Untyped getDefaultInstanceForType() {
+ return defaultInstance;
+ }
+
+ private final com.google.protobuf.UnknownFieldSet unknownFields;
+ @java.lang.Override
+ public final com.google.protobuf.UnknownFieldSet
+ getUnknownFields() {
+ return this.unknownFields;
+ }
+ private Untyped(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ initFields();
+ int mutable_bitField0_ = 0;
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder();
+ try {
+ boolean done = false;
+ while (!done) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ done = true;
+ break;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ done = true;
+ }
+ break;
+ }
+ case 9: {
+ bitField0_ |= 0x00000001;
+ value_ = input.readDouble();
+ break;
+ }
+ }
+ }
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(this);
+ } catch (java.io.IOException e) {
+ throw new com.google.protobuf.InvalidProtocolBufferException(
+ e.getMessage()).setUnfinishedMessage(this);
+ } finally {
+ this.unknownFields = unknownFields.build();
+ makeExtensionsImmutable();
+ }
+ }
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Untyped_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Untyped_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Untyped.class, io.prometheus.client.Metrics.Untyped.Builder.class);
+ }
+
+ public static com.google.protobuf.Parser PARSER =
+ new com.google.protobuf.AbstractParser() {
+ public Untyped parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new Untyped(input, extensionRegistry);
+ }
+ };
+
+ @java.lang.Override
+ public com.google.protobuf.Parser getParserForType() {
+ return PARSER;
+ }
+
+ private int bitField0_;
+ public static final int VALUE_FIELD_NUMBER = 1;
+ private double value_;
+ /**
+ * optional double value = 1;
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional double value = 1;
+ */
+ public double getValue() {
+ return value_;
+ }
+
+ private void initFields() {
+ value_ = 0D;
+ }
+ private byte memoizedIsInitialized = -1;
+ public final boolean isInitialized() {
+ byte isInitialized = memoizedIsInitialized;
+ if (isInitialized == 1) return true;
+ if (isInitialized == 0) return false;
+
+ memoizedIsInitialized = 1;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ output.writeDouble(1, value_);
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeDoubleSize(1, value_);
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ private static final long serialVersionUID = 0L;
+ @java.lang.Override
+ protected java.lang.Object writeReplace()
+ throws java.io.ObjectStreamException {
+ return super.writeReplace();
+ }
+
+ public static io.prometheus.client.Metrics.Untyped parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Untyped parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Untyped parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Untyped parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Untyped parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Untyped parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Untyped parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Untyped parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Untyped parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Untyped parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static Builder newBuilder() { return Builder.create(); }
+ public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder newBuilder(io.prometheus.client.Metrics.Untyped prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() { return newBuilder(this); }
+
+ @java.lang.Override
+ protected Builder newBuilderForType(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ Builder builder = new Builder(parent);
+ return builder;
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Untyped}
+ */
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder implements
+ // @@protoc_insertion_point(builder_implements:io.prometheus.client.Untyped)
+ io.prometheus.client.Metrics.UntypedOrBuilder {
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Untyped_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Untyped_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Untyped.class, io.prometheus.client.Metrics.Untyped.Builder.class);
+ }
+
+ // Construct using io.prometheus.client.Metrics.Untyped.newBuilder()
+ private Builder() {
+ maybeForceBuilderInitialization();
+ }
+
+ private Builder(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ super(parent);
+ maybeForceBuilderInitialization();
+ }
+ private void maybeForceBuilderInitialization() {
+ if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ }
+ }
+ private static Builder create() {
+ return new Builder();
+ }
+
+ public Builder clear() {
+ super.clear();
+ value_ = 0D;
+ bitField0_ = (bitField0_ & ~0x00000001);
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(buildPartial());
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Untyped_descriptor;
+ }
+
+ public io.prometheus.client.Metrics.Untyped getDefaultInstanceForType() {
+ return io.prometheus.client.Metrics.Untyped.getDefaultInstance();
+ }
+
+ public io.prometheus.client.Metrics.Untyped build() {
+ io.prometheus.client.Metrics.Untyped result = buildPartial();
+ if (!result.isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return result;
+ }
+
+ public io.prometheus.client.Metrics.Untyped buildPartial() {
+ io.prometheus.client.Metrics.Untyped result = new io.prometheus.client.Metrics.Untyped(this);
+ int from_bitField0_ = bitField0_;
+ int to_bitField0_ = 0;
+ if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+ to_bitField0_ |= 0x00000001;
+ }
+ result.value_ = value_;
+ result.bitField0_ = to_bitField0_;
+ onBuilt();
+ return result;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof io.prometheus.client.Metrics.Untyped) {
+ return mergeFrom((io.prometheus.client.Metrics.Untyped)other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(io.prometheus.client.Metrics.Untyped other) {
+ if (other == io.prometheus.client.Metrics.Untyped.getDefaultInstance()) return this;
+ if (other.hasValue()) {
+ setValue(other.getValue());
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public final boolean isInitialized() {
+ return true;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ io.prometheus.client.Metrics.Untyped parsedMessage = null;
+ try {
+ parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ parsedMessage = (io.prometheus.client.Metrics.Untyped) e.getUnfinishedMessage();
+ throw e;
+ } finally {
+ if (parsedMessage != null) {
+ mergeFrom(parsedMessage);
+ }
+ }
+ return this;
+ }
+ private int bitField0_;
+
+ private double value_ ;
+ /**
+ * optional double value = 1;
+ */
+ public boolean hasValue() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional double value = 1;
+ */
+ public double getValue() {
+ return value_;
+ }
+ /**
+ * optional double value = 1;
+ */
+ public Builder setValue(double value) {
+ bitField0_ |= 0x00000001;
+ value_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional double value = 1;
+ */
+ public Builder clearValue() {
+ bitField0_ = (bitField0_ & ~0x00000001);
+ value_ = 0D;
+ onChanged();
+ return this;
+ }
+
+ // @@protoc_insertion_point(builder_scope:io.prometheus.client.Untyped)
+ }
+
+ static {
+ defaultInstance = new Untyped(true);
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Untyped)
+ }
+
+ public interface HistogramOrBuilder extends
+ // @@protoc_insertion_point(interface_extends:io.prometheus.client.Histogram)
+ com.google.protobuf.MessageOrBuilder {
+
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ boolean hasSampleCount();
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ long getSampleCount();
+
+ /**
+ * optional double sample_sum = 2;
+ */
+ boolean hasSampleSum();
+ /**
+ * optional double sample_sum = 2;
+ */
+ double getSampleSum();
+
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ java.util.List
+ getBucketList();
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ io.prometheus.client.Metrics.Bucket getBucket(int index);
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ int getBucketCount();
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ java.util.List extends io.prometheus.client.Metrics.BucketOrBuilder>
+ getBucketOrBuilderList();
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ io.prometheus.client.Metrics.BucketOrBuilder getBucketOrBuilder(
+ int index);
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Histogram}
+ */
+ public static final class Histogram extends
+ com.google.protobuf.GeneratedMessage implements
+ // @@protoc_insertion_point(message_implements:io.prometheus.client.Histogram)
+ HistogramOrBuilder {
+ // Use Histogram.newBuilder() to construct.
+ private Histogram(com.google.protobuf.GeneratedMessage.Builder> builder) {
+ super(builder);
+ this.unknownFields = builder.getUnknownFields();
+ }
+ private Histogram(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+ private static final Histogram defaultInstance;
+ public static Histogram getDefaultInstance() {
+ return defaultInstance;
+ }
+
+ public Histogram getDefaultInstanceForType() {
+ return defaultInstance;
+ }
+
+ private final com.google.protobuf.UnknownFieldSet unknownFields;
+ @java.lang.Override
+ public final com.google.protobuf.UnknownFieldSet
+ getUnknownFields() {
+ return this.unknownFields;
+ }
+ private Histogram(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ initFields();
+ int mutable_bitField0_ = 0;
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder();
+ try {
+ boolean done = false;
+ while (!done) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ done = true;
+ break;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ done = true;
+ }
+ break;
+ }
+ case 8: {
+ bitField0_ |= 0x00000001;
+ sampleCount_ = input.readUInt64();
+ break;
+ }
+ case 17: {
+ bitField0_ |= 0x00000002;
+ sampleSum_ = input.readDouble();
+ break;
+ }
+ case 26: {
+ if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
+ bucket_ = new java.util.ArrayList();
+ mutable_bitField0_ |= 0x00000004;
+ }
+ bucket_.add(input.readMessage(io.prometheus.client.Metrics.Bucket.PARSER, extensionRegistry));
+ break;
+ }
+ }
+ }
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(this);
+ } catch (java.io.IOException e) {
+ throw new com.google.protobuf.InvalidProtocolBufferException(
+ e.getMessage()).setUnfinishedMessage(this);
+ } finally {
+ if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) {
+ bucket_ = java.util.Collections.unmodifiableList(bucket_);
+ }
+ this.unknownFields = unknownFields.build();
+ makeExtensionsImmutable();
+ }
+ }
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Histogram_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Histogram_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Histogram.class, io.prometheus.client.Metrics.Histogram.Builder.class);
+ }
+
+ public static com.google.protobuf.Parser PARSER =
+ new com.google.protobuf.AbstractParser() {
+ public Histogram parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new Histogram(input, extensionRegistry);
+ }
+ };
+
+ @java.lang.Override
+ public com.google.protobuf.Parser getParserForType() {
+ return PARSER;
+ }
+
+ private int bitField0_;
+ public static final int SAMPLE_COUNT_FIELD_NUMBER = 1;
+ private long sampleCount_;
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ public boolean hasSampleCount() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ public long getSampleCount() {
+ return sampleCount_;
+ }
+
+ public static final int SAMPLE_SUM_FIELD_NUMBER = 2;
+ private double sampleSum_;
+ /**
+ * optional double sample_sum = 2;
+ */
+ public boolean hasSampleSum() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional double sample_sum = 2;
+ */
+ public double getSampleSum() {
+ return sampleSum_;
+ }
+
+ public static final int BUCKET_FIELD_NUMBER = 3;
+ private java.util.List bucket_;
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public java.util.List getBucketList() {
+ return bucket_;
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public java.util.List extends io.prometheus.client.Metrics.BucketOrBuilder>
+ getBucketOrBuilderList() {
+ return bucket_;
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public int getBucketCount() {
+ return bucket_.size();
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public io.prometheus.client.Metrics.Bucket getBucket(int index) {
+ return bucket_.get(index);
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public io.prometheus.client.Metrics.BucketOrBuilder getBucketOrBuilder(
+ int index) {
+ return bucket_.get(index);
+ }
+
+ private void initFields() {
+ sampleCount_ = 0L;
+ sampleSum_ = 0D;
+ bucket_ = java.util.Collections.emptyList();
+ }
+ private byte memoizedIsInitialized = -1;
+ public final boolean isInitialized() {
+ byte isInitialized = memoizedIsInitialized;
+ if (isInitialized == 1) return true;
+ if (isInitialized == 0) return false;
+
+ memoizedIsInitialized = 1;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ output.writeUInt64(1, sampleCount_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ output.writeDouble(2, sampleSum_);
+ }
+ for (int i = 0; i < bucket_.size(); i++) {
+ output.writeMessage(3, bucket_.get(i));
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeUInt64Size(1, sampleCount_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeDoubleSize(2, sampleSum_);
+ }
+ for (int i = 0; i < bucket_.size(); i++) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeMessageSize(3, bucket_.get(i));
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ private static final long serialVersionUID = 0L;
+ @java.lang.Override
+ protected java.lang.Object writeReplace()
+ throws java.io.ObjectStreamException {
+ return super.writeReplace();
+ }
+
+ public static io.prometheus.client.Metrics.Histogram parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Histogram parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Histogram parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Histogram parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Histogram parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Histogram parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Histogram parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Histogram parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Histogram parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Histogram parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static Builder newBuilder() { return Builder.create(); }
+ public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder newBuilder(io.prometheus.client.Metrics.Histogram prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() { return newBuilder(this); }
+
+ @java.lang.Override
+ protected Builder newBuilderForType(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ Builder builder = new Builder(parent);
+ return builder;
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Histogram}
+ */
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder implements
+ // @@protoc_insertion_point(builder_implements:io.prometheus.client.Histogram)
+ io.prometheus.client.Metrics.HistogramOrBuilder {
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Histogram_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Histogram_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Histogram.class, io.prometheus.client.Metrics.Histogram.Builder.class);
+ }
+
+ // Construct using io.prometheus.client.Metrics.Histogram.newBuilder()
+ private Builder() {
+ maybeForceBuilderInitialization();
+ }
+
+ private Builder(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ super(parent);
+ maybeForceBuilderInitialization();
+ }
+ private void maybeForceBuilderInitialization() {
+ if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ getBucketFieldBuilder();
+ }
+ }
+ private static Builder create() {
+ return new Builder();
+ }
+
+ public Builder clear() {
+ super.clear();
+ sampleCount_ = 0L;
+ bitField0_ = (bitField0_ & ~0x00000001);
+ sampleSum_ = 0D;
+ bitField0_ = (bitField0_ & ~0x00000002);
+ if (bucketBuilder_ == null) {
+ bucket_ = java.util.Collections.emptyList();
+ bitField0_ = (bitField0_ & ~0x00000004);
+ } else {
+ bucketBuilder_.clear();
+ }
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(buildPartial());
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Histogram_descriptor;
+ }
+
+ public io.prometheus.client.Metrics.Histogram getDefaultInstanceForType() {
+ return io.prometheus.client.Metrics.Histogram.getDefaultInstance();
+ }
+
+ public io.prometheus.client.Metrics.Histogram build() {
+ io.prometheus.client.Metrics.Histogram result = buildPartial();
+ if (!result.isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return result;
+ }
+
+ public io.prometheus.client.Metrics.Histogram buildPartial() {
+ io.prometheus.client.Metrics.Histogram result = new io.prometheus.client.Metrics.Histogram(this);
+ int from_bitField0_ = bitField0_;
+ int to_bitField0_ = 0;
+ if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+ to_bitField0_ |= 0x00000001;
+ }
+ result.sampleCount_ = sampleCount_;
+ if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
+ to_bitField0_ |= 0x00000002;
+ }
+ result.sampleSum_ = sampleSum_;
+ if (bucketBuilder_ == null) {
+ if (((bitField0_ & 0x00000004) == 0x00000004)) {
+ bucket_ = java.util.Collections.unmodifiableList(bucket_);
+ bitField0_ = (bitField0_ & ~0x00000004);
+ }
+ result.bucket_ = bucket_;
+ } else {
+ result.bucket_ = bucketBuilder_.build();
+ }
+ result.bitField0_ = to_bitField0_;
+ onBuilt();
+ return result;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof io.prometheus.client.Metrics.Histogram) {
+ return mergeFrom((io.prometheus.client.Metrics.Histogram)other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(io.prometheus.client.Metrics.Histogram other) {
+ if (other == io.prometheus.client.Metrics.Histogram.getDefaultInstance()) return this;
+ if (other.hasSampleCount()) {
+ setSampleCount(other.getSampleCount());
+ }
+ if (other.hasSampleSum()) {
+ setSampleSum(other.getSampleSum());
+ }
+ if (bucketBuilder_ == null) {
+ if (!other.bucket_.isEmpty()) {
+ if (bucket_.isEmpty()) {
+ bucket_ = other.bucket_;
+ bitField0_ = (bitField0_ & ~0x00000004);
+ } else {
+ ensureBucketIsMutable();
+ bucket_.addAll(other.bucket_);
+ }
+ onChanged();
+ }
+ } else {
+ if (!other.bucket_.isEmpty()) {
+ if (bucketBuilder_.isEmpty()) {
+ bucketBuilder_.dispose();
+ bucketBuilder_ = null;
+ bucket_ = other.bucket_;
+ bitField0_ = (bitField0_ & ~0x00000004);
+ bucketBuilder_ =
+ com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
+ getBucketFieldBuilder() : null;
+ } else {
+ bucketBuilder_.addAllMessages(other.bucket_);
+ }
+ }
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public final boolean isInitialized() {
+ return true;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ io.prometheus.client.Metrics.Histogram parsedMessage = null;
+ try {
+ parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ parsedMessage = (io.prometheus.client.Metrics.Histogram) e.getUnfinishedMessage();
+ throw e;
+ } finally {
+ if (parsedMessage != null) {
+ mergeFrom(parsedMessage);
+ }
+ }
+ return this;
+ }
+ private int bitField0_;
+
+ private long sampleCount_ ;
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ public boolean hasSampleCount() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ public long getSampleCount() {
+ return sampleCount_;
+ }
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ public Builder setSampleCount(long value) {
+ bitField0_ |= 0x00000001;
+ sampleCount_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional uint64 sample_count = 1;
+ */
+ public Builder clearSampleCount() {
+ bitField0_ = (bitField0_ & ~0x00000001);
+ sampleCount_ = 0L;
+ onChanged();
+ return this;
+ }
+
+ private double sampleSum_ ;
+ /**
+ * optional double sample_sum = 2;
+ */
+ public boolean hasSampleSum() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional double sample_sum = 2;
+ */
+ public double getSampleSum() {
+ return sampleSum_;
+ }
+ /**
+ * optional double sample_sum = 2;
+ */
+ public Builder setSampleSum(double value) {
+ bitField0_ |= 0x00000002;
+ sampleSum_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional double sample_sum = 2;
+ */
+ public Builder clearSampleSum() {
+ bitField0_ = (bitField0_ & ~0x00000002);
+ sampleSum_ = 0D;
+ onChanged();
+ return this;
+ }
+
+ private java.util.List bucket_ =
+ java.util.Collections.emptyList();
+ private void ensureBucketIsMutable() {
+ if (!((bitField0_ & 0x00000004) == 0x00000004)) {
+ bucket_ = new java.util.ArrayList(bucket_);
+ bitField0_ |= 0x00000004;
+ }
+ }
+
+ private com.google.protobuf.RepeatedFieldBuilder<
+ io.prometheus.client.Metrics.Bucket, io.prometheus.client.Metrics.Bucket.Builder, io.prometheus.client.Metrics.BucketOrBuilder> bucketBuilder_;
+
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public java.util.List getBucketList() {
+ if (bucketBuilder_ == null) {
+ return java.util.Collections.unmodifiableList(bucket_);
+ } else {
+ return bucketBuilder_.getMessageList();
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public int getBucketCount() {
+ if (bucketBuilder_ == null) {
+ return bucket_.size();
+ } else {
+ return bucketBuilder_.getCount();
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public io.prometheus.client.Metrics.Bucket getBucket(int index) {
+ if (bucketBuilder_ == null) {
+ return bucket_.get(index);
+ } else {
+ return bucketBuilder_.getMessage(index);
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public Builder setBucket(
+ int index, io.prometheus.client.Metrics.Bucket value) {
+ if (bucketBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ ensureBucketIsMutable();
+ bucket_.set(index, value);
+ onChanged();
+ } else {
+ bucketBuilder_.setMessage(index, value);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public Builder setBucket(
+ int index, io.prometheus.client.Metrics.Bucket.Builder builderForValue) {
+ if (bucketBuilder_ == null) {
+ ensureBucketIsMutable();
+ bucket_.set(index, builderForValue.build());
+ onChanged();
+ } else {
+ bucketBuilder_.setMessage(index, builderForValue.build());
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public Builder addBucket(io.prometheus.client.Metrics.Bucket value) {
+ if (bucketBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ ensureBucketIsMutable();
+ bucket_.add(value);
+ onChanged();
+ } else {
+ bucketBuilder_.addMessage(value);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public Builder addBucket(
+ int index, io.prometheus.client.Metrics.Bucket value) {
+ if (bucketBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ ensureBucketIsMutable();
+ bucket_.add(index, value);
+ onChanged();
+ } else {
+ bucketBuilder_.addMessage(index, value);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public Builder addBucket(
+ io.prometheus.client.Metrics.Bucket.Builder builderForValue) {
+ if (bucketBuilder_ == null) {
+ ensureBucketIsMutable();
+ bucket_.add(builderForValue.build());
+ onChanged();
+ } else {
+ bucketBuilder_.addMessage(builderForValue.build());
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public Builder addBucket(
+ int index, io.prometheus.client.Metrics.Bucket.Builder builderForValue) {
+ if (bucketBuilder_ == null) {
+ ensureBucketIsMutable();
+ bucket_.add(index, builderForValue.build());
+ onChanged();
+ } else {
+ bucketBuilder_.addMessage(index, builderForValue.build());
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public Builder addAllBucket(
+ java.lang.Iterable extends io.prometheus.client.Metrics.Bucket> values) {
+ if (bucketBuilder_ == null) {
+ ensureBucketIsMutable();
+ com.google.protobuf.AbstractMessageLite.Builder.addAll(
+ values, bucket_);
+ onChanged();
+ } else {
+ bucketBuilder_.addAllMessages(values);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public Builder clearBucket() {
+ if (bucketBuilder_ == null) {
+ bucket_ = java.util.Collections.emptyList();
+ bitField0_ = (bitField0_ & ~0x00000004);
+ onChanged();
+ } else {
+ bucketBuilder_.clear();
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public Builder removeBucket(int index) {
+ if (bucketBuilder_ == null) {
+ ensureBucketIsMutable();
+ bucket_.remove(index);
+ onChanged();
+ } else {
+ bucketBuilder_.remove(index);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public io.prometheus.client.Metrics.Bucket.Builder getBucketBuilder(
+ int index) {
+ return getBucketFieldBuilder().getBuilder(index);
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public io.prometheus.client.Metrics.BucketOrBuilder getBucketOrBuilder(
+ int index) {
+ if (bucketBuilder_ == null) {
+ return bucket_.get(index); } else {
+ return bucketBuilder_.getMessageOrBuilder(index);
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public java.util.List extends io.prometheus.client.Metrics.BucketOrBuilder>
+ getBucketOrBuilderList() {
+ if (bucketBuilder_ != null) {
+ return bucketBuilder_.getMessageOrBuilderList();
+ } else {
+ return java.util.Collections.unmodifiableList(bucket_);
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public io.prometheus.client.Metrics.Bucket.Builder addBucketBuilder() {
+ return getBucketFieldBuilder().addBuilder(
+ io.prometheus.client.Metrics.Bucket.getDefaultInstance());
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public io.prometheus.client.Metrics.Bucket.Builder addBucketBuilder(
+ int index) {
+ return getBucketFieldBuilder().addBuilder(
+ index, io.prometheus.client.Metrics.Bucket.getDefaultInstance());
+ }
+ /**
+ * repeated .io.prometheus.client.Bucket bucket = 3;
+ *
+ *
+ * Ordered in increasing order of upper_bound, +Inf bucket is optional.
+ *
+ */
+ public java.util.List
+ getBucketBuilderList() {
+ return getBucketFieldBuilder().getBuilderList();
+ }
+ private com.google.protobuf.RepeatedFieldBuilder<
+ io.prometheus.client.Metrics.Bucket, io.prometheus.client.Metrics.Bucket.Builder, io.prometheus.client.Metrics.BucketOrBuilder>
+ getBucketFieldBuilder() {
+ if (bucketBuilder_ == null) {
+ bucketBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
+ io.prometheus.client.Metrics.Bucket, io.prometheus.client.Metrics.Bucket.Builder, io.prometheus.client.Metrics.BucketOrBuilder>(
+ bucket_,
+ ((bitField0_ & 0x00000004) == 0x00000004),
+ getParentForChildren(),
+ isClean());
+ bucket_ = null;
+ }
+ return bucketBuilder_;
+ }
+
+ // @@protoc_insertion_point(builder_scope:io.prometheus.client.Histogram)
+ }
+
+ static {
+ defaultInstance = new Histogram(true);
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Histogram)
+ }
+
+ public interface BucketOrBuilder extends
+ // @@protoc_insertion_point(interface_extends:io.prometheus.client.Bucket)
+ com.google.protobuf.MessageOrBuilder {
+
+ /**
+ * optional uint64 cumulative_count = 1;
+ *
+ *
+ * Cumulative in increasing order.
+ *
+ */
+ boolean hasCumulativeCount();
+ /**
+ * optional uint64 cumulative_count = 1;
+ *
+ *
+ * Cumulative in increasing order.
+ *
+ */
+ long getCumulativeCount();
+
+ /**
+ * optional double upper_bound = 2;
+ *
+ *
+ * Inclusive.
+ *
+ */
+ boolean hasUpperBound();
+ /**
+ * optional double upper_bound = 2;
+ *
+ *
+ * Inclusive.
+ *
+ */
+ double getUpperBound();
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Bucket}
+ */
+ public static final class Bucket extends
+ com.google.protobuf.GeneratedMessage implements
+ // @@protoc_insertion_point(message_implements:io.prometheus.client.Bucket)
+ BucketOrBuilder {
+ // Use Bucket.newBuilder() to construct.
+ private Bucket(com.google.protobuf.GeneratedMessage.Builder> builder) {
+ super(builder);
+ this.unknownFields = builder.getUnknownFields();
+ }
+ private Bucket(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+ private static final Bucket defaultInstance;
+ public static Bucket getDefaultInstance() {
+ return defaultInstance;
+ }
+
+ public Bucket getDefaultInstanceForType() {
+ return defaultInstance;
+ }
+
+ private final com.google.protobuf.UnknownFieldSet unknownFields;
+ @java.lang.Override
+ public final com.google.protobuf.UnknownFieldSet
+ getUnknownFields() {
+ return this.unknownFields;
+ }
+ private Bucket(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ initFields();
+ int mutable_bitField0_ = 0;
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder();
+ try {
+ boolean done = false;
+ while (!done) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ done = true;
+ break;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ done = true;
+ }
+ break;
+ }
+ case 8: {
+ bitField0_ |= 0x00000001;
+ cumulativeCount_ = input.readUInt64();
+ break;
+ }
+ case 17: {
+ bitField0_ |= 0x00000002;
+ upperBound_ = input.readDouble();
+ break;
+ }
+ }
+ }
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(this);
+ } catch (java.io.IOException e) {
+ throw new com.google.protobuf.InvalidProtocolBufferException(
+ e.getMessage()).setUnfinishedMessage(this);
+ } finally {
+ this.unknownFields = unknownFields.build();
+ makeExtensionsImmutable();
+ }
+ }
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Bucket_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Bucket_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Bucket.class, io.prometheus.client.Metrics.Bucket.Builder.class);
+ }
+
+ public static com.google.protobuf.Parser PARSER =
+ new com.google.protobuf.AbstractParser() {
+ public Bucket parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new Bucket(input, extensionRegistry);
+ }
+ };
+
+ @java.lang.Override
+ public com.google.protobuf.Parser getParserForType() {
+ return PARSER;
+ }
+
+ private int bitField0_;
+ public static final int CUMULATIVE_COUNT_FIELD_NUMBER = 1;
+ private long cumulativeCount_;
+ /**
+ * optional uint64 cumulative_count = 1;
+ *
+ *
+ * Cumulative in increasing order.
+ *
+ */
+ public boolean hasCumulativeCount() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional uint64 cumulative_count = 1;
+ *
+ *
+ * Cumulative in increasing order.
+ *
+ */
+ public long getCumulativeCount() {
+ return cumulativeCount_;
+ }
+
+ public static final int UPPER_BOUND_FIELD_NUMBER = 2;
+ private double upperBound_;
+ /**
+ * optional double upper_bound = 2;
+ *
+ *
+ * Inclusive.
+ *
+ */
+ public boolean hasUpperBound() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional double upper_bound = 2;
+ *
+ *
+ * Inclusive.
+ *
+ */
+ public double getUpperBound() {
+ return upperBound_;
+ }
+
+ private void initFields() {
+ cumulativeCount_ = 0L;
+ upperBound_ = 0D;
+ }
+ private byte memoizedIsInitialized = -1;
+ public final boolean isInitialized() {
+ byte isInitialized = memoizedIsInitialized;
+ if (isInitialized == 1) return true;
+ if (isInitialized == 0) return false;
+
+ memoizedIsInitialized = 1;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ output.writeUInt64(1, cumulativeCount_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ output.writeDouble(2, upperBound_);
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeUInt64Size(1, cumulativeCount_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeDoubleSize(2, upperBound_);
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ private static final long serialVersionUID = 0L;
+ @java.lang.Override
+ protected java.lang.Object writeReplace()
+ throws java.io.ObjectStreamException {
+ return super.writeReplace();
+ }
+
+ public static io.prometheus.client.Metrics.Bucket parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Bucket parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Bucket parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Bucket parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Bucket parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Bucket parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Bucket parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Bucket parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Bucket parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Bucket parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static Builder newBuilder() { return Builder.create(); }
+ public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder newBuilder(io.prometheus.client.Metrics.Bucket prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() { return newBuilder(this); }
+
+ @java.lang.Override
+ protected Builder newBuilderForType(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ Builder builder = new Builder(parent);
+ return builder;
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Bucket}
+ */
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder implements
+ // @@protoc_insertion_point(builder_implements:io.prometheus.client.Bucket)
+ io.prometheus.client.Metrics.BucketOrBuilder {
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Bucket_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Bucket_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Bucket.class, io.prometheus.client.Metrics.Bucket.Builder.class);
+ }
+
+ // Construct using io.prometheus.client.Metrics.Bucket.newBuilder()
+ private Builder() {
+ maybeForceBuilderInitialization();
+ }
+
+ private Builder(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ super(parent);
+ maybeForceBuilderInitialization();
+ }
+ private void maybeForceBuilderInitialization() {
+ if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ }
+ }
+ private static Builder create() {
+ return new Builder();
+ }
+
+ public Builder clear() {
+ super.clear();
+ cumulativeCount_ = 0L;
+ bitField0_ = (bitField0_ & ~0x00000001);
+ upperBound_ = 0D;
+ bitField0_ = (bitField0_ & ~0x00000002);
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(buildPartial());
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Bucket_descriptor;
+ }
+
+ public io.prometheus.client.Metrics.Bucket getDefaultInstanceForType() {
+ return io.prometheus.client.Metrics.Bucket.getDefaultInstance();
+ }
+
+ public io.prometheus.client.Metrics.Bucket build() {
+ io.prometheus.client.Metrics.Bucket result = buildPartial();
+ if (!result.isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return result;
+ }
+
+ public io.prometheus.client.Metrics.Bucket buildPartial() {
+ io.prometheus.client.Metrics.Bucket result = new io.prometheus.client.Metrics.Bucket(this);
+ int from_bitField0_ = bitField0_;
+ int to_bitField0_ = 0;
+ if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+ to_bitField0_ |= 0x00000001;
+ }
+ result.cumulativeCount_ = cumulativeCount_;
+ if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
+ to_bitField0_ |= 0x00000002;
+ }
+ result.upperBound_ = upperBound_;
+ result.bitField0_ = to_bitField0_;
+ onBuilt();
+ return result;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof io.prometheus.client.Metrics.Bucket) {
+ return mergeFrom((io.prometheus.client.Metrics.Bucket)other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(io.prometheus.client.Metrics.Bucket other) {
+ if (other == io.prometheus.client.Metrics.Bucket.getDefaultInstance()) return this;
+ if (other.hasCumulativeCount()) {
+ setCumulativeCount(other.getCumulativeCount());
+ }
+ if (other.hasUpperBound()) {
+ setUpperBound(other.getUpperBound());
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public final boolean isInitialized() {
+ return true;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ io.prometheus.client.Metrics.Bucket parsedMessage = null;
+ try {
+ parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ parsedMessage = (io.prometheus.client.Metrics.Bucket) e.getUnfinishedMessage();
+ throw e;
+ } finally {
+ if (parsedMessage != null) {
+ mergeFrom(parsedMessage);
+ }
+ }
+ return this;
+ }
+ private int bitField0_;
+
+ private long cumulativeCount_ ;
+ /**
+ * optional uint64 cumulative_count = 1;
+ *
+ *
+ * Cumulative in increasing order.
+ *
+ */
+ public boolean hasCumulativeCount() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional uint64 cumulative_count = 1;
+ *
+ *
+ * Cumulative in increasing order.
+ *
+ */
+ public long getCumulativeCount() {
+ return cumulativeCount_;
+ }
+ /**
+ * optional uint64 cumulative_count = 1;
+ *
+ *
+ * Cumulative in increasing order.
+ *
+ */
+ public Builder setCumulativeCount(long value) {
+ bitField0_ |= 0x00000001;
+ cumulativeCount_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional uint64 cumulative_count = 1;
+ *
+ *
+ * Cumulative in increasing order.
+ *
+ */
+ public Builder clearCumulativeCount() {
+ bitField0_ = (bitField0_ & ~0x00000001);
+ cumulativeCount_ = 0L;
+ onChanged();
+ return this;
+ }
+
+ private double upperBound_ ;
+ /**
+ * optional double upper_bound = 2;
+ *
+ *
+ * Inclusive.
+ *
+ */
+ public boolean hasUpperBound() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional double upper_bound = 2;
+ *
+ *
+ * Inclusive.
+ *
+ */
+ public double getUpperBound() {
+ return upperBound_;
+ }
+ /**
+ * optional double upper_bound = 2;
+ *
+ *
+ * Inclusive.
+ *
+ */
+ public Builder setUpperBound(double value) {
+ bitField0_ |= 0x00000002;
+ upperBound_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional double upper_bound = 2;
+ *
+ *
+ * Inclusive.
+ *
+ */
+ public Builder clearUpperBound() {
+ bitField0_ = (bitField0_ & ~0x00000002);
+ upperBound_ = 0D;
+ onChanged();
+ return this;
+ }
+
+ // @@protoc_insertion_point(builder_scope:io.prometheus.client.Bucket)
+ }
+
+ static {
+ defaultInstance = new Bucket(true);
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Bucket)
+ }
+
+ public interface MetricOrBuilder extends
+ // @@protoc_insertion_point(interface_extends:io.prometheus.client.Metric)
+ com.google.protobuf.MessageOrBuilder {
+
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ java.util.List
+ getLabelList();
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ io.prometheus.client.Metrics.LabelPair getLabel(int index);
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ int getLabelCount();
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ java.util.List extends io.prometheus.client.Metrics.LabelPairOrBuilder>
+ getLabelOrBuilderList();
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ io.prometheus.client.Metrics.LabelPairOrBuilder getLabelOrBuilder(
+ int index);
+
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ boolean hasGauge();
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ io.prometheus.client.Metrics.Gauge getGauge();
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ io.prometheus.client.Metrics.GaugeOrBuilder getGaugeOrBuilder();
+
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ boolean hasCounter();
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ io.prometheus.client.Metrics.Counter getCounter();
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ io.prometheus.client.Metrics.CounterOrBuilder getCounterOrBuilder();
+
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ boolean hasSummary();
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ io.prometheus.client.Metrics.Summary getSummary();
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ io.prometheus.client.Metrics.SummaryOrBuilder getSummaryOrBuilder();
+
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ boolean hasUntyped();
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ io.prometheus.client.Metrics.Untyped getUntyped();
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ io.prometheus.client.Metrics.UntypedOrBuilder getUntypedOrBuilder();
+
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ boolean hasHistogram();
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ io.prometheus.client.Metrics.Histogram getHistogram();
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ io.prometheus.client.Metrics.HistogramOrBuilder getHistogramOrBuilder();
+
+ /**
+ * optional int64 timestamp_ms = 6;
+ */
+ boolean hasTimestampMs();
+ /**
+ * optional int64 timestamp_ms = 6;
+ */
+ long getTimestampMs();
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Metric}
+ */
+ public static final class Metric extends
+ com.google.protobuf.GeneratedMessage implements
+ // @@protoc_insertion_point(message_implements:io.prometheus.client.Metric)
+ MetricOrBuilder {
+ // Use Metric.newBuilder() to construct.
+ private Metric(com.google.protobuf.GeneratedMessage.Builder> builder) {
+ super(builder);
+ this.unknownFields = builder.getUnknownFields();
+ }
+ private Metric(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+ private static final Metric defaultInstance;
+ public static Metric getDefaultInstance() {
+ return defaultInstance;
+ }
+
+ public Metric getDefaultInstanceForType() {
+ return defaultInstance;
+ }
+
+ private final com.google.protobuf.UnknownFieldSet unknownFields;
+ @java.lang.Override
+ public final com.google.protobuf.UnknownFieldSet
+ getUnknownFields() {
+ return this.unknownFields;
+ }
+ private Metric(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ initFields();
+ int mutable_bitField0_ = 0;
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder();
+ try {
+ boolean done = false;
+ while (!done) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ done = true;
+ break;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ done = true;
+ }
+ break;
+ }
+ case 10: {
+ if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
+ label_ = new java.util.ArrayList();
+ mutable_bitField0_ |= 0x00000001;
+ }
+ label_.add(input.readMessage(io.prometheus.client.Metrics.LabelPair.PARSER, extensionRegistry));
+ break;
+ }
+ case 18: {
+ io.prometheus.client.Metrics.Gauge.Builder subBuilder = null;
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ subBuilder = gauge_.toBuilder();
+ }
+ gauge_ = input.readMessage(io.prometheus.client.Metrics.Gauge.PARSER, extensionRegistry);
+ if (subBuilder != null) {
+ subBuilder.mergeFrom(gauge_);
+ gauge_ = subBuilder.buildPartial();
+ }
+ bitField0_ |= 0x00000001;
+ break;
+ }
+ case 26: {
+ io.prometheus.client.Metrics.Counter.Builder subBuilder = null;
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ subBuilder = counter_.toBuilder();
+ }
+ counter_ = input.readMessage(io.prometheus.client.Metrics.Counter.PARSER, extensionRegistry);
+ if (subBuilder != null) {
+ subBuilder.mergeFrom(counter_);
+ counter_ = subBuilder.buildPartial();
+ }
+ bitField0_ |= 0x00000002;
+ break;
+ }
+ case 34: {
+ io.prometheus.client.Metrics.Summary.Builder subBuilder = null;
+ if (((bitField0_ & 0x00000004) == 0x00000004)) {
+ subBuilder = summary_.toBuilder();
+ }
+ summary_ = input.readMessage(io.prometheus.client.Metrics.Summary.PARSER, extensionRegistry);
+ if (subBuilder != null) {
+ subBuilder.mergeFrom(summary_);
+ summary_ = subBuilder.buildPartial();
+ }
+ bitField0_ |= 0x00000004;
+ break;
+ }
+ case 42: {
+ io.prometheus.client.Metrics.Untyped.Builder subBuilder = null;
+ if (((bitField0_ & 0x00000008) == 0x00000008)) {
+ subBuilder = untyped_.toBuilder();
+ }
+ untyped_ = input.readMessage(io.prometheus.client.Metrics.Untyped.PARSER, extensionRegistry);
+ if (subBuilder != null) {
+ subBuilder.mergeFrom(untyped_);
+ untyped_ = subBuilder.buildPartial();
+ }
+ bitField0_ |= 0x00000008;
+ break;
+ }
+ case 48: {
+ bitField0_ |= 0x00000020;
+ timestampMs_ = input.readInt64();
+ break;
+ }
+ case 58: {
+ io.prometheus.client.Metrics.Histogram.Builder subBuilder = null;
+ if (((bitField0_ & 0x00000010) == 0x00000010)) {
+ subBuilder = histogram_.toBuilder();
+ }
+ histogram_ = input.readMessage(io.prometheus.client.Metrics.Histogram.PARSER, extensionRegistry);
+ if (subBuilder != null) {
+ subBuilder.mergeFrom(histogram_);
+ histogram_ = subBuilder.buildPartial();
+ }
+ bitField0_ |= 0x00000010;
+ break;
+ }
+ }
+ }
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(this);
+ } catch (java.io.IOException e) {
+ throw new com.google.protobuf.InvalidProtocolBufferException(
+ e.getMessage()).setUnfinishedMessage(this);
+ } finally {
+ if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
+ label_ = java.util.Collections.unmodifiableList(label_);
+ }
+ this.unknownFields = unknownFields.build();
+ makeExtensionsImmutable();
+ }
+ }
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Metric_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Metric_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Metric.class, io.prometheus.client.Metrics.Metric.Builder.class);
+ }
+
+ public static com.google.protobuf.Parser PARSER =
+ new com.google.protobuf.AbstractParser() {
+ public Metric parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new Metric(input, extensionRegistry);
+ }
+ };
+
+ @java.lang.Override
+ public com.google.protobuf.Parser getParserForType() {
+ return PARSER;
+ }
+
+ private int bitField0_;
+ public static final int LABEL_FIELD_NUMBER = 1;
+ private java.util.List label_;
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public java.util.List getLabelList() {
+ return label_;
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public java.util.List extends io.prometheus.client.Metrics.LabelPairOrBuilder>
+ getLabelOrBuilderList() {
+ return label_;
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public int getLabelCount() {
+ return label_.size();
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public io.prometheus.client.Metrics.LabelPair getLabel(int index) {
+ return label_.get(index);
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public io.prometheus.client.Metrics.LabelPairOrBuilder getLabelOrBuilder(
+ int index) {
+ return label_.get(index);
+ }
+
+ public static final int GAUGE_FIELD_NUMBER = 2;
+ private io.prometheus.client.Metrics.Gauge gauge_;
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ public boolean hasGauge() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ public io.prometheus.client.Metrics.Gauge getGauge() {
+ return gauge_;
+ }
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ public io.prometheus.client.Metrics.GaugeOrBuilder getGaugeOrBuilder() {
+ return gauge_;
+ }
+
+ public static final int COUNTER_FIELD_NUMBER = 3;
+ private io.prometheus.client.Metrics.Counter counter_;
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ public boolean hasCounter() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ public io.prometheus.client.Metrics.Counter getCounter() {
+ return counter_;
+ }
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ public io.prometheus.client.Metrics.CounterOrBuilder getCounterOrBuilder() {
+ return counter_;
+ }
+
+ public static final int SUMMARY_FIELD_NUMBER = 4;
+ private io.prometheus.client.Metrics.Summary summary_;
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ public boolean hasSummary() {
+ return ((bitField0_ & 0x00000004) == 0x00000004);
+ }
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ public io.prometheus.client.Metrics.Summary getSummary() {
+ return summary_;
+ }
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ public io.prometheus.client.Metrics.SummaryOrBuilder getSummaryOrBuilder() {
+ return summary_;
+ }
+
+ public static final int UNTYPED_FIELD_NUMBER = 5;
+ private io.prometheus.client.Metrics.Untyped untyped_;
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ public boolean hasUntyped() {
+ return ((bitField0_ & 0x00000008) == 0x00000008);
+ }
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ public io.prometheus.client.Metrics.Untyped getUntyped() {
+ return untyped_;
+ }
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ public io.prometheus.client.Metrics.UntypedOrBuilder getUntypedOrBuilder() {
+ return untyped_;
+ }
+
+ public static final int HISTOGRAM_FIELD_NUMBER = 7;
+ private io.prometheus.client.Metrics.Histogram histogram_;
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ public boolean hasHistogram() {
+ return ((bitField0_ & 0x00000010) == 0x00000010);
+ }
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ public io.prometheus.client.Metrics.Histogram getHistogram() {
+ return histogram_;
+ }
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ public io.prometheus.client.Metrics.HistogramOrBuilder getHistogramOrBuilder() {
+ return histogram_;
+ }
+
+ public static final int TIMESTAMP_MS_FIELD_NUMBER = 6;
+ private long timestampMs_;
+ /**
+ * optional int64 timestamp_ms = 6;
+ */
+ public boolean hasTimestampMs() {
+ return ((bitField0_ & 0x00000020) == 0x00000020);
+ }
+ /**
+ * optional int64 timestamp_ms = 6;
+ */
+ public long getTimestampMs() {
+ return timestampMs_;
+ }
+
+ private void initFields() {
+ label_ = java.util.Collections.emptyList();
+ gauge_ = io.prometheus.client.Metrics.Gauge.getDefaultInstance();
+ counter_ = io.prometheus.client.Metrics.Counter.getDefaultInstance();
+ summary_ = io.prometheus.client.Metrics.Summary.getDefaultInstance();
+ untyped_ = io.prometheus.client.Metrics.Untyped.getDefaultInstance();
+ histogram_ = io.prometheus.client.Metrics.Histogram.getDefaultInstance();
+ timestampMs_ = 0L;
+ }
+ private byte memoizedIsInitialized = -1;
+ public final boolean isInitialized() {
+ byte isInitialized = memoizedIsInitialized;
+ if (isInitialized == 1) return true;
+ if (isInitialized == 0) return false;
+
+ memoizedIsInitialized = 1;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ for (int i = 0; i < label_.size(); i++) {
+ output.writeMessage(1, label_.get(i));
+ }
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ output.writeMessage(2, gauge_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ output.writeMessage(3, counter_);
+ }
+ if (((bitField0_ & 0x00000004) == 0x00000004)) {
+ output.writeMessage(4, summary_);
+ }
+ if (((bitField0_ & 0x00000008) == 0x00000008)) {
+ output.writeMessage(5, untyped_);
+ }
+ if (((bitField0_ & 0x00000020) == 0x00000020)) {
+ output.writeInt64(6, timestampMs_);
+ }
+ if (((bitField0_ & 0x00000010) == 0x00000010)) {
+ output.writeMessage(7, histogram_);
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ for (int i = 0; i < label_.size(); i++) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeMessageSize(1, label_.get(i));
+ }
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeMessageSize(2, gauge_);
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeMessageSize(3, counter_);
+ }
+ if (((bitField0_ & 0x00000004) == 0x00000004)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeMessageSize(4, summary_);
+ }
+ if (((bitField0_ & 0x00000008) == 0x00000008)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeMessageSize(5, untyped_);
+ }
+ if (((bitField0_ & 0x00000020) == 0x00000020)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeInt64Size(6, timestampMs_);
+ }
+ if (((bitField0_ & 0x00000010) == 0x00000010)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeMessageSize(7, histogram_);
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ private static final long serialVersionUID = 0L;
+ @java.lang.Override
+ protected java.lang.Object writeReplace()
+ throws java.io.ObjectStreamException {
+ return super.writeReplace();
+ }
+
+ public static io.prometheus.client.Metrics.Metric parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Metric parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Metric parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.Metric parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Metric parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Metric parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Metric parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Metric parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.Metric parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.Metric parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static Builder newBuilder() { return Builder.create(); }
+ public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder newBuilder(io.prometheus.client.Metrics.Metric prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() { return newBuilder(this); }
+
+ @java.lang.Override
+ protected Builder newBuilderForType(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ Builder builder = new Builder(parent);
+ return builder;
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.Metric}
+ */
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder implements
+ // @@protoc_insertion_point(builder_implements:io.prometheus.client.Metric)
+ io.prometheus.client.Metrics.MetricOrBuilder {
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Metric_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Metric_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.Metric.class, io.prometheus.client.Metrics.Metric.Builder.class);
+ }
+
+ // Construct using io.prometheus.client.Metrics.Metric.newBuilder()
+ private Builder() {
+ maybeForceBuilderInitialization();
+ }
+
+ private Builder(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ super(parent);
+ maybeForceBuilderInitialization();
+ }
+ private void maybeForceBuilderInitialization() {
+ if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ getLabelFieldBuilder();
+ getGaugeFieldBuilder();
+ getCounterFieldBuilder();
+ getSummaryFieldBuilder();
+ getUntypedFieldBuilder();
+ getHistogramFieldBuilder();
+ }
+ }
+ private static Builder create() {
+ return new Builder();
+ }
+
+ public Builder clear() {
+ super.clear();
+ if (labelBuilder_ == null) {
+ label_ = java.util.Collections.emptyList();
+ bitField0_ = (bitField0_ & ~0x00000001);
+ } else {
+ labelBuilder_.clear();
+ }
+ if (gaugeBuilder_ == null) {
+ gauge_ = io.prometheus.client.Metrics.Gauge.getDefaultInstance();
+ } else {
+ gaugeBuilder_.clear();
+ }
+ bitField0_ = (bitField0_ & ~0x00000002);
+ if (counterBuilder_ == null) {
+ counter_ = io.prometheus.client.Metrics.Counter.getDefaultInstance();
+ } else {
+ counterBuilder_.clear();
+ }
+ bitField0_ = (bitField0_ & ~0x00000004);
+ if (summaryBuilder_ == null) {
+ summary_ = io.prometheus.client.Metrics.Summary.getDefaultInstance();
+ } else {
+ summaryBuilder_.clear();
+ }
+ bitField0_ = (bitField0_ & ~0x00000008);
+ if (untypedBuilder_ == null) {
+ untyped_ = io.prometheus.client.Metrics.Untyped.getDefaultInstance();
+ } else {
+ untypedBuilder_.clear();
+ }
+ bitField0_ = (bitField0_ & ~0x00000010);
+ if (histogramBuilder_ == null) {
+ histogram_ = io.prometheus.client.Metrics.Histogram.getDefaultInstance();
+ } else {
+ histogramBuilder_.clear();
+ }
+ bitField0_ = (bitField0_ & ~0x00000020);
+ timestampMs_ = 0L;
+ bitField0_ = (bitField0_ & ~0x00000040);
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(buildPartial());
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_Metric_descriptor;
+ }
+
+ public io.prometheus.client.Metrics.Metric getDefaultInstanceForType() {
+ return io.prometheus.client.Metrics.Metric.getDefaultInstance();
+ }
+
+ public io.prometheus.client.Metrics.Metric build() {
+ io.prometheus.client.Metrics.Metric result = buildPartial();
+ if (!result.isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return result;
+ }
+
+ public io.prometheus.client.Metrics.Metric buildPartial() {
+ io.prometheus.client.Metrics.Metric result = new io.prometheus.client.Metrics.Metric(this);
+ int from_bitField0_ = bitField0_;
+ int to_bitField0_ = 0;
+ if (labelBuilder_ == null) {
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ label_ = java.util.Collections.unmodifiableList(label_);
+ bitField0_ = (bitField0_ & ~0x00000001);
+ }
+ result.label_ = label_;
+ } else {
+ result.label_ = labelBuilder_.build();
+ }
+ if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
+ to_bitField0_ |= 0x00000001;
+ }
+ if (gaugeBuilder_ == null) {
+ result.gauge_ = gauge_;
+ } else {
+ result.gauge_ = gaugeBuilder_.build();
+ }
+ if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
+ to_bitField0_ |= 0x00000002;
+ }
+ if (counterBuilder_ == null) {
+ result.counter_ = counter_;
+ } else {
+ result.counter_ = counterBuilder_.build();
+ }
+ if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
+ to_bitField0_ |= 0x00000004;
+ }
+ if (summaryBuilder_ == null) {
+ result.summary_ = summary_;
+ } else {
+ result.summary_ = summaryBuilder_.build();
+ }
+ if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
+ to_bitField0_ |= 0x00000008;
+ }
+ if (untypedBuilder_ == null) {
+ result.untyped_ = untyped_;
+ } else {
+ result.untyped_ = untypedBuilder_.build();
+ }
+ if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
+ to_bitField0_ |= 0x00000010;
+ }
+ if (histogramBuilder_ == null) {
+ result.histogram_ = histogram_;
+ } else {
+ result.histogram_ = histogramBuilder_.build();
+ }
+ if (((from_bitField0_ & 0x00000040) == 0x00000040)) {
+ to_bitField0_ |= 0x00000020;
+ }
+ result.timestampMs_ = timestampMs_;
+ result.bitField0_ = to_bitField0_;
+ onBuilt();
+ return result;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof io.prometheus.client.Metrics.Metric) {
+ return mergeFrom((io.prometheus.client.Metrics.Metric)other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(io.prometheus.client.Metrics.Metric other) {
+ if (other == io.prometheus.client.Metrics.Metric.getDefaultInstance()) return this;
+ if (labelBuilder_ == null) {
+ if (!other.label_.isEmpty()) {
+ if (label_.isEmpty()) {
+ label_ = other.label_;
+ bitField0_ = (bitField0_ & ~0x00000001);
+ } else {
+ ensureLabelIsMutable();
+ label_.addAll(other.label_);
+ }
+ onChanged();
+ }
+ } else {
+ if (!other.label_.isEmpty()) {
+ if (labelBuilder_.isEmpty()) {
+ labelBuilder_.dispose();
+ labelBuilder_ = null;
+ label_ = other.label_;
+ bitField0_ = (bitField0_ & ~0x00000001);
+ labelBuilder_ =
+ com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
+ getLabelFieldBuilder() : null;
+ } else {
+ labelBuilder_.addAllMessages(other.label_);
+ }
+ }
+ }
+ if (other.hasGauge()) {
+ mergeGauge(other.getGauge());
+ }
+ if (other.hasCounter()) {
+ mergeCounter(other.getCounter());
+ }
+ if (other.hasSummary()) {
+ mergeSummary(other.getSummary());
+ }
+ if (other.hasUntyped()) {
+ mergeUntyped(other.getUntyped());
+ }
+ if (other.hasHistogram()) {
+ mergeHistogram(other.getHistogram());
+ }
+ if (other.hasTimestampMs()) {
+ setTimestampMs(other.getTimestampMs());
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public final boolean isInitialized() {
+ return true;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ io.prometheus.client.Metrics.Metric parsedMessage = null;
+ try {
+ parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ parsedMessage = (io.prometheus.client.Metrics.Metric) e.getUnfinishedMessage();
+ throw e;
+ } finally {
+ if (parsedMessage != null) {
+ mergeFrom(parsedMessage);
+ }
+ }
+ return this;
+ }
+ private int bitField0_;
+
+ private java.util.List label_ =
+ java.util.Collections.emptyList();
+ private void ensureLabelIsMutable() {
+ if (!((bitField0_ & 0x00000001) == 0x00000001)) {
+ label_ = new java.util.ArrayList(label_);
+ bitField0_ |= 0x00000001;
+ }
+ }
+
+ private com.google.protobuf.RepeatedFieldBuilder<
+ io.prometheus.client.Metrics.LabelPair, io.prometheus.client.Metrics.LabelPair.Builder, io.prometheus.client.Metrics.LabelPairOrBuilder> labelBuilder_;
+
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public java.util.List getLabelList() {
+ if (labelBuilder_ == null) {
+ return java.util.Collections.unmodifiableList(label_);
+ } else {
+ return labelBuilder_.getMessageList();
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public int getLabelCount() {
+ if (labelBuilder_ == null) {
+ return label_.size();
+ } else {
+ return labelBuilder_.getCount();
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public io.prometheus.client.Metrics.LabelPair getLabel(int index) {
+ if (labelBuilder_ == null) {
+ return label_.get(index);
+ } else {
+ return labelBuilder_.getMessage(index);
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public Builder setLabel(
+ int index, io.prometheus.client.Metrics.LabelPair value) {
+ if (labelBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ ensureLabelIsMutable();
+ label_.set(index, value);
+ onChanged();
+ } else {
+ labelBuilder_.setMessage(index, value);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public Builder setLabel(
+ int index, io.prometheus.client.Metrics.LabelPair.Builder builderForValue) {
+ if (labelBuilder_ == null) {
+ ensureLabelIsMutable();
+ label_.set(index, builderForValue.build());
+ onChanged();
+ } else {
+ labelBuilder_.setMessage(index, builderForValue.build());
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public Builder addLabel(io.prometheus.client.Metrics.LabelPair value) {
+ if (labelBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ ensureLabelIsMutable();
+ label_.add(value);
+ onChanged();
+ } else {
+ labelBuilder_.addMessage(value);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public Builder addLabel(
+ int index, io.prometheus.client.Metrics.LabelPair value) {
+ if (labelBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ ensureLabelIsMutable();
+ label_.add(index, value);
+ onChanged();
+ } else {
+ labelBuilder_.addMessage(index, value);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public Builder addLabel(
+ io.prometheus.client.Metrics.LabelPair.Builder builderForValue) {
+ if (labelBuilder_ == null) {
+ ensureLabelIsMutable();
+ label_.add(builderForValue.build());
+ onChanged();
+ } else {
+ labelBuilder_.addMessage(builderForValue.build());
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public Builder addLabel(
+ int index, io.prometheus.client.Metrics.LabelPair.Builder builderForValue) {
+ if (labelBuilder_ == null) {
+ ensureLabelIsMutable();
+ label_.add(index, builderForValue.build());
+ onChanged();
+ } else {
+ labelBuilder_.addMessage(index, builderForValue.build());
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public Builder addAllLabel(
+ java.lang.Iterable extends io.prometheus.client.Metrics.LabelPair> values) {
+ if (labelBuilder_ == null) {
+ ensureLabelIsMutable();
+ com.google.protobuf.AbstractMessageLite.Builder.addAll(
+ values, label_);
+ onChanged();
+ } else {
+ labelBuilder_.addAllMessages(values);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public Builder clearLabel() {
+ if (labelBuilder_ == null) {
+ label_ = java.util.Collections.emptyList();
+ bitField0_ = (bitField0_ & ~0x00000001);
+ onChanged();
+ } else {
+ labelBuilder_.clear();
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public Builder removeLabel(int index) {
+ if (labelBuilder_ == null) {
+ ensureLabelIsMutable();
+ label_.remove(index);
+ onChanged();
+ } else {
+ labelBuilder_.remove(index);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public io.prometheus.client.Metrics.LabelPair.Builder getLabelBuilder(
+ int index) {
+ return getLabelFieldBuilder().getBuilder(index);
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public io.prometheus.client.Metrics.LabelPairOrBuilder getLabelOrBuilder(
+ int index) {
+ if (labelBuilder_ == null) {
+ return label_.get(index); } else {
+ return labelBuilder_.getMessageOrBuilder(index);
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public java.util.List extends io.prometheus.client.Metrics.LabelPairOrBuilder>
+ getLabelOrBuilderList() {
+ if (labelBuilder_ != null) {
+ return labelBuilder_.getMessageOrBuilderList();
+ } else {
+ return java.util.Collections.unmodifiableList(label_);
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public io.prometheus.client.Metrics.LabelPair.Builder addLabelBuilder() {
+ return getLabelFieldBuilder().addBuilder(
+ io.prometheus.client.Metrics.LabelPair.getDefaultInstance());
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public io.prometheus.client.Metrics.LabelPair.Builder addLabelBuilder(
+ int index) {
+ return getLabelFieldBuilder().addBuilder(
+ index, io.prometheus.client.Metrics.LabelPair.getDefaultInstance());
+ }
+ /**
+ * repeated .io.prometheus.client.LabelPair label = 1;
+ */
+ public java.util.List
+ getLabelBuilderList() {
+ return getLabelFieldBuilder().getBuilderList();
+ }
+ private com.google.protobuf.RepeatedFieldBuilder<
+ io.prometheus.client.Metrics.LabelPair, io.prometheus.client.Metrics.LabelPair.Builder, io.prometheus.client.Metrics.LabelPairOrBuilder>
+ getLabelFieldBuilder() {
+ if (labelBuilder_ == null) {
+ labelBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
+ io.prometheus.client.Metrics.LabelPair, io.prometheus.client.Metrics.LabelPair.Builder, io.prometheus.client.Metrics.LabelPairOrBuilder>(
+ label_,
+ ((bitField0_ & 0x00000001) == 0x00000001),
+ getParentForChildren(),
+ isClean());
+ label_ = null;
+ }
+ return labelBuilder_;
+ }
+
+ private io.prometheus.client.Metrics.Gauge gauge_ = io.prometheus.client.Metrics.Gauge.getDefaultInstance();
+ private com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Gauge, io.prometheus.client.Metrics.Gauge.Builder, io.prometheus.client.Metrics.GaugeOrBuilder> gaugeBuilder_;
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ public boolean hasGauge() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ public io.prometheus.client.Metrics.Gauge getGauge() {
+ if (gaugeBuilder_ == null) {
+ return gauge_;
+ } else {
+ return gaugeBuilder_.getMessage();
+ }
+ }
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ public Builder setGauge(io.prometheus.client.Metrics.Gauge value) {
+ if (gaugeBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ gauge_ = value;
+ onChanged();
+ } else {
+ gaugeBuilder_.setMessage(value);
+ }
+ bitField0_ |= 0x00000002;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ public Builder setGauge(
+ io.prometheus.client.Metrics.Gauge.Builder builderForValue) {
+ if (gaugeBuilder_ == null) {
+ gauge_ = builderForValue.build();
+ onChanged();
+ } else {
+ gaugeBuilder_.setMessage(builderForValue.build());
+ }
+ bitField0_ |= 0x00000002;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ public Builder mergeGauge(io.prometheus.client.Metrics.Gauge value) {
+ if (gaugeBuilder_ == null) {
+ if (((bitField0_ & 0x00000002) == 0x00000002) &&
+ gauge_ != io.prometheus.client.Metrics.Gauge.getDefaultInstance()) {
+ gauge_ =
+ io.prometheus.client.Metrics.Gauge.newBuilder(gauge_).mergeFrom(value).buildPartial();
+ } else {
+ gauge_ = value;
+ }
+ onChanged();
+ } else {
+ gaugeBuilder_.mergeFrom(value);
+ }
+ bitField0_ |= 0x00000002;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ public Builder clearGauge() {
+ if (gaugeBuilder_ == null) {
+ gauge_ = io.prometheus.client.Metrics.Gauge.getDefaultInstance();
+ onChanged();
+ } else {
+ gaugeBuilder_.clear();
+ }
+ bitField0_ = (bitField0_ & ~0x00000002);
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ public io.prometheus.client.Metrics.Gauge.Builder getGaugeBuilder() {
+ bitField0_ |= 0x00000002;
+ onChanged();
+ return getGaugeFieldBuilder().getBuilder();
+ }
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ public io.prometheus.client.Metrics.GaugeOrBuilder getGaugeOrBuilder() {
+ if (gaugeBuilder_ != null) {
+ return gaugeBuilder_.getMessageOrBuilder();
+ } else {
+ return gauge_;
+ }
+ }
+ /**
+ * optional .io.prometheus.client.Gauge gauge = 2;
+ */
+ private com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Gauge, io.prometheus.client.Metrics.Gauge.Builder, io.prometheus.client.Metrics.GaugeOrBuilder>
+ getGaugeFieldBuilder() {
+ if (gaugeBuilder_ == null) {
+ gaugeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Gauge, io.prometheus.client.Metrics.Gauge.Builder, io.prometheus.client.Metrics.GaugeOrBuilder>(
+ getGauge(),
+ getParentForChildren(),
+ isClean());
+ gauge_ = null;
+ }
+ return gaugeBuilder_;
+ }
+
+ private io.prometheus.client.Metrics.Counter counter_ = io.prometheus.client.Metrics.Counter.getDefaultInstance();
+ private com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Counter, io.prometheus.client.Metrics.Counter.Builder, io.prometheus.client.Metrics.CounterOrBuilder> counterBuilder_;
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ public boolean hasCounter() {
+ return ((bitField0_ & 0x00000004) == 0x00000004);
+ }
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ public io.prometheus.client.Metrics.Counter getCounter() {
+ if (counterBuilder_ == null) {
+ return counter_;
+ } else {
+ return counterBuilder_.getMessage();
+ }
+ }
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ public Builder setCounter(io.prometheus.client.Metrics.Counter value) {
+ if (counterBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ counter_ = value;
+ onChanged();
+ } else {
+ counterBuilder_.setMessage(value);
+ }
+ bitField0_ |= 0x00000004;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ public Builder setCounter(
+ io.prometheus.client.Metrics.Counter.Builder builderForValue) {
+ if (counterBuilder_ == null) {
+ counter_ = builderForValue.build();
+ onChanged();
+ } else {
+ counterBuilder_.setMessage(builderForValue.build());
+ }
+ bitField0_ |= 0x00000004;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ public Builder mergeCounter(io.prometheus.client.Metrics.Counter value) {
+ if (counterBuilder_ == null) {
+ if (((bitField0_ & 0x00000004) == 0x00000004) &&
+ counter_ != io.prometheus.client.Metrics.Counter.getDefaultInstance()) {
+ counter_ =
+ io.prometheus.client.Metrics.Counter.newBuilder(counter_).mergeFrom(value).buildPartial();
+ } else {
+ counter_ = value;
+ }
+ onChanged();
+ } else {
+ counterBuilder_.mergeFrom(value);
+ }
+ bitField0_ |= 0x00000004;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ public Builder clearCounter() {
+ if (counterBuilder_ == null) {
+ counter_ = io.prometheus.client.Metrics.Counter.getDefaultInstance();
+ onChanged();
+ } else {
+ counterBuilder_.clear();
+ }
+ bitField0_ = (bitField0_ & ~0x00000004);
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ public io.prometheus.client.Metrics.Counter.Builder getCounterBuilder() {
+ bitField0_ |= 0x00000004;
+ onChanged();
+ return getCounterFieldBuilder().getBuilder();
+ }
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ public io.prometheus.client.Metrics.CounterOrBuilder getCounterOrBuilder() {
+ if (counterBuilder_ != null) {
+ return counterBuilder_.getMessageOrBuilder();
+ } else {
+ return counter_;
+ }
+ }
+ /**
+ * optional .io.prometheus.client.Counter counter = 3;
+ */
+ private com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Counter, io.prometheus.client.Metrics.Counter.Builder, io.prometheus.client.Metrics.CounterOrBuilder>
+ getCounterFieldBuilder() {
+ if (counterBuilder_ == null) {
+ counterBuilder_ = new com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Counter, io.prometheus.client.Metrics.Counter.Builder, io.prometheus.client.Metrics.CounterOrBuilder>(
+ getCounter(),
+ getParentForChildren(),
+ isClean());
+ counter_ = null;
+ }
+ return counterBuilder_;
+ }
+
+ private io.prometheus.client.Metrics.Summary summary_ = io.prometheus.client.Metrics.Summary.getDefaultInstance();
+ private com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Summary, io.prometheus.client.Metrics.Summary.Builder, io.prometheus.client.Metrics.SummaryOrBuilder> summaryBuilder_;
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ public boolean hasSummary() {
+ return ((bitField0_ & 0x00000008) == 0x00000008);
+ }
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ public io.prometheus.client.Metrics.Summary getSummary() {
+ if (summaryBuilder_ == null) {
+ return summary_;
+ } else {
+ return summaryBuilder_.getMessage();
+ }
+ }
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ public Builder setSummary(io.prometheus.client.Metrics.Summary value) {
+ if (summaryBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ summary_ = value;
+ onChanged();
+ } else {
+ summaryBuilder_.setMessage(value);
+ }
+ bitField0_ |= 0x00000008;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ public Builder setSummary(
+ io.prometheus.client.Metrics.Summary.Builder builderForValue) {
+ if (summaryBuilder_ == null) {
+ summary_ = builderForValue.build();
+ onChanged();
+ } else {
+ summaryBuilder_.setMessage(builderForValue.build());
+ }
+ bitField0_ |= 0x00000008;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ public Builder mergeSummary(io.prometheus.client.Metrics.Summary value) {
+ if (summaryBuilder_ == null) {
+ if (((bitField0_ & 0x00000008) == 0x00000008) &&
+ summary_ != io.prometheus.client.Metrics.Summary.getDefaultInstance()) {
+ summary_ =
+ io.prometheus.client.Metrics.Summary.newBuilder(summary_).mergeFrom(value).buildPartial();
+ } else {
+ summary_ = value;
+ }
+ onChanged();
+ } else {
+ summaryBuilder_.mergeFrom(value);
+ }
+ bitField0_ |= 0x00000008;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ public Builder clearSummary() {
+ if (summaryBuilder_ == null) {
+ summary_ = io.prometheus.client.Metrics.Summary.getDefaultInstance();
+ onChanged();
+ } else {
+ summaryBuilder_.clear();
+ }
+ bitField0_ = (bitField0_ & ~0x00000008);
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ public io.prometheus.client.Metrics.Summary.Builder getSummaryBuilder() {
+ bitField0_ |= 0x00000008;
+ onChanged();
+ return getSummaryFieldBuilder().getBuilder();
+ }
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ public io.prometheus.client.Metrics.SummaryOrBuilder getSummaryOrBuilder() {
+ if (summaryBuilder_ != null) {
+ return summaryBuilder_.getMessageOrBuilder();
+ } else {
+ return summary_;
+ }
+ }
+ /**
+ * optional .io.prometheus.client.Summary summary = 4;
+ */
+ private com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Summary, io.prometheus.client.Metrics.Summary.Builder, io.prometheus.client.Metrics.SummaryOrBuilder>
+ getSummaryFieldBuilder() {
+ if (summaryBuilder_ == null) {
+ summaryBuilder_ = new com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Summary, io.prometheus.client.Metrics.Summary.Builder, io.prometheus.client.Metrics.SummaryOrBuilder>(
+ getSummary(),
+ getParentForChildren(),
+ isClean());
+ summary_ = null;
+ }
+ return summaryBuilder_;
+ }
+
+ private io.prometheus.client.Metrics.Untyped untyped_ = io.prometheus.client.Metrics.Untyped.getDefaultInstance();
+ private com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Untyped, io.prometheus.client.Metrics.Untyped.Builder, io.prometheus.client.Metrics.UntypedOrBuilder> untypedBuilder_;
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ public boolean hasUntyped() {
+ return ((bitField0_ & 0x00000010) == 0x00000010);
+ }
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ public io.prometheus.client.Metrics.Untyped getUntyped() {
+ if (untypedBuilder_ == null) {
+ return untyped_;
+ } else {
+ return untypedBuilder_.getMessage();
+ }
+ }
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ public Builder setUntyped(io.prometheus.client.Metrics.Untyped value) {
+ if (untypedBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ untyped_ = value;
+ onChanged();
+ } else {
+ untypedBuilder_.setMessage(value);
+ }
+ bitField0_ |= 0x00000010;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ public Builder setUntyped(
+ io.prometheus.client.Metrics.Untyped.Builder builderForValue) {
+ if (untypedBuilder_ == null) {
+ untyped_ = builderForValue.build();
+ onChanged();
+ } else {
+ untypedBuilder_.setMessage(builderForValue.build());
+ }
+ bitField0_ |= 0x00000010;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ public Builder mergeUntyped(io.prometheus.client.Metrics.Untyped value) {
+ if (untypedBuilder_ == null) {
+ if (((bitField0_ & 0x00000010) == 0x00000010) &&
+ untyped_ != io.prometheus.client.Metrics.Untyped.getDefaultInstance()) {
+ untyped_ =
+ io.prometheus.client.Metrics.Untyped.newBuilder(untyped_).mergeFrom(value).buildPartial();
+ } else {
+ untyped_ = value;
+ }
+ onChanged();
+ } else {
+ untypedBuilder_.mergeFrom(value);
+ }
+ bitField0_ |= 0x00000010;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ public Builder clearUntyped() {
+ if (untypedBuilder_ == null) {
+ untyped_ = io.prometheus.client.Metrics.Untyped.getDefaultInstance();
+ onChanged();
+ } else {
+ untypedBuilder_.clear();
+ }
+ bitField0_ = (bitField0_ & ~0x00000010);
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ public io.prometheus.client.Metrics.Untyped.Builder getUntypedBuilder() {
+ bitField0_ |= 0x00000010;
+ onChanged();
+ return getUntypedFieldBuilder().getBuilder();
+ }
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ public io.prometheus.client.Metrics.UntypedOrBuilder getUntypedOrBuilder() {
+ if (untypedBuilder_ != null) {
+ return untypedBuilder_.getMessageOrBuilder();
+ } else {
+ return untyped_;
+ }
+ }
+ /**
+ * optional .io.prometheus.client.Untyped untyped = 5;
+ */
+ private com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Untyped, io.prometheus.client.Metrics.Untyped.Builder, io.prometheus.client.Metrics.UntypedOrBuilder>
+ getUntypedFieldBuilder() {
+ if (untypedBuilder_ == null) {
+ untypedBuilder_ = new com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Untyped, io.prometheus.client.Metrics.Untyped.Builder, io.prometheus.client.Metrics.UntypedOrBuilder>(
+ getUntyped(),
+ getParentForChildren(),
+ isClean());
+ untyped_ = null;
+ }
+ return untypedBuilder_;
+ }
+
+ private io.prometheus.client.Metrics.Histogram histogram_ = io.prometheus.client.Metrics.Histogram.getDefaultInstance();
+ private com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Histogram, io.prometheus.client.Metrics.Histogram.Builder, io.prometheus.client.Metrics.HistogramOrBuilder> histogramBuilder_;
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ public boolean hasHistogram() {
+ return ((bitField0_ & 0x00000020) == 0x00000020);
+ }
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ public io.prometheus.client.Metrics.Histogram getHistogram() {
+ if (histogramBuilder_ == null) {
+ return histogram_;
+ } else {
+ return histogramBuilder_.getMessage();
+ }
+ }
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ public Builder setHistogram(io.prometheus.client.Metrics.Histogram value) {
+ if (histogramBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ histogram_ = value;
+ onChanged();
+ } else {
+ histogramBuilder_.setMessage(value);
+ }
+ bitField0_ |= 0x00000020;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ public Builder setHistogram(
+ io.prometheus.client.Metrics.Histogram.Builder builderForValue) {
+ if (histogramBuilder_ == null) {
+ histogram_ = builderForValue.build();
+ onChanged();
+ } else {
+ histogramBuilder_.setMessage(builderForValue.build());
+ }
+ bitField0_ |= 0x00000020;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ public Builder mergeHistogram(io.prometheus.client.Metrics.Histogram value) {
+ if (histogramBuilder_ == null) {
+ if (((bitField0_ & 0x00000020) == 0x00000020) &&
+ histogram_ != io.prometheus.client.Metrics.Histogram.getDefaultInstance()) {
+ histogram_ =
+ io.prometheus.client.Metrics.Histogram.newBuilder(histogram_).mergeFrom(value).buildPartial();
+ } else {
+ histogram_ = value;
+ }
+ onChanged();
+ } else {
+ histogramBuilder_.mergeFrom(value);
+ }
+ bitField0_ |= 0x00000020;
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ public Builder clearHistogram() {
+ if (histogramBuilder_ == null) {
+ histogram_ = io.prometheus.client.Metrics.Histogram.getDefaultInstance();
+ onChanged();
+ } else {
+ histogramBuilder_.clear();
+ }
+ bitField0_ = (bitField0_ & ~0x00000020);
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ public io.prometheus.client.Metrics.Histogram.Builder getHistogramBuilder() {
+ bitField0_ |= 0x00000020;
+ onChanged();
+ return getHistogramFieldBuilder().getBuilder();
+ }
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ public io.prometheus.client.Metrics.HistogramOrBuilder getHistogramOrBuilder() {
+ if (histogramBuilder_ != null) {
+ return histogramBuilder_.getMessageOrBuilder();
+ } else {
+ return histogram_;
+ }
+ }
+ /**
+ * optional .io.prometheus.client.Histogram histogram = 7;
+ */
+ private com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Histogram, io.prometheus.client.Metrics.Histogram.Builder, io.prometheus.client.Metrics.HistogramOrBuilder>
+ getHistogramFieldBuilder() {
+ if (histogramBuilder_ == null) {
+ histogramBuilder_ = new com.google.protobuf.SingleFieldBuilder<
+ io.prometheus.client.Metrics.Histogram, io.prometheus.client.Metrics.Histogram.Builder, io.prometheus.client.Metrics.HistogramOrBuilder>(
+ getHistogram(),
+ getParentForChildren(),
+ isClean());
+ histogram_ = null;
+ }
+ return histogramBuilder_;
+ }
+
+ private long timestampMs_ ;
+ /**
+ * optional int64 timestamp_ms = 6;
+ */
+ public boolean hasTimestampMs() {
+ return ((bitField0_ & 0x00000040) == 0x00000040);
+ }
+ /**
+ * optional int64 timestamp_ms = 6;
+ */
+ public long getTimestampMs() {
+ return timestampMs_;
+ }
+ /**
+ * optional int64 timestamp_ms = 6;
+ */
+ public Builder setTimestampMs(long value) {
+ bitField0_ |= 0x00000040;
+ timestampMs_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional int64 timestamp_ms = 6;
+ */
+ public Builder clearTimestampMs() {
+ bitField0_ = (bitField0_ & ~0x00000040);
+ timestampMs_ = 0L;
+ onChanged();
+ return this;
+ }
+
+ // @@protoc_insertion_point(builder_scope:io.prometheus.client.Metric)
+ }
+
+ static {
+ defaultInstance = new Metric(true);
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.Metric)
+ }
+
+ public interface MetricFamilyOrBuilder extends
+ // @@protoc_insertion_point(interface_extends:io.prometheus.client.MetricFamily)
+ com.google.protobuf.MessageOrBuilder {
+
+ /**
+ * optional string name = 1;
+ */
+ boolean hasName();
+ /**
+ * optional string name = 1;
+ */
+ java.lang.String getName();
+ /**
+ * optional string name = 1;
+ */
+ com.google.protobuf.ByteString
+ getNameBytes();
+
+ /**
+ * optional string help = 2;
+ */
+ boolean hasHelp();
+ /**
+ * optional string help = 2;
+ */
+ java.lang.String getHelp();
+ /**
+ * optional string help = 2;
+ */
+ com.google.protobuf.ByteString
+ getHelpBytes();
+
+ /**
+ * optional .io.prometheus.client.MetricType type = 3;
+ */
+ boolean hasType();
+ /**
+ * optional .io.prometheus.client.MetricType type = 3;
+ */
+ io.prometheus.client.Metrics.MetricType getType();
+
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ java.util.List
+ getMetricList();
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ io.prometheus.client.Metrics.Metric getMetric(int index);
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ int getMetricCount();
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ java.util.List extends io.prometheus.client.Metrics.MetricOrBuilder>
+ getMetricOrBuilderList();
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ io.prometheus.client.Metrics.MetricOrBuilder getMetricOrBuilder(
+ int index);
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.MetricFamily}
+ */
+ public static final class MetricFamily extends
+ com.google.protobuf.GeneratedMessage implements
+ // @@protoc_insertion_point(message_implements:io.prometheus.client.MetricFamily)
+ MetricFamilyOrBuilder {
+ // Use MetricFamily.newBuilder() to construct.
+ private MetricFamily(com.google.protobuf.GeneratedMessage.Builder> builder) {
+ super(builder);
+ this.unknownFields = builder.getUnknownFields();
+ }
+ private MetricFamily(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+ private static final MetricFamily defaultInstance;
+ public static MetricFamily getDefaultInstance() {
+ return defaultInstance;
+ }
+
+ public MetricFamily getDefaultInstanceForType() {
+ return defaultInstance;
+ }
+
+ private final com.google.protobuf.UnknownFieldSet unknownFields;
+ @java.lang.Override
+ public final com.google.protobuf.UnknownFieldSet
+ getUnknownFields() {
+ return this.unknownFields;
+ }
+ private MetricFamily(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ initFields();
+ int mutable_bitField0_ = 0;
+ com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+ com.google.protobuf.UnknownFieldSet.newBuilder();
+ try {
+ boolean done = false;
+ while (!done) {
+ int tag = input.readTag();
+ switch (tag) {
+ case 0:
+ done = true;
+ break;
+ default: {
+ if (!parseUnknownField(input, unknownFields,
+ extensionRegistry, tag)) {
+ done = true;
+ }
+ break;
+ }
+ case 10: {
+ com.google.protobuf.ByteString bs = input.readBytes();
+ bitField0_ |= 0x00000001;
+ name_ = bs;
+ break;
+ }
+ case 18: {
+ com.google.protobuf.ByteString bs = input.readBytes();
+ bitField0_ |= 0x00000002;
+ help_ = bs;
+ break;
+ }
+ case 24: {
+ int rawValue = input.readEnum();
+ io.prometheus.client.Metrics.MetricType value = io.prometheus.client.Metrics.MetricType.valueOf(rawValue);
+ if (value == null) {
+ unknownFields.mergeVarintField(3, rawValue);
+ } else {
+ bitField0_ |= 0x00000004;
+ type_ = value;
+ }
+ break;
+ }
+ case 34: {
+ if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) {
+ metric_ = new java.util.ArrayList();
+ mutable_bitField0_ |= 0x00000008;
+ }
+ metric_.add(input.readMessage(io.prometheus.client.Metrics.Metric.PARSER, extensionRegistry));
+ break;
+ }
+ }
+ }
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ throw e.setUnfinishedMessage(this);
+ } catch (java.io.IOException e) {
+ throw new com.google.protobuf.InvalidProtocolBufferException(
+ e.getMessage()).setUnfinishedMessage(this);
+ } finally {
+ if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) {
+ metric_ = java.util.Collections.unmodifiableList(metric_);
+ }
+ this.unknownFields = unknownFields.build();
+ makeExtensionsImmutable();
+ }
+ }
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_MetricFamily_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_MetricFamily_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.MetricFamily.class, io.prometheus.client.Metrics.MetricFamily.Builder.class);
+ }
+
+ public static com.google.protobuf.Parser PARSER =
+ new com.google.protobuf.AbstractParser() {
+ public MetricFamily parsePartialFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return new MetricFamily(input, extensionRegistry);
+ }
+ };
+
+ @java.lang.Override
+ public com.google.protobuf.Parser getParserForType() {
+ return PARSER;
+ }
+
+ private int bitField0_;
+ public static final int NAME_FIELD_NUMBER = 1;
+ private java.lang.Object name_;
+ /**
+ * optional string name = 1;
+ */
+ public boolean hasName() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional string name = 1;
+ */
+ public java.lang.String getName() {
+ java.lang.Object ref = name_;
+ if (ref instanceof java.lang.String) {
+ return (java.lang.String) ref;
+ } else {
+ com.google.protobuf.ByteString bs =
+ (com.google.protobuf.ByteString) ref;
+ java.lang.String s = bs.toStringUtf8();
+ if (bs.isValidUtf8()) {
+ name_ = s;
+ }
+ return s;
+ }
+ }
+ /**
+ * optional string name = 1;
+ */
+ public com.google.protobuf.ByteString
+ getNameBytes() {
+ java.lang.Object ref = name_;
+ if (ref instanceof java.lang.String) {
+ com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString.copyFromUtf8(
+ (java.lang.String) ref);
+ name_ = b;
+ return b;
+ } else {
+ return (com.google.protobuf.ByteString) ref;
+ }
+ }
+
+ public static final int HELP_FIELD_NUMBER = 2;
+ private java.lang.Object help_;
+ /**
+ * optional string help = 2;
+ */
+ public boolean hasHelp() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional string help = 2;
+ */
+ public java.lang.String getHelp() {
+ java.lang.Object ref = help_;
+ if (ref instanceof java.lang.String) {
+ return (java.lang.String) ref;
+ } else {
+ com.google.protobuf.ByteString bs =
+ (com.google.protobuf.ByteString) ref;
+ java.lang.String s = bs.toStringUtf8();
+ if (bs.isValidUtf8()) {
+ help_ = s;
+ }
+ return s;
+ }
+ }
+ /**
+ * optional string help = 2;
+ */
+ public com.google.protobuf.ByteString
+ getHelpBytes() {
+ java.lang.Object ref = help_;
+ if (ref instanceof java.lang.String) {
+ com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString.copyFromUtf8(
+ (java.lang.String) ref);
+ help_ = b;
+ return b;
+ } else {
+ return (com.google.protobuf.ByteString) ref;
+ }
+ }
+
+ public static final int TYPE_FIELD_NUMBER = 3;
+ private io.prometheus.client.Metrics.MetricType type_;
+ /**
+ * optional .io.prometheus.client.MetricType type = 3;
+ */
+ public boolean hasType() {
+ return ((bitField0_ & 0x00000004) == 0x00000004);
+ }
+ /**
+ * optional .io.prometheus.client.MetricType type = 3;
+ */
+ public io.prometheus.client.Metrics.MetricType getType() {
+ return type_;
+ }
+
+ public static final int METRIC_FIELD_NUMBER = 4;
+ private java.util.List metric_;
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public java.util.List getMetricList() {
+ return metric_;
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public java.util.List extends io.prometheus.client.Metrics.MetricOrBuilder>
+ getMetricOrBuilderList() {
+ return metric_;
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public int getMetricCount() {
+ return metric_.size();
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public io.prometheus.client.Metrics.Metric getMetric(int index) {
+ return metric_.get(index);
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public io.prometheus.client.Metrics.MetricOrBuilder getMetricOrBuilder(
+ int index) {
+ return metric_.get(index);
+ }
+
+ private void initFields() {
+ name_ = "";
+ help_ = "";
+ type_ = io.prometheus.client.Metrics.MetricType.COUNTER;
+ metric_ = java.util.Collections.emptyList();
+ }
+ private byte memoizedIsInitialized = -1;
+ public final boolean isInitialized() {
+ byte isInitialized = memoizedIsInitialized;
+ if (isInitialized == 1) return true;
+ if (isInitialized == 0) return false;
+
+ memoizedIsInitialized = 1;
+ return true;
+ }
+
+ public void writeTo(com.google.protobuf.CodedOutputStream output)
+ throws java.io.IOException {
+ getSerializedSize();
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ output.writeBytes(1, getNameBytes());
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ output.writeBytes(2, getHelpBytes());
+ }
+ if (((bitField0_ & 0x00000004) == 0x00000004)) {
+ output.writeEnum(3, type_.getNumber());
+ }
+ for (int i = 0; i < metric_.size(); i++) {
+ output.writeMessage(4, metric_.get(i));
+ }
+ getUnknownFields().writeTo(output);
+ }
+
+ private int memoizedSerializedSize = -1;
+ public int getSerializedSize() {
+ int size = memoizedSerializedSize;
+ if (size != -1) return size;
+
+ size = 0;
+ if (((bitField0_ & 0x00000001) == 0x00000001)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBytesSize(1, getNameBytes());
+ }
+ if (((bitField0_ & 0x00000002) == 0x00000002)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeBytesSize(2, getHelpBytes());
+ }
+ if (((bitField0_ & 0x00000004) == 0x00000004)) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeEnumSize(3, type_.getNumber());
+ }
+ for (int i = 0; i < metric_.size(); i++) {
+ size += com.google.protobuf.CodedOutputStream
+ .computeMessageSize(4, metric_.get(i));
+ }
+ size += getUnknownFields().getSerializedSize();
+ memoizedSerializedSize = size;
+ return size;
+ }
+
+ private static final long serialVersionUID = 0L;
+ @java.lang.Override
+ protected java.lang.Object writeReplace()
+ throws java.io.ObjectStreamException {
+ return super.writeReplace();
+ }
+
+ public static io.prometheus.client.Metrics.MetricFamily parseFrom(
+ com.google.protobuf.ByteString data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.MetricFamily parseFrom(
+ com.google.protobuf.ByteString data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.MetricFamily parseFrom(byte[] data)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data);
+ }
+ public static io.prometheus.client.Metrics.MetricFamily parseFrom(
+ byte[] data,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws com.google.protobuf.InvalidProtocolBufferException {
+ return PARSER.parseFrom(data, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.MetricFamily parseFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.MetricFamily parseFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.MetricFamily parseDelimitedFrom(java.io.InputStream input)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input);
+ }
+ public static io.prometheus.client.Metrics.MetricFamily parseDelimitedFrom(
+ java.io.InputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseDelimitedFrom(input, extensionRegistry);
+ }
+ public static io.prometheus.client.Metrics.MetricFamily parseFrom(
+ com.google.protobuf.CodedInputStream input)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input);
+ }
+ public static io.prometheus.client.Metrics.MetricFamily parseFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ return PARSER.parseFrom(input, extensionRegistry);
+ }
+
+ public static Builder newBuilder() { return Builder.create(); }
+ public Builder newBuilderForType() { return newBuilder(); }
+ public static Builder newBuilder(io.prometheus.client.Metrics.MetricFamily prototype) {
+ return newBuilder().mergeFrom(prototype);
+ }
+ public Builder toBuilder() { return newBuilder(this); }
+
+ @java.lang.Override
+ protected Builder newBuilderForType(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ Builder builder = new Builder(parent);
+ return builder;
+ }
+ /**
+ * Protobuf type {@code io.prometheus.client.MetricFamily}
+ */
+ public static final class Builder extends
+ com.google.protobuf.GeneratedMessage.Builder implements
+ // @@protoc_insertion_point(builder_implements:io.prometheus.client.MetricFamily)
+ io.prometheus.client.Metrics.MetricFamilyOrBuilder {
+ public static final com.google.protobuf.Descriptors.Descriptor
+ getDescriptor() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_MetricFamily_descriptor;
+ }
+
+ protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internalGetFieldAccessorTable() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_MetricFamily_fieldAccessorTable
+ .ensureFieldAccessorsInitialized(
+ io.prometheus.client.Metrics.MetricFamily.class, io.prometheus.client.Metrics.MetricFamily.Builder.class);
+ }
+
+ // Construct using io.prometheus.client.Metrics.MetricFamily.newBuilder()
+ private Builder() {
+ maybeForceBuilderInitialization();
+ }
+
+ private Builder(
+ com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+ super(parent);
+ maybeForceBuilderInitialization();
+ }
+ private void maybeForceBuilderInitialization() {
+ if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+ getMetricFieldBuilder();
+ }
+ }
+ private static Builder create() {
+ return new Builder();
+ }
+
+ public Builder clear() {
+ super.clear();
+ name_ = "";
+ bitField0_ = (bitField0_ & ~0x00000001);
+ help_ = "";
+ bitField0_ = (bitField0_ & ~0x00000002);
+ type_ = io.prometheus.client.Metrics.MetricType.COUNTER;
+ bitField0_ = (bitField0_ & ~0x00000004);
+ if (metricBuilder_ == null) {
+ metric_ = java.util.Collections.emptyList();
+ bitField0_ = (bitField0_ & ~0x00000008);
+ } else {
+ metricBuilder_.clear();
+ }
+ return this;
+ }
+
+ public Builder clone() {
+ return create().mergeFrom(buildPartial());
+ }
+
+ public com.google.protobuf.Descriptors.Descriptor
+ getDescriptorForType() {
+ return io.prometheus.client.Metrics.internal_static_io_prometheus_client_MetricFamily_descriptor;
+ }
+
+ public io.prometheus.client.Metrics.MetricFamily getDefaultInstanceForType() {
+ return io.prometheus.client.Metrics.MetricFamily.getDefaultInstance();
+ }
+
+ public io.prometheus.client.Metrics.MetricFamily build() {
+ io.prometheus.client.Metrics.MetricFamily result = buildPartial();
+ if (!result.isInitialized()) {
+ throw newUninitializedMessageException(result);
+ }
+ return result;
+ }
+
+ public io.prometheus.client.Metrics.MetricFamily buildPartial() {
+ io.prometheus.client.Metrics.MetricFamily result = new io.prometheus.client.Metrics.MetricFamily(this);
+ int from_bitField0_ = bitField0_;
+ int to_bitField0_ = 0;
+ if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+ to_bitField0_ |= 0x00000001;
+ }
+ result.name_ = name_;
+ if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
+ to_bitField0_ |= 0x00000002;
+ }
+ result.help_ = help_;
+ if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
+ to_bitField0_ |= 0x00000004;
+ }
+ result.type_ = type_;
+ if (metricBuilder_ == null) {
+ if (((bitField0_ & 0x00000008) == 0x00000008)) {
+ metric_ = java.util.Collections.unmodifiableList(metric_);
+ bitField0_ = (bitField0_ & ~0x00000008);
+ }
+ result.metric_ = metric_;
+ } else {
+ result.metric_ = metricBuilder_.build();
+ }
+ result.bitField0_ = to_bitField0_;
+ onBuilt();
+ return result;
+ }
+
+ public Builder mergeFrom(com.google.protobuf.Message other) {
+ if (other instanceof io.prometheus.client.Metrics.MetricFamily) {
+ return mergeFrom((io.prometheus.client.Metrics.MetricFamily)other);
+ } else {
+ super.mergeFrom(other);
+ return this;
+ }
+ }
+
+ public Builder mergeFrom(io.prometheus.client.Metrics.MetricFamily other) {
+ if (other == io.prometheus.client.Metrics.MetricFamily.getDefaultInstance()) return this;
+ if (other.hasName()) {
+ bitField0_ |= 0x00000001;
+ name_ = other.name_;
+ onChanged();
+ }
+ if (other.hasHelp()) {
+ bitField0_ |= 0x00000002;
+ help_ = other.help_;
+ onChanged();
+ }
+ if (other.hasType()) {
+ setType(other.getType());
+ }
+ if (metricBuilder_ == null) {
+ if (!other.metric_.isEmpty()) {
+ if (metric_.isEmpty()) {
+ metric_ = other.metric_;
+ bitField0_ = (bitField0_ & ~0x00000008);
+ } else {
+ ensureMetricIsMutable();
+ metric_.addAll(other.metric_);
+ }
+ onChanged();
+ }
+ } else {
+ if (!other.metric_.isEmpty()) {
+ if (metricBuilder_.isEmpty()) {
+ metricBuilder_.dispose();
+ metricBuilder_ = null;
+ metric_ = other.metric_;
+ bitField0_ = (bitField0_ & ~0x00000008);
+ metricBuilder_ =
+ com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
+ getMetricFieldBuilder() : null;
+ } else {
+ metricBuilder_.addAllMessages(other.metric_);
+ }
+ }
+ }
+ this.mergeUnknownFields(other.getUnknownFields());
+ return this;
+ }
+
+ public final boolean isInitialized() {
+ return true;
+ }
+
+ public Builder mergeFrom(
+ com.google.protobuf.CodedInputStream input,
+ com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+ throws java.io.IOException {
+ io.prometheus.client.Metrics.MetricFamily parsedMessage = null;
+ try {
+ parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+ } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+ parsedMessage = (io.prometheus.client.Metrics.MetricFamily) e.getUnfinishedMessage();
+ throw e;
+ } finally {
+ if (parsedMessage != null) {
+ mergeFrom(parsedMessage);
+ }
+ }
+ return this;
+ }
+ private int bitField0_;
+
+ private java.lang.Object name_ = "";
+ /**
+ * optional string name = 1;
+ */
+ public boolean hasName() {
+ return ((bitField0_ & 0x00000001) == 0x00000001);
+ }
+ /**
+ * optional string name = 1;
+ */
+ public java.lang.String getName() {
+ java.lang.Object ref = name_;
+ if (!(ref instanceof java.lang.String)) {
+ com.google.protobuf.ByteString bs =
+ (com.google.protobuf.ByteString) ref;
+ java.lang.String s = bs.toStringUtf8();
+ if (bs.isValidUtf8()) {
+ name_ = s;
+ }
+ return s;
+ } else {
+ return (java.lang.String) ref;
+ }
+ }
+ /**
+ * optional string name = 1;
+ */
+ public com.google.protobuf.ByteString
+ getNameBytes() {
+ java.lang.Object ref = name_;
+ if (ref instanceof String) {
+ com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString.copyFromUtf8(
+ (java.lang.String) ref);
+ name_ = b;
+ return b;
+ } else {
+ return (com.google.protobuf.ByteString) ref;
+ }
+ }
+ /**
+ * optional string name = 1;
+ */
+ public Builder setName(
+ java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000001;
+ name_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional string name = 1;
+ */
+ public Builder clearName() {
+ bitField0_ = (bitField0_ & ~0x00000001);
+ name_ = getDefaultInstance().getName();
+ onChanged();
+ return this;
+ }
+ /**
+ * optional string name = 1;
+ */
+ public Builder setNameBytes(
+ com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000001;
+ name_ = value;
+ onChanged();
+ return this;
+ }
+
+ private java.lang.Object help_ = "";
+ /**
+ * optional string help = 2;
+ */
+ public boolean hasHelp() {
+ return ((bitField0_ & 0x00000002) == 0x00000002);
+ }
+ /**
+ * optional string help = 2;
+ */
+ public java.lang.String getHelp() {
+ java.lang.Object ref = help_;
+ if (!(ref instanceof java.lang.String)) {
+ com.google.protobuf.ByteString bs =
+ (com.google.protobuf.ByteString) ref;
+ java.lang.String s = bs.toStringUtf8();
+ if (bs.isValidUtf8()) {
+ help_ = s;
+ }
+ return s;
+ } else {
+ return (java.lang.String) ref;
+ }
+ }
+ /**
+ * optional string help = 2;
+ */
+ public com.google.protobuf.ByteString
+ getHelpBytes() {
+ java.lang.Object ref = help_;
+ if (ref instanceof String) {
+ com.google.protobuf.ByteString b =
+ com.google.protobuf.ByteString.copyFromUtf8(
+ (java.lang.String) ref);
+ help_ = b;
+ return b;
+ } else {
+ return (com.google.protobuf.ByteString) ref;
+ }
+ }
+ /**
+ * optional string help = 2;
+ */
+ public Builder setHelp(
+ java.lang.String value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000002;
+ help_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional string help = 2;
+ */
+ public Builder clearHelp() {
+ bitField0_ = (bitField0_ & ~0x00000002);
+ help_ = getDefaultInstance().getHelp();
+ onChanged();
+ return this;
+ }
+ /**
+ * optional string help = 2;
+ */
+ public Builder setHelpBytes(
+ com.google.protobuf.ByteString value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000002;
+ help_ = value;
+ onChanged();
+ return this;
+ }
+
+ private io.prometheus.client.Metrics.MetricType type_ = io.prometheus.client.Metrics.MetricType.COUNTER;
+ /**
+ * optional .io.prometheus.client.MetricType type = 3;
+ */
+ public boolean hasType() {
+ return ((bitField0_ & 0x00000004) == 0x00000004);
+ }
+ /**
+ * optional .io.prometheus.client.MetricType type = 3;
+ */
+ public io.prometheus.client.Metrics.MetricType getType() {
+ return type_;
+ }
+ /**
+ * optional .io.prometheus.client.MetricType type = 3;
+ */
+ public Builder setType(io.prometheus.client.Metrics.MetricType value) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ bitField0_ |= 0x00000004;
+ type_ = value;
+ onChanged();
+ return this;
+ }
+ /**
+ * optional .io.prometheus.client.MetricType type = 3;
+ */
+ public Builder clearType() {
+ bitField0_ = (bitField0_ & ~0x00000004);
+ type_ = io.prometheus.client.Metrics.MetricType.COUNTER;
+ onChanged();
+ return this;
+ }
+
+ private java.util.List metric_ =
+ java.util.Collections.emptyList();
+ private void ensureMetricIsMutable() {
+ if (!((bitField0_ & 0x00000008) == 0x00000008)) {
+ metric_ = new java.util.ArrayList(metric_);
+ bitField0_ |= 0x00000008;
+ }
+ }
+
+ private com.google.protobuf.RepeatedFieldBuilder<
+ io.prometheus.client.Metrics.Metric, io.prometheus.client.Metrics.Metric.Builder, io.prometheus.client.Metrics.MetricOrBuilder> metricBuilder_;
+
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public java.util.List getMetricList() {
+ if (metricBuilder_ == null) {
+ return java.util.Collections.unmodifiableList(metric_);
+ } else {
+ return metricBuilder_.getMessageList();
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public int getMetricCount() {
+ if (metricBuilder_ == null) {
+ return metric_.size();
+ } else {
+ return metricBuilder_.getCount();
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public io.prometheus.client.Metrics.Metric getMetric(int index) {
+ if (metricBuilder_ == null) {
+ return metric_.get(index);
+ } else {
+ return metricBuilder_.getMessage(index);
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public Builder setMetric(
+ int index, io.prometheus.client.Metrics.Metric value) {
+ if (metricBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ ensureMetricIsMutable();
+ metric_.set(index, value);
+ onChanged();
+ } else {
+ metricBuilder_.setMessage(index, value);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public Builder setMetric(
+ int index, io.prometheus.client.Metrics.Metric.Builder builderForValue) {
+ if (metricBuilder_ == null) {
+ ensureMetricIsMutable();
+ metric_.set(index, builderForValue.build());
+ onChanged();
+ } else {
+ metricBuilder_.setMessage(index, builderForValue.build());
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public Builder addMetric(io.prometheus.client.Metrics.Metric value) {
+ if (metricBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ ensureMetricIsMutable();
+ metric_.add(value);
+ onChanged();
+ } else {
+ metricBuilder_.addMessage(value);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public Builder addMetric(
+ int index, io.prometheus.client.Metrics.Metric value) {
+ if (metricBuilder_ == null) {
+ if (value == null) {
+ throw new NullPointerException();
+ }
+ ensureMetricIsMutable();
+ metric_.add(index, value);
+ onChanged();
+ } else {
+ metricBuilder_.addMessage(index, value);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public Builder addMetric(
+ io.prometheus.client.Metrics.Metric.Builder builderForValue) {
+ if (metricBuilder_ == null) {
+ ensureMetricIsMutable();
+ metric_.add(builderForValue.build());
+ onChanged();
+ } else {
+ metricBuilder_.addMessage(builderForValue.build());
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public Builder addMetric(
+ int index, io.prometheus.client.Metrics.Metric.Builder builderForValue) {
+ if (metricBuilder_ == null) {
+ ensureMetricIsMutable();
+ metric_.add(index, builderForValue.build());
+ onChanged();
+ } else {
+ metricBuilder_.addMessage(index, builderForValue.build());
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public Builder addAllMetric(
+ java.lang.Iterable extends io.prometheus.client.Metrics.Metric> values) {
+ if (metricBuilder_ == null) {
+ ensureMetricIsMutable();
+ com.google.protobuf.AbstractMessageLite.Builder.addAll(
+ values, metric_);
+ onChanged();
+ } else {
+ metricBuilder_.addAllMessages(values);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public Builder clearMetric() {
+ if (metricBuilder_ == null) {
+ metric_ = java.util.Collections.emptyList();
+ bitField0_ = (bitField0_ & ~0x00000008);
+ onChanged();
+ } else {
+ metricBuilder_.clear();
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public Builder removeMetric(int index) {
+ if (metricBuilder_ == null) {
+ ensureMetricIsMutable();
+ metric_.remove(index);
+ onChanged();
+ } else {
+ metricBuilder_.remove(index);
+ }
+ return this;
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public io.prometheus.client.Metrics.Metric.Builder getMetricBuilder(
+ int index) {
+ return getMetricFieldBuilder().getBuilder(index);
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public io.prometheus.client.Metrics.MetricOrBuilder getMetricOrBuilder(
+ int index) {
+ if (metricBuilder_ == null) {
+ return metric_.get(index); } else {
+ return metricBuilder_.getMessageOrBuilder(index);
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public java.util.List extends io.prometheus.client.Metrics.MetricOrBuilder>
+ getMetricOrBuilderList() {
+ if (metricBuilder_ != null) {
+ return metricBuilder_.getMessageOrBuilderList();
+ } else {
+ return java.util.Collections.unmodifiableList(metric_);
+ }
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public io.prometheus.client.Metrics.Metric.Builder addMetricBuilder() {
+ return getMetricFieldBuilder().addBuilder(
+ io.prometheus.client.Metrics.Metric.getDefaultInstance());
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public io.prometheus.client.Metrics.Metric.Builder addMetricBuilder(
+ int index) {
+ return getMetricFieldBuilder().addBuilder(
+ index, io.prometheus.client.Metrics.Metric.getDefaultInstance());
+ }
+ /**
+ * repeated .io.prometheus.client.Metric metric = 4;
+ */
+ public java.util.List
+ getMetricBuilderList() {
+ return getMetricFieldBuilder().getBuilderList();
+ }
+ private com.google.protobuf.RepeatedFieldBuilder<
+ io.prometheus.client.Metrics.Metric, io.prometheus.client.Metrics.Metric.Builder, io.prometheus.client.Metrics.MetricOrBuilder>
+ getMetricFieldBuilder() {
+ if (metricBuilder_ == null) {
+ metricBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
+ io.prometheus.client.Metrics.Metric, io.prometheus.client.Metrics.Metric.Builder, io.prometheus.client.Metrics.MetricOrBuilder>(
+ metric_,
+ ((bitField0_ & 0x00000008) == 0x00000008),
+ getParentForChildren(),
+ isClean());
+ metric_ = null;
+ }
+ return metricBuilder_;
+ }
+
+ // @@protoc_insertion_point(builder_scope:io.prometheus.client.MetricFamily)
+ }
+
+ static {
+ defaultInstance = new MetricFamily(true);
+ defaultInstance.initFields();
+ }
+
+ // @@protoc_insertion_point(class_scope:io.prometheus.client.MetricFamily)
+ }
+
+ private static final com.google.protobuf.Descriptors.Descriptor
+ internal_static_io_prometheus_client_LabelPair_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_io_prometheus_client_LabelPair_fieldAccessorTable;
+ private static final com.google.protobuf.Descriptors.Descriptor
+ internal_static_io_prometheus_client_Gauge_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_io_prometheus_client_Gauge_fieldAccessorTable;
+ private static final com.google.protobuf.Descriptors.Descriptor
+ internal_static_io_prometheus_client_Counter_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_io_prometheus_client_Counter_fieldAccessorTable;
+ private static final com.google.protobuf.Descriptors.Descriptor
+ internal_static_io_prometheus_client_Quantile_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_io_prometheus_client_Quantile_fieldAccessorTable;
+ private static final com.google.protobuf.Descriptors.Descriptor
+ internal_static_io_prometheus_client_Summary_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_io_prometheus_client_Summary_fieldAccessorTable;
+ private static final com.google.protobuf.Descriptors.Descriptor
+ internal_static_io_prometheus_client_Untyped_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_io_prometheus_client_Untyped_fieldAccessorTable;
+ private static final com.google.protobuf.Descriptors.Descriptor
+ internal_static_io_prometheus_client_Histogram_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_io_prometheus_client_Histogram_fieldAccessorTable;
+ private static final com.google.protobuf.Descriptors.Descriptor
+ internal_static_io_prometheus_client_Bucket_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_io_prometheus_client_Bucket_fieldAccessorTable;
+ private static final com.google.protobuf.Descriptors.Descriptor
+ internal_static_io_prometheus_client_Metric_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_io_prometheus_client_Metric_fieldAccessorTable;
+ private static final com.google.protobuf.Descriptors.Descriptor
+ internal_static_io_prometheus_client_MetricFamily_descriptor;
+ private static
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable
+ internal_static_io_prometheus_client_MetricFamily_fieldAccessorTable;
+
+ public static com.google.protobuf.Descriptors.FileDescriptor
+ getDescriptor() {
+ return descriptor;
+ }
+ private static com.google.protobuf.Descriptors.FileDescriptor
+ descriptor;
+ static {
+ java.lang.String[] descriptorData = {
+ "\n\rmetrics.proto\022\024io.prometheus.client\"(\n" +
+ "\tLabelPair\022\014\n\004name\030\001 \001(\t\022\r\n\005value\030\002 \001(\t\"" +
+ "\026\n\005Gauge\022\r\n\005value\030\001 \001(\001\"\030\n\007Counter\022\r\n\005va" +
+ "lue\030\001 \001(\001\"+\n\010Quantile\022\020\n\010quantile\030\001 \001(\001\022" +
+ "\r\n\005value\030\002 \001(\001\"e\n\007Summary\022\024\n\014sample_coun" +
+ "t\030\001 \001(\004\022\022\n\nsample_sum\030\002 \001(\001\0220\n\010quantile\030" +
+ "\003 \003(\0132\036.io.prometheus.client.Quantile\"\030\n" +
+ "\007Untyped\022\r\n\005value\030\001 \001(\001\"c\n\tHistogram\022\024\n\014" +
+ "sample_count\030\001 \001(\004\022\022\n\nsample_sum\030\002 \001(\001\022," +
+ "\n\006bucket\030\003 \003(\0132\034.io.prometheus.client.Bu",
+ "cket\"7\n\006Bucket\022\030\n\020cumulative_count\030\001 \001(\004" +
+ "\022\023\n\013upper_bound\030\002 \001(\001\"\276\002\n\006Metric\022.\n\005labe" +
+ "l\030\001 \003(\0132\037.io.prometheus.client.LabelPair" +
+ "\022*\n\005gauge\030\002 \001(\0132\033.io.prometheus.client.G" +
+ "auge\022.\n\007counter\030\003 \001(\0132\035.io.prometheus.cl" +
+ "ient.Counter\022.\n\007summary\030\004 \001(\0132\035.io.prome" +
+ "theus.client.Summary\022.\n\007untyped\030\005 \001(\0132\035." +
+ "io.prometheus.client.Untyped\0222\n\thistogra" +
+ "m\030\007 \001(\0132\037.io.prometheus.client.Histogram" +
+ "\022\024\n\014timestamp_ms\030\006 \001(\003\"\210\001\n\014MetricFamily\022",
+ "\014\n\004name\030\001 \001(\t\022\014\n\004help\030\002 \001(\t\022.\n\004type\030\003 \001(" +
+ "\0162 .io.prometheus.client.MetricType\022,\n\006m" +
+ "etric\030\004 \003(\0132\034.io.prometheus.client.Metri" +
+ "c*M\n\nMetricType\022\013\n\007COUNTER\020\000\022\t\n\005GAUGE\020\001\022" +
+ "\013\n\007SUMMARY\020\002\022\013\n\007UNTYPED\020\003\022\r\n\tHISTOGRAM\020\004" +
+ "B\026\n\024io.prometheus.client"
+ };
+ com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
+ new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() {
+ public com.google.protobuf.ExtensionRegistry assignDescriptors(
+ com.google.protobuf.Descriptors.FileDescriptor root) {
+ descriptor = root;
+ return null;
+ }
+ };
+ com.google.protobuf.Descriptors.FileDescriptor
+ .internalBuildGeneratedFileFrom(descriptorData,
+ new com.google.protobuf.Descriptors.FileDescriptor[] {
+ }, assigner);
+ internal_static_io_prometheus_client_LabelPair_descriptor =
+ getDescriptor().getMessageTypes().get(0);
+ internal_static_io_prometheus_client_LabelPair_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_io_prometheus_client_LabelPair_descriptor,
+ new java.lang.String[] { "Name", "Value", });
+ internal_static_io_prometheus_client_Gauge_descriptor =
+ getDescriptor().getMessageTypes().get(1);
+ internal_static_io_prometheus_client_Gauge_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_io_prometheus_client_Gauge_descriptor,
+ new java.lang.String[] { "Value", });
+ internal_static_io_prometheus_client_Counter_descriptor =
+ getDescriptor().getMessageTypes().get(2);
+ internal_static_io_prometheus_client_Counter_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_io_prometheus_client_Counter_descriptor,
+ new java.lang.String[] { "Value", });
+ internal_static_io_prometheus_client_Quantile_descriptor =
+ getDescriptor().getMessageTypes().get(3);
+ internal_static_io_prometheus_client_Quantile_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_io_prometheus_client_Quantile_descriptor,
+ new java.lang.String[] { "Quantile", "Value", });
+ internal_static_io_prometheus_client_Summary_descriptor =
+ getDescriptor().getMessageTypes().get(4);
+ internal_static_io_prometheus_client_Summary_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_io_prometheus_client_Summary_descriptor,
+ new java.lang.String[] { "SampleCount", "SampleSum", "Quantile", });
+ internal_static_io_prometheus_client_Untyped_descriptor =
+ getDescriptor().getMessageTypes().get(5);
+ internal_static_io_prometheus_client_Untyped_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_io_prometheus_client_Untyped_descriptor,
+ new java.lang.String[] { "Value", });
+ internal_static_io_prometheus_client_Histogram_descriptor =
+ getDescriptor().getMessageTypes().get(6);
+ internal_static_io_prometheus_client_Histogram_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_io_prometheus_client_Histogram_descriptor,
+ new java.lang.String[] { "SampleCount", "SampleSum", "Bucket", });
+ internal_static_io_prometheus_client_Bucket_descriptor =
+ getDescriptor().getMessageTypes().get(7);
+ internal_static_io_prometheus_client_Bucket_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_io_prometheus_client_Bucket_descriptor,
+ new java.lang.String[] { "CumulativeCount", "UpperBound", });
+ internal_static_io_prometheus_client_Metric_descriptor =
+ getDescriptor().getMessageTypes().get(8);
+ internal_static_io_prometheus_client_Metric_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_io_prometheus_client_Metric_descriptor,
+ new java.lang.String[] { "Label", "Gauge", "Counter", "Summary", "Untyped", "Histogram", "TimestampMs", });
+ internal_static_io_prometheus_client_MetricFamily_descriptor =
+ getDescriptor().getMessageTypes().get(9);
+ internal_static_io_prometheus_client_MetricFamily_fieldAccessorTable = new
+ com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+ internal_static_io_prometheus_client_MetricFamily_descriptor,
+ new java.lang.String[] { "Name", "Help", "Type", "Metric", });
+ }
+
+ // @@protoc_insertion_point(outer_class_scope)
+}
diff --git a/vendor/github.com/prometheus/common/.travis.yml b/vendor/github.com/prometheus/common/.travis.yml
new file mode 100644
index 0000000..2fe8e9a
--- /dev/null
+++ b/vendor/github.com/prometheus/common/.travis.yml
@@ -0,0 +1,6 @@
+sudo: false
+
+language: go
+go:
+ - 1.7.5
+ - tip
diff --git a/vendor/github.com/prometheus/common/CONTRIBUTING.md b/vendor/github.com/prometheus/common/CONTRIBUTING.md
new file mode 100644
index 0000000..40503ed
--- /dev/null
+++ b/vendor/github.com/prometheus/common/CONTRIBUTING.md
@@ -0,0 +1,18 @@
+# Contributing
+
+Prometheus uses GitHub to manage reviews of pull requests.
+
+* If you have a trivial fix or improvement, go ahead and create a pull request,
+ addressing (with `@...`) the maintainer of this repository (see
+ [MAINTAINERS.md](MAINTAINERS.md)) in the description of the pull request.
+
+* If you plan to do something more involved, first discuss your ideas
+ on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers).
+ This will avoid unnecessary work and surely give you and us a good deal
+ of inspiration.
+
+* Relevant coding style guidelines are the [Go Code Review
+ Comments](https://code.google.com/p/go-wiki/wiki/CodeReviewComments)
+ and the _Formatting and style_ section of Peter Bourgon's [Go: Best
+ Practices for Production
+ Environments](http://peter.bourgon.org/go-in-production/#formatting-and-style).
diff --git a/vendor/github.com/prometheus/common/LICENSE b/vendor/github.com/prometheus/common/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/vendor/github.com/prometheus/common/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/vendor/github.com/prometheus/common/MAINTAINERS.md b/vendor/github.com/prometheus/common/MAINTAINERS.md
new file mode 100644
index 0000000..1b31521
--- /dev/null
+++ b/vendor/github.com/prometheus/common/MAINTAINERS.md
@@ -0,0 +1 @@
+* Fabian Reinartz
diff --git a/vendor/github.com/prometheus/common/NOTICE b/vendor/github.com/prometheus/common/NOTICE
new file mode 100644
index 0000000..636a2c1
--- /dev/null
+++ b/vendor/github.com/prometheus/common/NOTICE
@@ -0,0 +1,5 @@
+Common libraries shared by Prometheus Go components.
+Copyright 2015 The Prometheus Authors
+
+This product includes software developed at
+SoundCloud Ltd. (http://soundcloud.com/).
diff --git a/vendor/github.com/prometheus/common/README.md b/vendor/github.com/prometheus/common/README.md
new file mode 100644
index 0000000..11a5849
--- /dev/null
+++ b/vendor/github.com/prometheus/common/README.md
@@ -0,0 +1,12 @@
+# Common
+[![Build Status](https://travis-ci.org/prometheus/common.svg)](https://travis-ci.org/prometheus/common)
+
+This repository contains Go libraries that are shared across Prometheus
+components and libraries.
+
+* **config**: Common configuration structures
+* **expfmt**: Decoding and encoding for the exposition format
+* **log**: A logging wrapper around [logrus](https://github.com/sirupsen/logrus)
+* **model**: Shared data structures
+* **route**: A routing wrapper around [httprouter](https://github.com/julienschmidt/httprouter) using `context.Context`
+* **version**: Version informations and metric
diff --git a/vendor/github.com/prometheus/common/config/config.go b/vendor/github.com/prometheus/common/config/config.go
new file mode 100644
index 0000000..9195c34
--- /dev/null
+++ b/vendor/github.com/prometheus/common/config/config.go
@@ -0,0 +1,47 @@
+// Copyright 2016 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package config
+
+import (
+ "fmt"
+ "strings"
+)
+
+func checkOverflow(m map[string]interface{}, ctx string) error {
+ if len(m) > 0 {
+ var keys []string
+ for k := range m {
+ keys = append(keys, k)
+ }
+ return fmt.Errorf("unknown fields in %s: %s", ctx, strings.Join(keys, ", "))
+ }
+ return nil
+}
+
+// Secret special type for storing secrets.
+type Secret string
+
+// MarshalYAML implements the yaml.Marshaler interface for Secrets.
+func (s Secret) MarshalYAML() (interface{}, error) {
+ if s != "" {
+ return "", nil
+ }
+ return nil, nil
+}
+
+//UnmarshalYAML implements the yaml.Unmarshaler interface for Secrets.
+func (s *Secret) UnmarshalYAML(unmarshal func(interface{}) error) error {
+ type plain Secret
+ return unmarshal((*plain)(s))
+}
diff --git a/vendor/github.com/prometheus/common/config/http_config.go b/vendor/github.com/prometheus/common/config/http_config.go
new file mode 100644
index 0000000..ff5837f
--- /dev/null
+++ b/vendor/github.com/prometheus/common/config/http_config.go
@@ -0,0 +1,279 @@
+// Copyright 2016 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package config
+
+import (
+ "crypto/tls"
+ "crypto/x509"
+ "fmt"
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "strings"
+
+ yaml "gopkg.in/yaml.v2"
+)
+
+// BasicAuth contains basic HTTP authentication credentials.
+type BasicAuth struct {
+ Username string `yaml:"username"`
+ Password Secret `yaml:"password"`
+
+ // Catches all undefined fields and must be empty after parsing.
+ XXX map[string]interface{} `yaml:",inline"`
+}
+
+// URL is a custom URL type that allows validation at configuration load time.
+type URL struct {
+ *url.URL
+}
+
+// UnmarshalYAML implements the yaml.Unmarshaler interface for URLs.
+func (u *URL) UnmarshalYAML(unmarshal func(interface{}) error) error {
+ var s string
+ if err := unmarshal(&s); err != nil {
+ return err
+ }
+
+ urlp, err := url.Parse(s)
+ if err != nil {
+ return err
+ }
+ u.URL = urlp
+ return nil
+}
+
+// MarshalYAML implements the yaml.Marshaler interface for URLs.
+func (u URL) MarshalYAML() (interface{}, error) {
+ if u.URL != nil {
+ return u.String(), nil
+ }
+ return nil, nil
+}
+
+// HTTPClientConfig configures an HTTP client.
+type HTTPClientConfig struct {
+ // The HTTP basic authentication credentials for the targets.
+ BasicAuth *BasicAuth `yaml:"basic_auth,omitempty"`
+ // The bearer token for the targets.
+ BearerToken Secret `yaml:"bearer_token,omitempty"`
+ // The bearer token file for the targets.
+ BearerTokenFile string `yaml:"bearer_token_file,omitempty"`
+ // HTTP proxy server to use to connect to the targets.
+ ProxyURL URL `yaml:"proxy_url,omitempty"`
+ // TLSConfig to use to connect to the targets.
+ TLSConfig TLSConfig `yaml:"tls_config,omitempty"`
+
+ // Catches all undefined fields and must be empty after parsing.
+ XXX map[string]interface{} `yaml:",inline"`
+}
+
+func (c *HTTPClientConfig) validate() error {
+ if len(c.BearerToken) > 0 && len(c.BearerTokenFile) > 0 {
+ return fmt.Errorf("at most one of bearer_token & bearer_token_file must be configured")
+ }
+ if c.BasicAuth != nil && (len(c.BearerToken) > 0 || len(c.BearerTokenFile) > 0) {
+ return fmt.Errorf("at most one of basic_auth, bearer_token & bearer_token_file must be configured")
+ }
+ return nil
+}
+
+// UnmarshalYAML implements the yaml.Unmarshaler interface
+func (c *HTTPClientConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
+ type plain HTTPClientConfig
+ err := unmarshal((*plain)(c))
+ if err != nil {
+ return err
+ }
+ err = c.validate()
+ if err != nil {
+ return c.validate()
+ }
+ return checkOverflow(c.XXX, "http_client_config")
+}
+
+// UnmarshalYAML implements the yaml.Unmarshaler interface.
+func (a *BasicAuth) UnmarshalYAML(unmarshal func(interface{}) error) error {
+ type plain BasicAuth
+ err := unmarshal((*plain)(a))
+ if err != nil {
+ return err
+ }
+ return checkOverflow(a.XXX, "basic_auth")
+}
+
+// NewHTTPClientFromConfig returns a new HTTP client configured for the
+// given config.HTTPClientConfig.
+func NewHTTPClientFromConfig(cfg *HTTPClientConfig) (*http.Client, error) {
+ tlsConfig, err := NewTLSConfig(&cfg.TLSConfig)
+ if err != nil {
+ return nil, err
+ }
+
+ // It's the caller's job to handle timeouts
+ var rt http.RoundTripper = &http.Transport{
+ Proxy: http.ProxyURL(cfg.ProxyURL.URL),
+ DisableKeepAlives: true,
+ TLSClientConfig: tlsConfig,
+ }
+
+ // If a bearer token is provided, create a round tripper that will set the
+ // Authorization header correctly on each request.
+ bearerToken := cfg.BearerToken
+ if len(bearerToken) == 0 && len(cfg.BearerTokenFile) > 0 {
+ b, err := ioutil.ReadFile(cfg.BearerTokenFile)
+ if err != nil {
+ return nil, fmt.Errorf("unable to read bearer token file %s: %s", cfg.BearerTokenFile, err)
+ }
+ bearerToken = Secret(strings.TrimSpace(string(b)))
+ }
+
+ if len(bearerToken) > 0 {
+ rt = NewBearerAuthRoundTripper(bearerToken, rt)
+ }
+
+ if cfg.BasicAuth != nil {
+ rt = NewBasicAuthRoundTripper(cfg.BasicAuth.Username, Secret(cfg.BasicAuth.Password), rt)
+ }
+
+ // Return a new client with the configured round tripper.
+ return &http.Client{Transport: rt}, nil
+}
+
+type bearerAuthRoundTripper struct {
+ bearerToken Secret
+ rt http.RoundTripper
+}
+
+type basicAuthRoundTripper struct {
+ username string
+ password Secret
+ rt http.RoundTripper
+}
+
+// NewBasicAuthRoundTripper will apply a BASIC auth authorization header to a request unless it has
+// already been set.
+func NewBasicAuthRoundTripper(username string, password Secret, rt http.RoundTripper) http.RoundTripper {
+ return &basicAuthRoundTripper{username, password, rt}
+}
+
+func (rt *bearerAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
+ if len(req.Header.Get("Authorization")) == 0 {
+ req = cloneRequest(req)
+ req.Header.Set("Authorization", "Bearer "+string(rt.bearerToken))
+ }
+
+ return rt.rt.RoundTrip(req)
+}
+
+// NewBearerAuthRoundTripper adds the provided bearer token to a request unless the authorization
+// header has already been set.
+func NewBearerAuthRoundTripper(bearer Secret, rt http.RoundTripper) http.RoundTripper {
+ return &bearerAuthRoundTripper{bearer, rt}
+}
+
+func (rt *basicAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
+ if len(req.Header.Get("Authorization")) != 0 {
+ return rt.RoundTrip(req)
+ }
+ req = cloneRequest(req)
+ req.SetBasicAuth(rt.username, string(rt.password))
+ return rt.rt.RoundTrip(req)
+}
+
+// cloneRequest returns a clone of the provided *http.Request.
+// The clone is a shallow copy of the struct and its Header map.
+func cloneRequest(r *http.Request) *http.Request {
+ // Shallow copy of the struct.
+ r2 := new(http.Request)
+ *r2 = *r
+ // Deep copy of the Header.
+ r2.Header = make(http.Header)
+ for k, s := range r.Header {
+ r2.Header[k] = s
+ }
+ return r2
+}
+
+// NewTLSConfig creates a new tls.Config from the given config.TLSConfig.
+func NewTLSConfig(cfg *TLSConfig) (*tls.Config, error) {
+ tlsConfig := &tls.Config{InsecureSkipVerify: cfg.InsecureSkipVerify}
+
+ // If a CA cert is provided then let's read it in so we can validate the
+ // scrape target's certificate properly.
+ if len(cfg.CAFile) > 0 {
+ caCertPool := x509.NewCertPool()
+ // Load CA cert.
+ caCert, err := ioutil.ReadFile(cfg.CAFile)
+ if err != nil {
+ return nil, fmt.Errorf("unable to use specified CA cert %s: %s", cfg.CAFile, err)
+ }
+ caCertPool.AppendCertsFromPEM(caCert)
+ tlsConfig.RootCAs = caCertPool
+ }
+
+ if len(cfg.ServerName) > 0 {
+ tlsConfig.ServerName = cfg.ServerName
+ }
+
+ // If a client cert & key is provided then configure TLS config accordingly.
+ if len(cfg.CertFile) > 0 && len(cfg.KeyFile) == 0 {
+ return nil, fmt.Errorf("client cert file %q specified without client key file", cfg.CertFile)
+ } else if len(cfg.KeyFile) > 0 && len(cfg.CertFile) == 0 {
+ return nil, fmt.Errorf("client key file %q specified without client cert file", cfg.KeyFile)
+ } else if len(cfg.CertFile) > 0 && len(cfg.KeyFile) > 0 {
+ cert, err := tls.LoadX509KeyPair(cfg.CertFile, cfg.KeyFile)
+ if err != nil {
+ return nil, fmt.Errorf("unable to use specified client cert (%s) & key (%s): %s", cfg.CertFile, cfg.KeyFile, err)
+ }
+ tlsConfig.Certificates = []tls.Certificate{cert}
+ }
+ tlsConfig.BuildNameToCertificate()
+
+ return tlsConfig, nil
+}
+
+// TLSConfig configures the options for TLS connections.
+type TLSConfig struct {
+ // The CA cert to use for the targets.
+ CAFile string `yaml:"ca_file,omitempty"`
+ // The client cert file for the targets.
+ CertFile string `yaml:"cert_file,omitempty"`
+ // The client key file for the targets.
+ KeyFile string `yaml:"key_file,omitempty"`
+ // Used to verify the hostname for the targets.
+ ServerName string `yaml:"server_name,omitempty"`
+ // Disable target certificate validation.
+ InsecureSkipVerify bool `yaml:"insecure_skip_verify"`
+
+ // Catches all undefined fields and must be empty after parsing.
+ XXX map[string]interface{} `yaml:",inline"`
+}
+
+// UnmarshalYAML implements the yaml.Unmarshaler interface.
+func (c *TLSConfig) UnmarshalYAML(unmarshal func(interface{}) error) error {
+ type plain TLSConfig
+ if err := unmarshal((*plain)(c)); err != nil {
+ return err
+ }
+ return checkOverflow(c.XXX, "TLS config")
+}
+
+func (c HTTPClientConfig) String() string {
+ b, err := yaml.Marshal(c)
+ if err != nil {
+ return fmt.Sprintf("", err)
+ }
+ return string(b)
+}
diff --git a/vendor/github.com/prometheus/common/config/http_config_test.go b/vendor/github.com/prometheus/common/config/http_config_test.go
new file mode 100644
index 0000000..1e2490b
--- /dev/null
+++ b/vendor/github.com/prometheus/common/config/http_config_test.go
@@ -0,0 +1,157 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package config
+
+import (
+ "io/ioutil"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+
+ yaml "gopkg.in/yaml.v2"
+)
+
+var invalidHTTPClientConfigs = []struct {
+ httpClientConfigFile string
+ errMsg string
+}{
+ {
+ httpClientConfigFile: "testdata/http.conf.bearer-token-and-file-set.bad.yml",
+ errMsg: "at most one of bearer_token & bearer_token_file must be configured",
+ },
+ {
+ httpClientConfigFile: "testdata/http.conf.empty.bad.yml",
+ errMsg: "at most one of basic_auth, bearer_token & bearer_token_file must be configured",
+ },
+}
+
+func TestAuthRoundTrippers(t *testing.T) {
+
+ cfg, _, err := LoadHTTPConfigFile("testdata/http.conf.good.yml")
+ if err != nil {
+ t.Errorf("Error loading HTTP client config: %v", err)
+ }
+
+ tlsConfig, err := NewTLSConfig(&cfg.TLSConfig)
+ if err != nil {
+ t.Errorf("Error creating new TLS config: %v", err)
+ }
+
+ rt := &http.Transport{
+ Proxy: http.ProxyURL(cfg.ProxyURL.URL),
+ DisableKeepAlives: true,
+ TLSClientConfig: tlsConfig,
+ }
+ req := new(http.Request)
+
+ bearerAuthRoundTripper := NewBearerAuthRoundTripper("mysecret", rt)
+ bearerAuthRoundTripper.RoundTrip(req)
+
+ basicAuthRoundTripper := NewBasicAuthRoundTripper("username", "password", rt)
+ basicAuthRoundTripper.RoundTrip(req)
+}
+
+func TestHideHTTPClientConfigSecrets(t *testing.T) {
+ c, _, err := LoadHTTPConfigFile("testdata/http.conf.good.yml")
+ if err != nil {
+ t.Errorf("Error parsing %s: %s", "testdata/http.conf.good.yml", err)
+ }
+
+ // String method must not reveal authentication credentials.
+ s := c.String()
+ if strings.Contains(s, "mysecret") {
+ t.Fatal("http client config's String method reveals authentication credentials.")
+ }
+}
+
+func mustParseURL(u string) *URL {
+ parsed, err := url.Parse(u)
+ if err != nil {
+ panic(err)
+ }
+ return &URL{URL: parsed}
+}
+
+func TestNewClientFromConfig(t *testing.T) {
+ cfg, _, err := LoadHTTPConfigFile("testdata/http.conf.good.yml")
+ if err != nil {
+ t.Errorf("Error loading HTTP client config: %v", err)
+ }
+ _, err = NewHTTPClientFromConfig(cfg)
+ if err != nil {
+ t.Errorf("Error creating new client from config: %v", err)
+ }
+}
+
+func TestNewClientFromInvalidConfig(t *testing.T) {
+ cfg, _, err := LoadHTTPConfigFile("testdata/http.conf.invalid-bearer-token-file.bad.yml")
+ if err != nil {
+ t.Errorf("Error loading HTTP client config: %v", err)
+ }
+ _, err = NewHTTPClientFromConfig(cfg)
+ if err == nil {
+ t.Error("Expected error creating new client from invalid config but got none")
+ }
+ if !strings.Contains(err.Error(), "unable to read bearer token file file: open file: no such file or directory") {
+ t.Errorf("Expected error with config but got: %s", err.Error())
+ }
+}
+
+func TestValidateHTTPConfig(t *testing.T) {
+ cfg, _, err := LoadHTTPConfigFile("testdata/http.conf.good.yml")
+ if err != nil {
+ t.Errorf("Error loading HTTP client config: %v", err)
+ }
+ err = cfg.validate()
+ if err != nil {
+ t.Fatalf("Error validating %s: %s", "testdata/http.conf.good.yml", err)
+ }
+}
+
+func TestInvalidHTTPConfigs(t *testing.T) {
+ for _, ee := range invalidHTTPClientConfigs {
+ _, _, err := LoadHTTPConfigFile(ee.httpClientConfigFile)
+ if err == nil {
+ t.Error("Expected error with config but got none")
+ continue
+ }
+ if !strings.Contains(err.Error(), ee.errMsg) {
+ t.Errorf("Expected error for invalid HTTP client configuration to contain %q but got: %s", ee.errMsg, err)
+ }
+ }
+}
+
+// LoadHTTPConfig parses the YAML input s into a HTTPClientConfig.
+func LoadHTTPConfig(s string) (*HTTPClientConfig, error) {
+ cfg := &HTTPClientConfig{}
+ err := yaml.Unmarshal([]byte(s), cfg)
+ if err != nil {
+ return nil, err
+ }
+ return cfg, nil
+}
+
+// LoadHTTPConfigFile parses the given YAML file into a HTTPClientConfig.
+func LoadHTTPConfigFile(filename string) (*HTTPClientConfig, []byte, error) {
+ content, err := ioutil.ReadFile(filename)
+ if err != nil {
+ return nil, nil, err
+ }
+ cfg, err := LoadHTTPConfig(string(content))
+ if err != nil {
+ return nil, nil, err
+ }
+ return cfg, content, nil
+}
diff --git a/vendor/github.com/prometheus/common/config/testdata/http.conf.bearer-token-and-file-set.bad.yml b/vendor/github.com/prometheus/common/config/testdata/http.conf.bearer-token-and-file-set.bad.yml
new file mode 100644
index 0000000..c613bac
--- /dev/null
+++ b/vendor/github.com/prometheus/common/config/testdata/http.conf.bearer-token-and-file-set.bad.yml
@@ -0,0 +1,5 @@
+basic_auth:
+ username: username
+ password: "mysecret"
+bearer_token: mysecret
+bearer_token_file: file
diff --git a/vendor/github.com/prometheus/common/config/testdata/http.conf.empty.bad.yml b/vendor/github.com/prometheus/common/config/testdata/http.conf.empty.bad.yml
new file mode 100644
index 0000000..ea2811f
--- /dev/null
+++ b/vendor/github.com/prometheus/common/config/testdata/http.conf.empty.bad.yml
@@ -0,0 +1,4 @@
+basic_auth:
+ username: username
+ password: mysecret
+bearer_token_file: file
diff --git a/vendor/github.com/prometheus/common/config/testdata/http.conf.good.yml b/vendor/github.com/prometheus/common/config/testdata/http.conf.good.yml
new file mode 100644
index 0000000..46ca639
--- /dev/null
+++ b/vendor/github.com/prometheus/common/config/testdata/http.conf.good.yml
@@ -0,0 +1,4 @@
+basic_auth:
+ username: username
+ password: "mysecret"
+proxy_url: "http://remote.host"
diff --git a/vendor/github.com/prometheus/common/config/testdata/http.conf.invalid-bearer-token-file.bad.yml b/vendor/github.com/prometheus/common/config/testdata/http.conf.invalid-bearer-token-file.bad.yml
new file mode 100644
index 0000000..4b1349b
--- /dev/null
+++ b/vendor/github.com/prometheus/common/config/testdata/http.conf.invalid-bearer-token-file.bad.yml
@@ -0,0 +1 @@
+bearer_token_file: file
diff --git a/vendor/github.com/prometheus/common/config/testdata/tls_config.cert_no_key.bad.yml b/vendor/github.com/prometheus/common/config/testdata/tls_config.cert_no_key.bad.yml
new file mode 100644
index 0000000..7dfdc1e
--- /dev/null
+++ b/vendor/github.com/prometheus/common/config/testdata/tls_config.cert_no_key.bad.yml
@@ -0,0 +1 @@
+cert_file: somefile
diff --git a/vendor/github.com/prometheus/common/config/testdata/tls_config.empty.good.yml b/vendor/github.com/prometheus/common/config/testdata/tls_config.empty.good.yml
new file mode 100644
index 0000000..e69de29
diff --git a/vendor/github.com/prometheus/common/config/testdata/tls_config.insecure.good.yml b/vendor/github.com/prometheus/common/config/testdata/tls_config.insecure.good.yml
new file mode 100644
index 0000000..d054383
--- /dev/null
+++ b/vendor/github.com/prometheus/common/config/testdata/tls_config.insecure.good.yml
@@ -0,0 +1 @@
+insecure_skip_verify: true
diff --git a/vendor/github.com/prometheus/common/config/testdata/tls_config.invalid_field.bad.yml b/vendor/github.com/prometheus/common/config/testdata/tls_config.invalid_field.bad.yml
new file mode 100644
index 0000000..12cbaac
--- /dev/null
+++ b/vendor/github.com/prometheus/common/config/testdata/tls_config.invalid_field.bad.yml
@@ -0,0 +1 @@
+something_invalid: true
diff --git a/vendor/github.com/prometheus/common/config/testdata/tls_config.key_no_cert.bad.yml b/vendor/github.com/prometheus/common/config/testdata/tls_config.key_no_cert.bad.yml
new file mode 100644
index 0000000..cec045e
--- /dev/null
+++ b/vendor/github.com/prometheus/common/config/testdata/tls_config.key_no_cert.bad.yml
@@ -0,0 +1 @@
+key_file: somefile
diff --git a/vendor/github.com/prometheus/common/config/tls_config_test.go b/vendor/github.com/prometheus/common/config/tls_config_test.go
new file mode 100644
index 0000000..e2bd68e
--- /dev/null
+++ b/vendor/github.com/prometheus/common/config/tls_config_test.go
@@ -0,0 +1,92 @@
+// Copyright 2016 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package config
+
+import (
+ "crypto/tls"
+ "io/ioutil"
+ "reflect"
+ "strings"
+ "testing"
+
+ "gopkg.in/yaml.v2"
+)
+
+// LoadTLSConfig parses the given YAML file into a tls.Config.
+func LoadTLSConfig(filename string) (*tls.Config, error) {
+ content, err := ioutil.ReadFile(filename)
+ if err != nil {
+ return nil, err
+ }
+ cfg := &TLSConfig{}
+ if err = yaml.Unmarshal(content, cfg); err != nil {
+ return nil, err
+ }
+ return NewTLSConfig(cfg)
+}
+
+var expectedTLSConfigs = []struct {
+ filename string
+ config *tls.Config
+}{
+ {
+ filename: "tls_config.empty.good.yml",
+ config: &tls.Config{},
+ }, {
+ filename: "tls_config.insecure.good.yml",
+ config: &tls.Config{InsecureSkipVerify: true},
+ },
+}
+
+func TestValidTLSConfig(t *testing.T) {
+ for _, cfg := range expectedTLSConfigs {
+ cfg.config.BuildNameToCertificate()
+ got, err := LoadTLSConfig("testdata/" + cfg.filename)
+ if err != nil {
+ t.Errorf("Error parsing %s: %s", cfg.filename, err)
+ }
+ if !reflect.DeepEqual(*got, *cfg.config) {
+ t.Fatalf("%v: unexpected config result: \n\n%v\n expected\n\n%v", cfg.filename, got, cfg.config)
+ }
+ }
+}
+
+var expectedTLSConfigErrors = []struct {
+ filename string
+ errMsg string
+}{
+ {
+ filename: "tls_config.invalid_field.bad.yml",
+ errMsg: "unknown fields in",
+ }, {
+ filename: "tls_config.cert_no_key.bad.yml",
+ errMsg: "specified without client key file",
+ }, {
+ filename: "tls_config.key_no_cert.bad.yml",
+ errMsg: "specified without client cert file",
+ },
+}
+
+func TestBadTLSConfigs(t *testing.T) {
+ for _, ee := range expectedTLSConfigErrors {
+ _, err := LoadTLSConfig("testdata/" + ee.filename)
+ if err == nil {
+ t.Errorf("Expected error parsing %s but got none", ee.filename)
+ continue
+ }
+ if !strings.Contains(err.Error(), ee.errMsg) {
+ t.Errorf("Expected error for %s to contain %q but got: %s", ee.filename, ee.errMsg, err)
+ }
+ }
+}
diff --git a/vendor/github.com/prometheus/client_golang/text/bench_test.go b/vendor/github.com/prometheus/common/expfmt/bench_test.go
similarity index 95%
rename from vendor/github.com/prometheus/client_golang/text/bench_test.go
rename to vendor/github.com/prometheus/common/expfmt/bench_test.go
index c315eec..e539bfc 100644
--- a/vendor/github.com/prometheus/client_golang/text/bench_test.go
+++ b/vendor/github.com/prometheus/common/expfmt/bench_test.go
@@ -11,7 +11,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-package text
+package expfmt
import (
"bytes"
@@ -25,6 +25,8 @@ import (
dto "github.com/prometheus/client_model/go"
)
+var parser TextParser
+
// Benchmarks to show how much penalty text format parsing actually inflicts.
//
// Example results on Linux 3.13.0, Intel(R) Core(TM) i7-4700MQ CPU @ 2.40GHz, go1.4.
@@ -40,10 +42,6 @@ import (
// the difference becomes less relevant, only ~4x.
//
// The test data contains 248 samples.
-//
-// BenchmarkProcessor002ParseOnly in the extraction package is not quite
-// comparable to the benchmarks here, but it gives an idea: JSON parsing is even
-// slower than text parsing and needs a comparable amount of allocs.
// BenchmarkParseText benchmarks the parsing of a text-format scrape into metric
// family DTOs.
diff --git a/vendor/github.com/prometheus/common/expfmt/decode.go b/vendor/github.com/prometheus/common/expfmt/decode.go
new file mode 100644
index 0000000..a7a42d5
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/decode.go
@@ -0,0 +1,429 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package expfmt
+
+import (
+ "fmt"
+ "io"
+ "math"
+ "mime"
+ "net/http"
+
+ dto "github.com/prometheus/client_model/go"
+
+ "github.com/matttproud/golang_protobuf_extensions/pbutil"
+ "github.com/prometheus/common/model"
+)
+
+// Decoder types decode an input stream into metric families.
+type Decoder interface {
+ Decode(*dto.MetricFamily) error
+}
+
+// DecodeOptions contains options used by the Decoder and in sample extraction.
+type DecodeOptions struct {
+ // Timestamp is added to each value from the stream that has no explicit timestamp set.
+ Timestamp model.Time
+}
+
+// ResponseFormat extracts the correct format from a HTTP response header.
+// If no matching format can be found FormatUnknown is returned.
+func ResponseFormat(h http.Header) Format {
+ ct := h.Get(hdrContentType)
+
+ mediatype, params, err := mime.ParseMediaType(ct)
+ if err != nil {
+ return FmtUnknown
+ }
+
+ const textType = "text/plain"
+
+ switch mediatype {
+ case ProtoType:
+ if p, ok := params["proto"]; ok && p != ProtoProtocol {
+ return FmtUnknown
+ }
+ if e, ok := params["encoding"]; ok && e != "delimited" {
+ return FmtUnknown
+ }
+ return FmtProtoDelim
+
+ case textType:
+ if v, ok := params["version"]; ok && v != TextVersion {
+ return FmtUnknown
+ }
+ return FmtText
+ }
+
+ return FmtUnknown
+}
+
+// NewDecoder returns a new decoder based on the given input format.
+// If the input format does not imply otherwise, a text format decoder is returned.
+func NewDecoder(r io.Reader, format Format) Decoder {
+ switch format {
+ case FmtProtoDelim:
+ return &protoDecoder{r: r}
+ }
+ return &textDecoder{r: r}
+}
+
+// protoDecoder implements the Decoder interface for protocol buffers.
+type protoDecoder struct {
+ r io.Reader
+}
+
+// Decode implements the Decoder interface.
+func (d *protoDecoder) Decode(v *dto.MetricFamily) error {
+ _, err := pbutil.ReadDelimited(d.r, v)
+ if err != nil {
+ return err
+ }
+ if !model.IsValidMetricName(model.LabelValue(v.GetName())) {
+ return fmt.Errorf("invalid metric name %q", v.GetName())
+ }
+ for _, m := range v.GetMetric() {
+ if m == nil {
+ continue
+ }
+ for _, l := range m.GetLabel() {
+ if l == nil {
+ continue
+ }
+ if !model.LabelValue(l.GetValue()).IsValid() {
+ return fmt.Errorf("invalid label value %q", l.GetValue())
+ }
+ if !model.LabelName(l.GetName()).IsValid() {
+ return fmt.Errorf("invalid label name %q", l.GetName())
+ }
+ }
+ }
+ return nil
+}
+
+// textDecoder implements the Decoder interface for the text protocol.
+type textDecoder struct {
+ r io.Reader
+ p TextParser
+ fams []*dto.MetricFamily
+}
+
+// Decode implements the Decoder interface.
+func (d *textDecoder) Decode(v *dto.MetricFamily) error {
+ // TODO(fabxc): Wrap this as a line reader to make streaming safer.
+ if len(d.fams) == 0 {
+ // No cached metric families, read everything and parse metrics.
+ fams, err := d.p.TextToMetricFamilies(d.r)
+ if err != nil {
+ return err
+ }
+ if len(fams) == 0 {
+ return io.EOF
+ }
+ d.fams = make([]*dto.MetricFamily, 0, len(fams))
+ for _, f := range fams {
+ d.fams = append(d.fams, f)
+ }
+ }
+
+ *v = *d.fams[0]
+ d.fams = d.fams[1:]
+
+ return nil
+}
+
+// SampleDecoder wraps a Decoder to extract samples from the metric families
+// decoded by the wrapped Decoder.
+type SampleDecoder struct {
+ Dec Decoder
+ Opts *DecodeOptions
+
+ f dto.MetricFamily
+}
+
+// Decode calls the Decode method of the wrapped Decoder and then extracts the
+// samples from the decoded MetricFamily into the provided model.Vector.
+func (sd *SampleDecoder) Decode(s *model.Vector) error {
+ err := sd.Dec.Decode(&sd.f)
+ if err != nil {
+ return err
+ }
+ *s, err = extractSamples(&sd.f, sd.Opts)
+ return err
+}
+
+// ExtractSamples builds a slice of samples from the provided metric
+// families. If an error occurs during sample extraction, it continues to
+// extract from the remaining metric families. The returned error is the last
+// error that has occured.
+func ExtractSamples(o *DecodeOptions, fams ...*dto.MetricFamily) (model.Vector, error) {
+ var (
+ all model.Vector
+ lastErr error
+ )
+ for _, f := range fams {
+ some, err := extractSamples(f, o)
+ if err != nil {
+ lastErr = err
+ continue
+ }
+ all = append(all, some...)
+ }
+ return all, lastErr
+}
+
+func extractSamples(f *dto.MetricFamily, o *DecodeOptions) (model.Vector, error) {
+ switch f.GetType() {
+ case dto.MetricType_COUNTER:
+ return extractCounter(o, f), nil
+ case dto.MetricType_GAUGE:
+ return extractGauge(o, f), nil
+ case dto.MetricType_SUMMARY:
+ return extractSummary(o, f), nil
+ case dto.MetricType_UNTYPED:
+ return extractUntyped(o, f), nil
+ case dto.MetricType_HISTOGRAM:
+ return extractHistogram(o, f), nil
+ }
+ return nil, fmt.Errorf("expfmt.extractSamples: unknown metric family type %v", f.GetType())
+}
+
+func extractCounter(o *DecodeOptions, f *dto.MetricFamily) model.Vector {
+ samples := make(model.Vector, 0, len(f.Metric))
+
+ for _, m := range f.Metric {
+ if m.Counter == nil {
+ continue
+ }
+
+ lset := make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName())
+
+ smpl := &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Counter.GetValue()),
+ }
+
+ if m.TimestampMs != nil {
+ smpl.Timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000)
+ } else {
+ smpl.Timestamp = o.Timestamp
+ }
+
+ samples = append(samples, smpl)
+ }
+
+ return samples
+}
+
+func extractGauge(o *DecodeOptions, f *dto.MetricFamily) model.Vector {
+ samples := make(model.Vector, 0, len(f.Metric))
+
+ for _, m := range f.Metric {
+ if m.Gauge == nil {
+ continue
+ }
+
+ lset := make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName())
+
+ smpl := &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Gauge.GetValue()),
+ }
+
+ if m.TimestampMs != nil {
+ smpl.Timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000)
+ } else {
+ smpl.Timestamp = o.Timestamp
+ }
+
+ samples = append(samples, smpl)
+ }
+
+ return samples
+}
+
+func extractUntyped(o *DecodeOptions, f *dto.MetricFamily) model.Vector {
+ samples := make(model.Vector, 0, len(f.Metric))
+
+ for _, m := range f.Metric {
+ if m.Untyped == nil {
+ continue
+ }
+
+ lset := make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName())
+
+ smpl := &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Untyped.GetValue()),
+ }
+
+ if m.TimestampMs != nil {
+ smpl.Timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000)
+ } else {
+ smpl.Timestamp = o.Timestamp
+ }
+
+ samples = append(samples, smpl)
+ }
+
+ return samples
+}
+
+func extractSummary(o *DecodeOptions, f *dto.MetricFamily) model.Vector {
+ samples := make(model.Vector, 0, len(f.Metric))
+
+ for _, m := range f.Metric {
+ if m.Summary == nil {
+ continue
+ }
+
+ timestamp := o.Timestamp
+ if m.TimestampMs != nil {
+ timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000)
+ }
+
+ for _, q := range m.Summary.Quantile {
+ lset := make(model.LabelSet, len(m.Label)+2)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ // BUG(matt): Update other names to "quantile".
+ lset[model.LabelName(model.QuantileLabel)] = model.LabelValue(fmt.Sprint(q.GetQuantile()))
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName())
+
+ samples = append(samples, &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(q.GetValue()),
+ Timestamp: timestamp,
+ })
+ }
+
+ lset := make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_sum")
+
+ samples = append(samples, &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Summary.GetSampleSum()),
+ Timestamp: timestamp,
+ })
+
+ lset = make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_count")
+
+ samples = append(samples, &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Summary.GetSampleCount()),
+ Timestamp: timestamp,
+ })
+ }
+
+ return samples
+}
+
+func extractHistogram(o *DecodeOptions, f *dto.MetricFamily) model.Vector {
+ samples := make(model.Vector, 0, len(f.Metric))
+
+ for _, m := range f.Metric {
+ if m.Histogram == nil {
+ continue
+ }
+
+ timestamp := o.Timestamp
+ if m.TimestampMs != nil {
+ timestamp = model.TimeFromUnixNano(*m.TimestampMs * 1000000)
+ }
+
+ infSeen := false
+
+ for _, q := range m.Histogram.Bucket {
+ lset := make(model.LabelSet, len(m.Label)+2)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.LabelName(model.BucketLabel)] = model.LabelValue(fmt.Sprint(q.GetUpperBound()))
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_bucket")
+
+ if math.IsInf(q.GetUpperBound(), +1) {
+ infSeen = true
+ }
+
+ samples = append(samples, &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(q.GetCumulativeCount()),
+ Timestamp: timestamp,
+ })
+ }
+
+ lset := make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_sum")
+
+ samples = append(samples, &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Histogram.GetSampleSum()),
+ Timestamp: timestamp,
+ })
+
+ lset = make(model.LabelSet, len(m.Label)+1)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_count")
+
+ count := &model.Sample{
+ Metric: model.Metric(lset),
+ Value: model.SampleValue(m.Histogram.GetSampleCount()),
+ Timestamp: timestamp,
+ }
+ samples = append(samples, count)
+
+ if !infSeen {
+ // Append an infinity bucket sample.
+ lset := make(model.LabelSet, len(m.Label)+2)
+ for _, p := range m.Label {
+ lset[model.LabelName(p.GetName())] = model.LabelValue(p.GetValue())
+ }
+ lset[model.LabelName(model.BucketLabel)] = model.LabelValue("+Inf")
+ lset[model.MetricNameLabel] = model.LabelValue(f.GetName() + "_bucket")
+
+ samples = append(samples, &model.Sample{
+ Metric: model.Metric(lset),
+ Value: count.Value,
+ Timestamp: timestamp,
+ })
+ }
+ }
+
+ return samples
+}
diff --git a/vendor/github.com/prometheus/common/expfmt/decode_test.go b/vendor/github.com/prometheus/common/expfmt/decode_test.go
new file mode 100644
index 0000000..82c1130
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/decode_test.go
@@ -0,0 +1,435 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package expfmt
+
+import (
+ "io"
+ "net/http"
+ "reflect"
+ "sort"
+ "strings"
+ "testing"
+
+ "github.com/golang/protobuf/proto"
+ dto "github.com/prometheus/client_model/go"
+
+ "github.com/prometheus/common/model"
+)
+
+func TestTextDecoder(t *testing.T) {
+ var (
+ ts = model.Now()
+ in = `
+# Only a quite simple scenario with two metric families.
+# More complicated tests of the parser itself can be found in the text package.
+# TYPE mf2 counter
+mf2 3
+mf1{label="value1"} -3.14 123456
+mf1{label="value2"} 42
+mf2 4
+`
+ out = model.Vector{
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "mf1",
+ "label": "value1",
+ },
+ Value: -3.14,
+ Timestamp: 123456,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "mf1",
+ "label": "value2",
+ },
+ Value: 42,
+ Timestamp: ts,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "mf2",
+ },
+ Value: 3,
+ Timestamp: ts,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "mf2",
+ },
+ Value: 4,
+ Timestamp: ts,
+ },
+ }
+ )
+
+ dec := &SampleDecoder{
+ Dec: &textDecoder{r: strings.NewReader(in)},
+ Opts: &DecodeOptions{
+ Timestamp: ts,
+ },
+ }
+ var all model.Vector
+ for {
+ var smpls model.Vector
+ err := dec.Decode(&smpls)
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ all = append(all, smpls...)
+ }
+ sort.Sort(all)
+ sort.Sort(out)
+ if !reflect.DeepEqual(all, out) {
+ t.Fatalf("output does not match")
+ }
+}
+
+func TestProtoDecoder(t *testing.T) {
+
+ var testTime = model.Now()
+
+ scenarios := []struct {
+ in string
+ expected model.Vector
+ fail bool
+ }{
+ {
+ in: "",
+ },
+ {
+ in: "\x8f\x01\n\rrequest_count\x12\x12Number of requests\x18\x00\"0\n#\n\x0fsome_!abel_name\x12\x10some_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00E\xc0\"6\n)\n\x12another_label_name\x12\x13another_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00U@",
+ fail: true,
+ },
+ {
+ in: "\x8f\x01\n\rrequest_count\x12\x12Number of requests\x18\x00\"0\n#\n\x0fsome_label_name\x12\x10some_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00E\xc0\"6\n)\n\x12another_label_name\x12\x13another_label_value\x1a\t\t\x00\x00\x00\x00\x00\x00U@",
+ expected: model.Vector{
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_count",
+ "some_label_name": "some_label_value",
+ },
+ Value: -42,
+ Timestamp: testTime,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_count",
+ "another_label_name": "another_label_value",
+ },
+ Value: 84,
+ Timestamp: testTime,
+ },
+ },
+ },
+ {
+ in: "\xb9\x01\n\rrequest_count\x12\x12Number of requests\x18\x02\"O\n#\n\x0fsome_label_name\x12\x10some_label_value\"(\x1a\x12\t\xaeG\xe1z\x14\xae\xef?\x11\x00\x00\x00\x00\x00\x00E\xc0\x1a\x12\t+\x87\x16\xd9\xce\xf7\xef?\x11\x00\x00\x00\x00\x00\x00U\xc0\"A\n)\n\x12another_label_name\x12\x13another_label_value\"\x14\x1a\x12\t\x00\x00\x00\x00\x00\x00\xe0?\x11\x00\x00\x00\x00\x00\x00$@",
+ expected: model.Vector{
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_count_count",
+ "some_label_name": "some_label_value",
+ },
+ Value: 0,
+ Timestamp: testTime,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_count_sum",
+ "some_label_name": "some_label_value",
+ },
+ Value: 0,
+ Timestamp: testTime,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_count",
+ "some_label_name": "some_label_value",
+ "quantile": "0.99",
+ },
+ Value: -42,
+ Timestamp: testTime,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_count",
+ "some_label_name": "some_label_value",
+ "quantile": "0.999",
+ },
+ Value: -84,
+ Timestamp: testTime,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_count_count",
+ "another_label_name": "another_label_value",
+ },
+ Value: 0,
+ Timestamp: testTime,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_count_sum",
+ "another_label_name": "another_label_value",
+ },
+ Value: 0,
+ Timestamp: testTime,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_count",
+ "another_label_name": "another_label_value",
+ "quantile": "0.5",
+ },
+ Value: 10,
+ Timestamp: testTime,
+ },
+ },
+ },
+ {
+ in: "\x8d\x01\n\x1drequest_duration_microseconds\x12\x15The response latency.\x18\x04\"S:Q\b\x85\x15\x11\xcd\xcc\xccL\x8f\xcb:A\x1a\v\b{\x11\x00\x00\x00\x00\x00\x00Y@\x1a\f\b\x9c\x03\x11\x00\x00\x00\x00\x00\x00^@\x1a\f\b\xd0\x04\x11\x00\x00\x00\x00\x00\x00b@\x1a\f\b\xf4\v\x11\x9a\x99\x99\x99\x99\x99e@\x1a\f\b\x85\x15\x11\x00\x00\x00\x00\x00\x00\xf0\u007f",
+ expected: model.Vector{
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_duration_microseconds_bucket",
+ "le": "100",
+ },
+ Value: 123,
+ Timestamp: testTime,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_duration_microseconds_bucket",
+ "le": "120",
+ },
+ Value: 412,
+ Timestamp: testTime,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_duration_microseconds_bucket",
+ "le": "144",
+ },
+ Value: 592,
+ Timestamp: testTime,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_duration_microseconds_bucket",
+ "le": "172.8",
+ },
+ Value: 1524,
+ Timestamp: testTime,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_duration_microseconds_bucket",
+ "le": "+Inf",
+ },
+ Value: 2693,
+ Timestamp: testTime,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_duration_microseconds_sum",
+ },
+ Value: 1756047.3,
+ Timestamp: testTime,
+ },
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_duration_microseconds_count",
+ },
+ Value: 2693,
+ Timestamp: testTime,
+ },
+ },
+ },
+ {
+ // The metric type is unset in this protobuf, which needs to be handled
+ // correctly by the decoder.
+ in: "\x1c\n\rrequest_count\"\v\x1a\t\t\x00\x00\x00\x00\x00\x00\xf0?",
+ expected: model.Vector{
+ &model.Sample{
+ Metric: model.Metric{
+ model.MetricNameLabel: "request_count",
+ },
+ Value: 1,
+ Timestamp: testTime,
+ },
+ },
+ },
+ }
+
+ for i, scenario := range scenarios {
+ dec := &SampleDecoder{
+ Dec: &protoDecoder{r: strings.NewReader(scenario.in)},
+ Opts: &DecodeOptions{
+ Timestamp: testTime,
+ },
+ }
+
+ var all model.Vector
+ for {
+ var smpls model.Vector
+ err := dec.Decode(&smpls)
+ if err == io.EOF {
+ break
+ }
+ if scenario.fail {
+ if err == nil {
+ t.Fatal("Expected error but got none")
+ }
+ break
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ all = append(all, smpls...)
+ }
+ sort.Sort(all)
+ sort.Sort(scenario.expected)
+ if !reflect.DeepEqual(all, scenario.expected) {
+ t.Fatalf("%d. output does not match, want: %#v, got %#v", i, scenario.expected, all)
+ }
+ }
+}
+
+func testDiscriminatorHTTPHeader(t testing.TB) {
+ var scenarios = []struct {
+ input map[string]string
+ output Format
+ err error
+ }{
+ {
+ input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="delimited"`},
+ output: FmtProtoDelim,
+ },
+ {
+ input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="illegal"; encoding="delimited"`},
+ output: FmtUnknown,
+ },
+ {
+ input: map[string]string{"Content-Type": `application/vnd.google.protobuf; proto="io.prometheus.client.MetricFamily"; encoding="illegal"`},
+ output: FmtUnknown,
+ },
+ {
+ input: map[string]string{"Content-Type": `text/plain; version=0.0.4`},
+ output: FmtText,
+ },
+ {
+ input: map[string]string{"Content-Type": `text/plain`},
+ output: FmtText,
+ },
+ {
+ input: map[string]string{"Content-Type": `text/plain; version=0.0.3`},
+ output: FmtUnknown,
+ },
+ }
+
+ for i, scenario := range scenarios {
+ var header http.Header
+
+ if len(scenario.input) > 0 {
+ header = http.Header{}
+ }
+
+ for key, value := range scenario.input {
+ header.Add(key, value)
+ }
+
+ actual := ResponseFormat(header)
+
+ if scenario.output != actual {
+ t.Errorf("%d. expected %s, got %s", i, scenario.output, actual)
+ }
+ }
+}
+
+func TestDiscriminatorHTTPHeader(t *testing.T) {
+ testDiscriminatorHTTPHeader(t)
+}
+
+func BenchmarkDiscriminatorHTTPHeader(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ testDiscriminatorHTTPHeader(b)
+ }
+}
+
+func TestExtractSamples(t *testing.T) {
+ var (
+ goodMetricFamily1 = &dto.MetricFamily{
+ Name: proto.String("foo"),
+ Help: proto.String("Help for foo."),
+ Type: dto.MetricType_COUNTER.Enum(),
+ Metric: []*dto.Metric{
+ &dto.Metric{
+ Counter: &dto.Counter{
+ Value: proto.Float64(4711),
+ },
+ },
+ },
+ }
+ goodMetricFamily2 = &dto.MetricFamily{
+ Name: proto.String("bar"),
+ Help: proto.String("Help for bar."),
+ Type: dto.MetricType_GAUGE.Enum(),
+ Metric: []*dto.Metric{
+ &dto.Metric{
+ Gauge: &dto.Gauge{
+ Value: proto.Float64(3.14),
+ },
+ },
+ },
+ }
+ badMetricFamily = &dto.MetricFamily{
+ Name: proto.String("bad"),
+ Help: proto.String("Help for bad."),
+ Type: dto.MetricType(42).Enum(),
+ Metric: []*dto.Metric{
+ &dto.Metric{
+ Gauge: &dto.Gauge{
+ Value: proto.Float64(2.7),
+ },
+ },
+ },
+ }
+
+ opts = &DecodeOptions{
+ Timestamp: 42,
+ }
+ )
+
+ got, err := ExtractSamples(opts, goodMetricFamily1, goodMetricFamily2)
+ if err != nil {
+ t.Error("Unexpected error from ExtractSamples:", err)
+ }
+ want := model.Vector{
+ &model.Sample{Metric: model.Metric{model.MetricNameLabel: "foo"}, Value: 4711, Timestamp: 42},
+ &model.Sample{Metric: model.Metric{model.MetricNameLabel: "bar"}, Value: 3.14, Timestamp: 42},
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("unexpected samples extracted, got: %v, want: %v", got, want)
+ }
+
+ got, err = ExtractSamples(opts, goodMetricFamily1, badMetricFamily, goodMetricFamily2)
+ if err == nil {
+ t.Error("Expected error from ExtractSamples")
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("unexpected samples extracted, got: %v, want: %v", got, want)
+ }
+}
diff --git a/vendor/github.com/prometheus/common/expfmt/encode.go b/vendor/github.com/prometheus/common/expfmt/encode.go
new file mode 100644
index 0000000..11839ed
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/encode.go
@@ -0,0 +1,88 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package expfmt
+
+import (
+ "fmt"
+ "io"
+ "net/http"
+
+ "github.com/golang/protobuf/proto"
+ "github.com/matttproud/golang_protobuf_extensions/pbutil"
+ "github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg"
+
+ dto "github.com/prometheus/client_model/go"
+)
+
+// Encoder types encode metric families into an underlying wire protocol.
+type Encoder interface {
+ Encode(*dto.MetricFamily) error
+}
+
+type encoder func(*dto.MetricFamily) error
+
+func (e encoder) Encode(v *dto.MetricFamily) error {
+ return e(v)
+}
+
+// Negotiate returns the Content-Type based on the given Accept header.
+// If no appropriate accepted type is found, FmtText is returned.
+func Negotiate(h http.Header) Format {
+ for _, ac := range goautoneg.ParseAccept(h.Get(hdrAccept)) {
+ // Check for protocol buffer
+ if ac.Type+"/"+ac.SubType == ProtoType && ac.Params["proto"] == ProtoProtocol {
+ switch ac.Params["encoding"] {
+ case "delimited":
+ return FmtProtoDelim
+ case "text":
+ return FmtProtoText
+ case "compact-text":
+ return FmtProtoCompact
+ }
+ }
+ // Check for text format.
+ ver := ac.Params["version"]
+ if ac.Type == "text" && ac.SubType == "plain" && (ver == TextVersion || ver == "") {
+ return FmtText
+ }
+ }
+ return FmtText
+}
+
+// NewEncoder returns a new encoder based on content type negotiation.
+func NewEncoder(w io.Writer, format Format) Encoder {
+ switch format {
+ case FmtProtoDelim:
+ return encoder(func(v *dto.MetricFamily) error {
+ _, err := pbutil.WriteDelimited(w, v)
+ return err
+ })
+ case FmtProtoCompact:
+ return encoder(func(v *dto.MetricFamily) error {
+ _, err := fmt.Fprintln(w, v.String())
+ return err
+ })
+ case FmtProtoText:
+ return encoder(func(v *dto.MetricFamily) error {
+ _, err := fmt.Fprintln(w, proto.MarshalTextString(v))
+ return err
+ })
+ case FmtText:
+ return encoder(func(v *dto.MetricFamily) error {
+ _, err := MetricFamilyToText(w, v)
+ return err
+ })
+ }
+ panic("expfmt.NewEncoder: unknown format")
+}
diff --git a/vendor/github.com/prometheus/common/expfmt/expfmt.go b/vendor/github.com/prometheus/common/expfmt/expfmt.go
new file mode 100644
index 0000000..371ac75
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/expfmt.go
@@ -0,0 +1,38 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package expfmt contains tools for reading and writing Prometheus metrics.
+package expfmt
+
+// Format specifies the HTTP content type of the different wire protocols.
+type Format string
+
+// Constants to assemble the Content-Type values for the different wire protocols.
+const (
+ TextVersion = "0.0.4"
+ ProtoType = `application/vnd.google.protobuf`
+ ProtoProtocol = `io.prometheus.client.MetricFamily`
+ ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";"
+
+ // The Content-Type values for the different wire protocols.
+ FmtUnknown Format = ``
+ FmtText Format = `text/plain; version=` + TextVersion
+ FmtProtoDelim Format = ProtoFmt + ` encoding=delimited`
+ FmtProtoText Format = ProtoFmt + ` encoding=text`
+ FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text`
+)
+
+const (
+ hdrContentType = "Content-Type"
+ hdrAccept = "Accept"
+)
diff --git a/vendor/github.com/prometheus/client_golang/model/samplevalue.go b/vendor/github.com/prometheus/common/expfmt/fuzz.go
similarity index 51%
rename from vendor/github.com/prometheus/client_golang/model/samplevalue.go
rename to vendor/github.com/prometheus/common/expfmt/fuzz.go
index 469c2c0..dc2eede 100644
--- a/vendor/github.com/prometheus/client_golang/model/samplevalue.go
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz.go
@@ -1,4 +1,4 @@
-// Copyright 2013 The Prometheus Authors
+// Copyright 2014 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
@@ -11,27 +11,26 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-package model
+// Build only when actually fuzzing
+// +build gofuzz
-import (
- "fmt"
- "strconv"
-)
+package expfmt
-// A SampleValue is a representation of a value for a given sample at a given
-// time.
-type SampleValue float64
+import "bytes"
-// Equal does a straight v==o.
-func (v SampleValue) Equal(o SampleValue) bool {
- return v == o
-}
-
-// MarshalJSON implements json.Marshaler.
-func (v SampleValue) MarshalJSON() ([]byte, error) {
- return []byte(fmt.Sprintf(`"%s"`, v)), nil
-}
-
-func (v SampleValue) String() string {
- return strconv.FormatFloat(float64(v), 'f', -1, 64)
+// Fuzz text metric parser with with github.com/dvyukov/go-fuzz:
+//
+// go-fuzz-build github.com/prometheus/common/expfmt
+// go-fuzz -bin expfmt-fuzz.zip -workdir fuzz
+//
+// Further input samples should go in the folder fuzz/corpus.
+func Fuzz(in []byte) int {
+ parser := TextParser{}
+ _, err := parser.TextToMetricFamilies(bytes.NewReader(in))
+
+ if err != nil {
+ return 0
+ }
+
+ return 1
}
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_0 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_0
new file mode 100644
index 0000000..139597f
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_0
@@ -0,0 +1,2 @@
+
+
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_1 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_1
new file mode 100644
index 0000000..2ae8706
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_1
@@ -0,0 +1,6 @@
+
+minimal_metric 1.234
+another_metric -3e3 103948
+# Even that:
+no_labels{} 3
+# HELP line for non-existing metric will be ignored.
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_2 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_2
new file mode 100644
index 0000000..5c351db
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_2
@@ -0,0 +1,12 @@
+
+# A normal comment.
+#
+# TYPE name counter
+name{labelname="val1",basename="basevalue"} NaN
+name {labelname="val2",basename="base\"v\\al\nue"} 0.23 1234567890
+# HELP name two-line\n doc str\\ing
+
+ # HELP name2 doc str"ing 2
+ # TYPE name2 gauge
+name2{labelname="val2" ,basename = "basevalue2" } +Inf 54321
+name2{ labelname = "val1" , }-Inf
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_3 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_3
new file mode 100644
index 0000000..0b3c345
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_3
@@ -0,0 +1,22 @@
+
+# TYPE my_summary summary
+my_summary{n1="val1",quantile="0.5"} 110
+decoy -1 -2
+my_summary{n1="val1",quantile="0.9"} 140 1
+my_summary_count{n1="val1"} 42
+# Latest timestamp wins in case of a summary.
+my_summary_sum{n1="val1"} 4711 2
+fake_sum{n1="val1"} 2001
+# TYPE another_summary summary
+another_summary_count{n2="val2",n1="val1"} 20
+my_summary_count{n2="val2",n1="val1"} 5 5
+another_summary{n1="val1",n2="val2",quantile=".3"} -1.2
+my_summary_sum{n1="val2"} 08 15
+my_summary{n1="val3", quantile="0.2"} 4711
+ my_summary{n1="val1",n2="val2",quantile="-12.34",} NaN
+# some
+# funny comments
+# HELP
+# HELP
+# HELP my_summary
+# HELP my_summary
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_4 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_4
new file mode 100644
index 0000000..bde0a38
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_4
@@ -0,0 +1,10 @@
+
+# HELP request_duration_microseconds The response latency.
+# TYPE request_duration_microseconds histogram
+request_duration_microseconds_bucket{le="100"} 123
+request_duration_microseconds_bucket{le="120"} 412
+request_duration_microseconds_bucket{le="144"} 592
+request_duration_microseconds_bucket{le="172.8"} 1524
+request_duration_microseconds_bucket{le="+Inf"} 2693
+request_duration_microseconds_sum 1.7560473e+06
+request_duration_microseconds_count 2693
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_0 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_0
new file mode 100644
index 0000000..4c67f9a
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_0
@@ -0,0 +1 @@
+bla 3.14
\ No newline at end of file
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_1 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_1
new file mode 100644
index 0000000..b853478
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_1
@@ -0,0 +1 @@
+metric{label="\t"} 3.14
\ No newline at end of file
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_10 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_10
new file mode 100644
index 0000000..b5fe5f5
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_10
@@ -0,0 +1 @@
+metric{label="bla"} 3.14 2 3
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_11 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_11
new file mode 100644
index 0000000..57c7fbc
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_11
@@ -0,0 +1 @@
+metric{label="bla"} blubb
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_12 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_12
new file mode 100644
index 0000000..0a9df79
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_12
@@ -0,0 +1,3 @@
+
+# HELP metric one
+# HELP metric two
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_13 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_13
new file mode 100644
index 0000000..5bc7427
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_13
@@ -0,0 +1,3 @@
+
+# TYPE metric counter
+# TYPE metric untyped
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_14 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_14
new file mode 100644
index 0000000..a9a2426
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_14
@@ -0,0 +1,3 @@
+
+metric 4.12
+# TYPE metric counter
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_15 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_15
new file mode 100644
index 0000000..7e95ca8
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_15
@@ -0,0 +1,2 @@
+
+# TYPE metric bla
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_16 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_16
new file mode 100644
index 0000000..7825f88
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_16
@@ -0,0 +1,2 @@
+
+# TYPE met-ric
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_17 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_17
new file mode 100644
index 0000000..8f35cae
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_17
@@ -0,0 +1 @@
+@invalidmetric{label="bla"} 3.14 2
\ No newline at end of file
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_18 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_18
new file mode 100644
index 0000000..7ca2cc2
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_18
@@ -0,0 +1 @@
+{label="bla"} 3.14 2
\ No newline at end of file
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_19 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_19
new file mode 100644
index 0000000..7a6ccc0
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_19
@@ -0,0 +1,3 @@
+
+# TYPE metric histogram
+metric_bucket{le="bla"} 3.14
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_2 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_2
new file mode 100644
index 0000000..726d001
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_2
@@ -0,0 +1,3 @@
+
+metric{label="new
+line"} 3.14
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_3 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_3
new file mode 100644
index 0000000..6aa9e30
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_3
@@ -0,0 +1 @@
+metric{@="bla"} 3.14
\ No newline at end of file
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_4 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_4
new file mode 100644
index 0000000..d112cb9
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_4
@@ -0,0 +1 @@
+metric{__name__="bla"} 3.14
\ No newline at end of file
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_5 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_5
new file mode 100644
index 0000000..b34554a
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_5
@@ -0,0 +1 @@
+metric{label+="bla"} 3.14
\ No newline at end of file
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_6 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_6
new file mode 100644
index 0000000..c4d7df3
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_6
@@ -0,0 +1 @@
+metric{label=bla} 3.14
\ No newline at end of file
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_7 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_7
new file mode 100644
index 0000000..97eafc4
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_7
@@ -0,0 +1,3 @@
+
+# TYPE metric summary
+metric{quantile="bla"} 3.14
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_8 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_8
new file mode 100644
index 0000000..fc70649
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_8
@@ -0,0 +1 @@
+metric{label="bla"+} 3.14
\ No newline at end of file
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_9 b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_9
new file mode 100644
index 0000000..57b4879
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/from_test_parse_error_9
@@ -0,0 +1 @@
+metric{label="bla"} 3.14 2.72
diff --git a/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/minimal b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/minimal
new file mode 100644
index 0000000..be1e6a3
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/fuzz/corpus/minimal
@@ -0,0 +1 @@
+m{} 0
diff --git a/vendor/github.com/prometheus/common/expfmt/testdata/json2 b/vendor/github.com/prometheus/common/expfmt/testdata/json2
new file mode 100644
index 0000000..b914c93
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/testdata/json2
@@ -0,0 +1,46 @@
+[
+ {
+ "baseLabels": {
+ "__name__": "rpc_calls_total",
+ "job": "batch_job"
+ },
+ "docstring": "RPC calls.",
+ "metric": {
+ "type": "counter",
+ "value": [
+ {
+ "labels": {
+ "service": "zed"
+ },
+ "value": 25
+ },
+ {
+ "labels": {
+ "service": "bar"
+ },
+ "value": 24
+ }
+ ]
+ }
+ },
+ {
+ "baseLabels": {
+ "__name__": "rpc_latency_microseconds"
+ },
+ "docstring": "RPC latency.",
+ "metric": {
+ "type": "histogram",
+ "value": [
+ {
+ "labels": {
+ "service": "foo"
+ },
+ "value": {
+ "0.010000": 15,
+ "0.990000": 17
+ }
+ }
+ ]
+ }
+ }
+]
diff --git a/vendor/github.com/prometheus/common/expfmt/testdata/json2_bad b/vendor/github.com/prometheus/common/expfmt/testdata/json2_bad
new file mode 100644
index 0000000..cc6ac97
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/testdata/json2_bad
@@ -0,0 +1,46 @@
+[
+ {
+ "baseLabels": {
+ "__name__": "rpc_calls_total",
+ "job": "batch_job"
+ },
+ "docstring": "RPC calls.",
+ "metric": {
+ "type": "counter",
+ "value": [
+ {
+ "labels": {
+ "servic|e": "zed"
+ },
+ "value": 25
+ },
+ {
+ "labels": {
+ "service": "bar"
+ },
+ "value": 24
+ }
+ ]
+ }
+ },
+ {
+ "baseLabels": {
+ "__name__": "rpc_latency_microseconds"
+ },
+ "docstring": "RPC latency.",
+ "metric": {
+ "type": "histogram",
+ "value": [
+ {
+ "labels": {
+ "service": "foo"
+ },
+ "value": {
+ "0.010000": 15,
+ "0.990000": 17
+ }
+ }
+ ]
+ }
+ }
+]
diff --git a/vendor/github.com/prometheus/common/expfmt/testdata/protobuf b/vendor/github.com/prometheus/common/expfmt/testdata/protobuf
new file mode 100644
index 0000000..b2d018a
Binary files /dev/null and b/vendor/github.com/prometheus/common/expfmt/testdata/protobuf differ
diff --git a/vendor/github.com/prometheus/common/expfmt/testdata/protobuf.gz b/vendor/github.com/prometheus/common/expfmt/testdata/protobuf.gz
new file mode 100644
index 0000000..7622adb
Binary files /dev/null and b/vendor/github.com/prometheus/common/expfmt/testdata/protobuf.gz differ
diff --git a/vendor/github.com/prometheus/common/expfmt/testdata/text b/vendor/github.com/prometheus/common/expfmt/testdata/text
new file mode 100644
index 0000000..f3d8c37
--- /dev/null
+++ b/vendor/github.com/prometheus/common/expfmt/testdata/text
@@ -0,0 +1,322 @@
+# HELP http_request_duration_microseconds The HTTP request latencies in microseconds.
+# TYPE http_request_duration_microseconds summary
+http_request_duration_microseconds{handler="/",quantile="0.5"} 0
+http_request_duration_microseconds{handler="/",quantile="0.9"} 0
+http_request_duration_microseconds{handler="/",quantile="0.99"} 0
+http_request_duration_microseconds_sum{handler="/"} 0
+http_request_duration_microseconds_count{handler="/"} 0
+http_request_duration_microseconds{handler="/alerts",quantile="0.5"} 0
+http_request_duration_microseconds{handler="/alerts",quantile="0.9"} 0
+http_request_duration_microseconds{handler="/alerts",quantile="0.99"} 0
+http_request_duration_microseconds_sum{handler="/alerts"} 0
+http_request_duration_microseconds_count{handler="/alerts"} 0
+http_request_duration_microseconds{handler="/api/metrics",quantile="0.5"} 0
+http_request_duration_microseconds{handler="/api/metrics",quantile="0.9"} 0
+http_request_duration_microseconds{handler="/api/metrics",quantile="0.99"} 0
+http_request_duration_microseconds_sum{handler="/api/metrics"} 0
+http_request_duration_microseconds_count{handler="/api/metrics"} 0
+http_request_duration_microseconds{handler="/api/query",quantile="0.5"} 0
+http_request_duration_microseconds{handler="/api/query",quantile="0.9"} 0
+http_request_duration_microseconds{handler="/api/query",quantile="0.99"} 0
+http_request_duration_microseconds_sum{handler="/api/query"} 0
+http_request_duration_microseconds_count{handler="/api/query"} 0
+http_request_duration_microseconds{handler="/api/query_range",quantile="0.5"} 0
+http_request_duration_microseconds{handler="/api/query_range",quantile="0.9"} 0
+http_request_duration_microseconds{handler="/api/query_range",quantile="0.99"} 0
+http_request_duration_microseconds_sum{handler="/api/query_range"} 0
+http_request_duration_microseconds_count{handler="/api/query_range"} 0
+http_request_duration_microseconds{handler="/api/targets",quantile="0.5"} 0
+http_request_duration_microseconds{handler="/api/targets",quantile="0.9"} 0
+http_request_duration_microseconds{handler="/api/targets",quantile="0.99"} 0
+http_request_duration_microseconds_sum{handler="/api/targets"} 0
+http_request_duration_microseconds_count{handler="/api/targets"} 0
+http_request_duration_microseconds{handler="/consoles/",quantile="0.5"} 0
+http_request_duration_microseconds{handler="/consoles/",quantile="0.9"} 0
+http_request_duration_microseconds{handler="/consoles/",quantile="0.99"} 0
+http_request_duration_microseconds_sum{handler="/consoles/"} 0
+http_request_duration_microseconds_count{handler="/consoles/"} 0
+http_request_duration_microseconds{handler="/graph",quantile="0.5"} 0
+http_request_duration_microseconds{handler="/graph",quantile="0.9"} 0
+http_request_duration_microseconds{handler="/graph",quantile="0.99"} 0
+http_request_duration_microseconds_sum{handler="/graph"} 0
+http_request_duration_microseconds_count{handler="/graph"} 0
+http_request_duration_microseconds{handler="/heap",quantile="0.5"} 0
+http_request_duration_microseconds{handler="/heap",quantile="0.9"} 0
+http_request_duration_microseconds{handler="/heap",quantile="0.99"} 0
+http_request_duration_microseconds_sum{handler="/heap"} 0
+http_request_duration_microseconds_count{handler="/heap"} 0
+http_request_duration_microseconds{handler="/static/",quantile="0.5"} 0
+http_request_duration_microseconds{handler="/static/",quantile="0.9"} 0
+http_request_duration_microseconds{handler="/static/",quantile="0.99"} 0
+http_request_duration_microseconds_sum{handler="/static/"} 0
+http_request_duration_microseconds_count{handler="/static/"} 0
+http_request_duration_microseconds{handler="prometheus",quantile="0.5"} 1307.275
+http_request_duration_microseconds{handler="prometheus",quantile="0.9"} 1858.632
+http_request_duration_microseconds{handler="prometheus",quantile="0.99"} 3087.384
+http_request_duration_microseconds_sum{handler="prometheus"} 179886.5000000001
+http_request_duration_microseconds_count{handler="prometheus"} 119
+# HELP http_request_size_bytes The HTTP request sizes in bytes.
+# TYPE http_request_size_bytes summary
+http_request_size_bytes{handler="/",quantile="0.5"} 0
+http_request_size_bytes{handler="/",quantile="0.9"} 0
+http_request_size_bytes{handler="/",quantile="0.99"} 0
+http_request_size_bytes_sum{handler="/"} 0
+http_request_size_bytes_count{handler="/"} 0
+http_request_size_bytes{handler="/alerts",quantile="0.5"} 0
+http_request_size_bytes{handler="/alerts",quantile="0.9"} 0
+http_request_size_bytes{handler="/alerts",quantile="0.99"} 0
+http_request_size_bytes_sum{handler="/alerts"} 0
+http_request_size_bytes_count{handler="/alerts"} 0
+http_request_size_bytes{handler="/api/metrics",quantile="0.5"} 0
+http_request_size_bytes{handler="/api/metrics",quantile="0.9"} 0
+http_request_size_bytes{handler="/api/metrics",quantile="0.99"} 0
+http_request_size_bytes_sum{handler="/api/metrics"} 0
+http_request_size_bytes_count{handler="/api/metrics"} 0
+http_request_size_bytes{handler="/api/query",quantile="0.5"} 0
+http_request_size_bytes{handler="/api/query",quantile="0.9"} 0
+http_request_size_bytes{handler="/api/query",quantile="0.99"} 0
+http_request_size_bytes_sum{handler="/api/query"} 0
+http_request_size_bytes_count{handler="/api/query"} 0
+http_request_size_bytes{handler="/api/query_range",quantile="0.5"} 0
+http_request_size_bytes{handler="/api/query_range",quantile="0.9"} 0
+http_request_size_bytes{handler="/api/query_range",quantile="0.99"} 0
+http_request_size_bytes_sum{handler="/api/query_range"} 0
+http_request_size_bytes_count{handler="/api/query_range"} 0
+http_request_size_bytes{handler="/api/targets",quantile="0.5"} 0
+http_request_size_bytes{handler="/api/targets",quantile="0.9"} 0
+http_request_size_bytes{handler="/api/targets",quantile="0.99"} 0
+http_request_size_bytes_sum{handler="/api/targets"} 0
+http_request_size_bytes_count{handler="/api/targets"} 0
+http_request_size_bytes{handler="/consoles/",quantile="0.5"} 0
+http_request_size_bytes{handler="/consoles/",quantile="0.9"} 0
+http_request_size_bytes{handler="/consoles/",quantile="0.99"} 0
+http_request_size_bytes_sum{handler="/consoles/"} 0
+http_request_size_bytes_count{handler="/consoles/"} 0
+http_request_size_bytes{handler="/graph",quantile="0.5"} 0
+http_request_size_bytes{handler="/graph",quantile="0.9"} 0
+http_request_size_bytes{handler="/graph",quantile="0.99"} 0
+http_request_size_bytes_sum{handler="/graph"} 0
+http_request_size_bytes_count{handler="/graph"} 0
+http_request_size_bytes{handler="/heap",quantile="0.5"} 0
+http_request_size_bytes{handler="/heap",quantile="0.9"} 0
+http_request_size_bytes{handler="/heap",quantile="0.99"} 0
+http_request_size_bytes_sum{handler="/heap"} 0
+http_request_size_bytes_count{handler="/heap"} 0
+http_request_size_bytes{handler="/static/",quantile="0.5"} 0
+http_request_size_bytes{handler="/static/",quantile="0.9"} 0
+http_request_size_bytes{handler="/static/",quantile="0.99"} 0
+http_request_size_bytes_sum{handler="/static/"} 0
+http_request_size_bytes_count{handler="/static/"} 0
+http_request_size_bytes{handler="prometheus",quantile="0.5"} 291
+http_request_size_bytes{handler="prometheus",quantile="0.9"} 291
+http_request_size_bytes{handler="prometheus",quantile="0.99"} 291
+http_request_size_bytes_sum{handler="prometheus"} 34488
+http_request_size_bytes_count{handler="prometheus"} 119
+# HELP http_requests_total Total number of HTTP requests made.
+# TYPE http_requests_total counter
+http_requests_total{code="200",handler="prometheus",method="get"} 119
+# HELP http_response_size_bytes The HTTP response sizes in bytes.
+# TYPE http_response_size_bytes summary
+http_response_size_bytes{handler="/",quantile="0.5"} 0
+http_response_size_bytes{handler="/",quantile="0.9"} 0
+http_response_size_bytes{handler="/",quantile="0.99"} 0
+http_response_size_bytes_sum{handler="/"} 0
+http_response_size_bytes_count{handler="/"} 0
+http_response_size_bytes{handler="/alerts",quantile="0.5"} 0
+http_response_size_bytes{handler="/alerts",quantile="0.9"} 0
+http_response_size_bytes{handler="/alerts",quantile="0.99"} 0
+http_response_size_bytes_sum{handler="/alerts"} 0
+http_response_size_bytes_count{handler="/alerts"} 0
+http_response_size_bytes{handler="/api/metrics",quantile="0.5"} 0
+http_response_size_bytes{handler="/api/metrics",quantile="0.9"} 0
+http_response_size_bytes{handler="/api/metrics",quantile="0.99"} 0
+http_response_size_bytes_sum{handler="/api/metrics"} 0
+http_response_size_bytes_count{handler="/api/metrics"} 0
+http_response_size_bytes{handler="/api/query",quantile="0.5"} 0
+http_response_size_bytes{handler="/api/query",quantile="0.9"} 0
+http_response_size_bytes{handler="/api/query",quantile="0.99"} 0
+http_response_size_bytes_sum{handler="/api/query"} 0
+http_response_size_bytes_count{handler="/api/query"} 0
+http_response_size_bytes{handler="/api/query_range",quantile="0.5"} 0
+http_response_size_bytes{handler="/api/query_range",quantile="0.9"} 0
+http_response_size_bytes{handler="/api/query_range",quantile="0.99"} 0
+http_response_size_bytes_sum{handler="/api/query_range"} 0
+http_response_size_bytes_count{handler="/api/query_range"} 0
+http_response_size_bytes{handler="/api/targets",quantile="0.5"} 0
+http_response_size_bytes{handler="/api/targets",quantile="0.9"} 0
+http_response_size_bytes{handler="/api/targets",quantile="0.99"} 0
+http_response_size_bytes_sum{handler="/api/targets"} 0
+http_response_size_bytes_count{handler="/api/targets"} 0
+http_response_size_bytes{handler="/consoles/",quantile="0.5"} 0
+http_response_size_bytes{handler="/consoles/",quantile="0.9"} 0
+http_response_size_bytes{handler="/consoles/",quantile="0.99"} 0
+http_response_size_bytes_sum{handler="/consoles/"} 0
+http_response_size_bytes_count{handler="/consoles/"} 0
+http_response_size_bytes{handler="/graph",quantile="0.5"} 0
+http_response_size_bytes{handler="/graph",quantile="0.9"} 0
+http_response_size_bytes{handler="/graph",quantile="0.99"} 0
+http_response_size_bytes_sum{handler="/graph"} 0
+http_response_size_bytes_count{handler="/graph"} 0
+http_response_size_bytes{handler="/heap",quantile="0.5"} 0
+http_response_size_bytes{handler="/heap",quantile="0.9"} 0
+http_response_size_bytes{handler="/heap",quantile="0.99"} 0
+http_response_size_bytes_sum{handler="/heap"} 0
+http_response_size_bytes_count{handler="/heap"} 0
+http_response_size_bytes{handler="/static/",quantile="0.5"} 0
+http_response_size_bytes{handler="/static/",quantile="0.9"} 0
+http_response_size_bytes{handler="/static/",quantile="0.99"} 0
+http_response_size_bytes_sum{handler="/static/"} 0
+http_response_size_bytes_count{handler="/static/"} 0
+http_response_size_bytes{handler="prometheus",quantile="0.5"} 2049
+http_response_size_bytes{handler="prometheus",quantile="0.9"} 2058
+http_response_size_bytes{handler="prometheus",quantile="0.99"} 2064
+http_response_size_bytes_sum{handler="prometheus"} 247001
+http_response_size_bytes_count{handler="prometheus"} 119
+# HELP process_cpu_seconds_total Total user and system CPU time spent in seconds.
+# TYPE process_cpu_seconds_total counter
+process_cpu_seconds_total 0.55
+# HELP go_goroutines Number of goroutines that currently exist.
+# TYPE go_goroutines gauge
+go_goroutines 70
+# HELP process_max_fds Maximum number of open file descriptors.
+# TYPE process_max_fds gauge
+process_max_fds 8192
+# HELP process_open_fds Number of open file descriptors.
+# TYPE process_open_fds gauge
+process_open_fds 29
+# HELP process_resident_memory_bytes Resident memory size in bytes.
+# TYPE process_resident_memory_bytes gauge
+process_resident_memory_bytes 5.3870592e+07
+# HELP process_start_time_seconds Start time of the process since unix epoch in seconds.
+# TYPE process_start_time_seconds gauge
+process_start_time_seconds 1.42236894836e+09
+# HELP process_virtual_memory_bytes Virtual memory size in bytes.
+# TYPE process_virtual_memory_bytes gauge
+process_virtual_memory_bytes 5.41478912e+08
+# HELP prometheus_dns_sd_lookup_failures_total The number of DNS-SD lookup failures.
+# TYPE prometheus_dns_sd_lookup_failures_total counter
+prometheus_dns_sd_lookup_failures_total 0
+# HELP prometheus_dns_sd_lookups_total The number of DNS-SD lookups.
+# TYPE prometheus_dns_sd_lookups_total counter
+prometheus_dns_sd_lookups_total 7
+# HELP prometheus_evaluator_duration_milliseconds The duration for all evaluations to execute.
+# TYPE prometheus_evaluator_duration_milliseconds summary
+prometheus_evaluator_duration_milliseconds{quantile="0.01"} 0
+prometheus_evaluator_duration_milliseconds{quantile="0.05"} 0
+prometheus_evaluator_duration_milliseconds{quantile="0.5"} 0
+prometheus_evaluator_duration_milliseconds{quantile="0.9"} 1
+prometheus_evaluator_duration_milliseconds{quantile="0.99"} 1
+prometheus_evaluator_duration_milliseconds_sum 12
+prometheus_evaluator_duration_milliseconds_count 23
+# HELP prometheus_local_storage_checkpoint_duration_milliseconds The duration (in milliseconds) it took to checkpoint in-memory metrics and head chunks.
+# TYPE prometheus_local_storage_checkpoint_duration_milliseconds gauge
+prometheus_local_storage_checkpoint_duration_milliseconds 0
+# HELP prometheus_local_storage_chunk_ops_total The total number of chunk operations by their type.
+# TYPE prometheus_local_storage_chunk_ops_total counter
+prometheus_local_storage_chunk_ops_total{type="create"} 598
+prometheus_local_storage_chunk_ops_total{type="persist"} 174
+prometheus_local_storage_chunk_ops_total{type="pin"} 920
+prometheus_local_storage_chunk_ops_total{type="transcode"} 415
+prometheus_local_storage_chunk_ops_total{type="unpin"} 920
+# HELP prometheus_local_storage_indexing_batch_latency_milliseconds Quantiles for batch indexing latencies in milliseconds.
+# TYPE prometheus_local_storage_indexing_batch_latency_milliseconds summary
+prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.5"} 0
+prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.9"} 0
+prometheus_local_storage_indexing_batch_latency_milliseconds{quantile="0.99"} 0
+prometheus_local_storage_indexing_batch_latency_milliseconds_sum 0
+prometheus_local_storage_indexing_batch_latency_milliseconds_count 1
+# HELP prometheus_local_storage_indexing_batch_sizes Quantiles for indexing batch sizes (number of metrics per batch).
+# TYPE prometheus_local_storage_indexing_batch_sizes summary
+prometheus_local_storage_indexing_batch_sizes{quantile="0.5"} 2
+prometheus_local_storage_indexing_batch_sizes{quantile="0.9"} 2
+prometheus_local_storage_indexing_batch_sizes{quantile="0.99"} 2
+prometheus_local_storage_indexing_batch_sizes_sum 2
+prometheus_local_storage_indexing_batch_sizes_count 1
+# HELP prometheus_local_storage_indexing_queue_capacity The capacity of the indexing queue.
+# TYPE prometheus_local_storage_indexing_queue_capacity gauge
+prometheus_local_storage_indexing_queue_capacity 16384
+# HELP prometheus_local_storage_indexing_queue_length The number of metrics waiting to be indexed.
+# TYPE prometheus_local_storage_indexing_queue_length gauge
+prometheus_local_storage_indexing_queue_length 0
+# HELP prometheus_local_storage_ingested_samples_total The total number of samples ingested.
+# TYPE prometheus_local_storage_ingested_samples_total counter
+prometheus_local_storage_ingested_samples_total 30473
+# HELP prometheus_local_storage_invalid_preload_requests_total The total number of preload requests referring to a non-existent series. This is an indication of outdated label indexes.
+# TYPE prometheus_local_storage_invalid_preload_requests_total counter
+prometheus_local_storage_invalid_preload_requests_total 0
+# HELP prometheus_local_storage_memory_chunkdescs The current number of chunk descriptors in memory.
+# TYPE prometheus_local_storage_memory_chunkdescs gauge
+prometheus_local_storage_memory_chunkdescs 1059
+# HELP prometheus_local_storage_memory_chunks The current number of chunks in memory, excluding cloned chunks (i.e. chunks without a descriptor).
+# TYPE prometheus_local_storage_memory_chunks gauge
+prometheus_local_storage_memory_chunks 1020
+# HELP prometheus_local_storage_memory_series The current number of series in memory.
+# TYPE prometheus_local_storage_memory_series gauge
+prometheus_local_storage_memory_series 424
+# HELP prometheus_local_storage_persist_latency_microseconds A summary of latencies for persisting each chunk.
+# TYPE prometheus_local_storage_persist_latency_microseconds summary
+prometheus_local_storage_persist_latency_microseconds{quantile="0.5"} 30.377
+prometheus_local_storage_persist_latency_microseconds{quantile="0.9"} 203.539
+prometheus_local_storage_persist_latency_microseconds{quantile="0.99"} 2626.463
+prometheus_local_storage_persist_latency_microseconds_sum 20424.415
+prometheus_local_storage_persist_latency_microseconds_count 174
+# HELP prometheus_local_storage_persist_queue_capacity The total capacity of the persist queue.
+# TYPE prometheus_local_storage_persist_queue_capacity gauge
+prometheus_local_storage_persist_queue_capacity 1024
+# HELP prometheus_local_storage_persist_queue_length The current number of chunks waiting in the persist queue.
+# TYPE prometheus_local_storage_persist_queue_length gauge
+prometheus_local_storage_persist_queue_length 0
+# HELP prometheus_local_storage_series_ops_total The total number of series operations by their type.
+# TYPE prometheus_local_storage_series_ops_total counter
+prometheus_local_storage_series_ops_total{type="create"} 2
+prometheus_local_storage_series_ops_total{type="maintenance_in_memory"} 11
+# HELP prometheus_notifications_latency_milliseconds Latency quantiles for sending alert notifications (not including dropped notifications).
+# TYPE prometheus_notifications_latency_milliseconds summary
+prometheus_notifications_latency_milliseconds{quantile="0.5"} 0
+prometheus_notifications_latency_milliseconds{quantile="0.9"} 0
+prometheus_notifications_latency_milliseconds{quantile="0.99"} 0
+prometheus_notifications_latency_milliseconds_sum 0
+prometheus_notifications_latency_milliseconds_count 0
+# HELP prometheus_notifications_queue_capacity The capacity of the alert notifications queue.
+# TYPE prometheus_notifications_queue_capacity gauge
+prometheus_notifications_queue_capacity 100
+# HELP prometheus_notifications_queue_length The number of alert notifications in the queue.
+# TYPE prometheus_notifications_queue_length gauge
+prometheus_notifications_queue_length 0
+# HELP prometheus_rule_evaluation_duration_milliseconds The duration for a rule to execute.
+# TYPE prometheus_rule_evaluation_duration_milliseconds summary
+prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.5"} 0
+prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.9"} 0
+prometheus_rule_evaluation_duration_milliseconds{rule_type="alerting",quantile="0.99"} 2
+prometheus_rule_evaluation_duration_milliseconds_sum{rule_type="alerting"} 12
+prometheus_rule_evaluation_duration_milliseconds_count{rule_type="alerting"} 115
+prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.5"} 0
+prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.9"} 0
+prometheus_rule_evaluation_duration_milliseconds{rule_type="recording",quantile="0.99"} 3
+prometheus_rule_evaluation_duration_milliseconds_sum{rule_type="recording"} 15
+prometheus_rule_evaluation_duration_milliseconds_count{rule_type="recording"} 115
+# HELP prometheus_rule_evaluation_failures_total The total number of rule evaluation failures.
+# TYPE prometheus_rule_evaluation_failures_total counter
+prometheus_rule_evaluation_failures_total 0
+# HELP prometheus_samples_queue_capacity Capacity of the queue for unwritten samples.
+# TYPE prometheus_samples_queue_capacity gauge
+prometheus_samples_queue_capacity 4096
+# HELP prometheus_samples_queue_length Current number of items in the queue for unwritten samples. Each item comprises all samples exposed by one target as one metric family (i.e. metrics of the same name).
+# TYPE prometheus_samples_queue_length gauge
+prometheus_samples_queue_length 0
+# HELP prometheus_target_interval_length_seconds Actual intervals between scrapes.
+# TYPE prometheus_target_interval_length_seconds summary
+prometheus_target_interval_length_seconds{interval="15s",quantile="0.01"} 14
+prometheus_target_interval_length_seconds{interval="15s",quantile="0.05"} 14
+prometheus_target_interval_length_seconds{interval="15s",quantile="0.5"} 15
+prometheus_target_interval_length_seconds{interval="15s",quantile="0.9"} 15
+prometheus_target_interval_length_seconds{interval="15s",quantile="0.99"} 15
+prometheus_target_interval_length_seconds_sum{interval="15s"} 175
+prometheus_target_interval_length_seconds_count{interval="15s"} 12
+prometheus_target_interval_length_seconds{interval="1s",quantile="0.01"} 0
+prometheus_target_interval_length_seconds{interval="1s",quantile="0.05"} 0
+prometheus_target_interval_length_seconds{interval="1s",quantile="0.5"} 0
+prometheus_target_interval_length_seconds{interval="1s",quantile="0.9"} 1
+prometheus_target_interval_length_seconds{interval="1s",quantile="0.99"} 1
+prometheus_target_interval_length_seconds_sum{interval="1s"} 55
+prometheus_target_interval_length_seconds_count{interval="1s"} 117
diff --git a/vendor/github.com/prometheus/common/expfmt/testdata/text.gz b/vendor/github.com/prometheus/common/expfmt/testdata/text.gz
new file mode 100644
index 0000000..b7658c8
Binary files /dev/null and b/vendor/github.com/prometheus/common/expfmt/testdata/text.gz differ
diff --git a/vendor/github.com/prometheus/client_golang/text/create.go b/vendor/github.com/prometheus/common/expfmt/text_create.go
similarity index 86%
rename from vendor/github.com/prometheus/client_golang/text/create.go
rename to vendor/github.com/prometheus/common/expfmt/text_create.go
index 57def32..f11321c 100644
--- a/vendor/github.com/prometheus/client_golang/text/create.go
+++ b/vendor/github.com/prometheus/common/expfmt/text_create.go
@@ -11,31 +11,26 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-// Package text contains helper functions to parse and create text-based
-// exchange formats. The package currently supports (only) version 0.0.4 of the
-// exchange format. Should other versions be supported in the future, some
-// versioning scheme has to be applied. Possibilities include separate packages
-// or separate functions. The best way depends on the nature of future changes,
-// which is the reason why no versioning scheme has been applied prematurely
-// here.
-package text
+package expfmt
import (
- "bytes"
"fmt"
"io"
"math"
"strings"
- "github.com/prometheus/client_golang/model"
dto "github.com/prometheus/client_model/go"
+ "github.com/prometheus/common/model"
)
// MetricFamilyToText converts a MetricFamily proto message into text format and
// writes the resulting lines to 'out'. It returns the number of bytes written
-// and any error encountered. This function does not perform checks on the
-// content of the metric and label names, i.e. invalid metric or label names
+// and any error encountered. The output will have the same order as the input,
+// no further sorting is performed. Furthermore, this function assumes the input
+// is already sanitized and does not perform any sanity checks. If the input
+// contains duplicate metrics or invalid metric or label names, the conversion
// will result in invalid text format output.
+//
// This method fulfills the type 'prometheus.encoder'.
func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error) {
var written int
@@ -48,9 +43,6 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error) {
if name == "" {
return written, fmt.Errorf("MetricFamily has no name: %s", in)
}
- if in.Type == nil {
- return written, fmt.Errorf("MetricFamily has no type: %s", in)
- }
// Comments, first HELP, then TYPE.
if in.Help != nil {
@@ -295,21 +287,17 @@ func labelPairsToText(
return written, nil
}
+var (
+ escape = strings.NewReplacer("\\", `\\`, "\n", `\n`)
+ escapeWithDoubleQuote = strings.NewReplacer("\\", `\\`, "\n", `\n`, "\"", `\"`)
+)
+
// escapeString replaces '\' by '\\', new line character by '\n', and - if
// includeDoubleQuote is true - '"' by '\"'.
func escapeString(v string, includeDoubleQuote bool) string {
- result := bytes.NewBuffer(make([]byte, 0, len(v)))
- for _, c := range v {
- switch {
- case c == '\\':
- result.WriteString(`\\`)
- case includeDoubleQuote && c == '"':
- result.WriteString(`\"`)
- case c == '\n':
- result.WriteString(`\n`)
- default:
- result.WriteRune(c)
- }
+ if includeDoubleQuote {
+ return escapeWithDoubleQuote.Replace(v)
}
- return result.String()
+
+ return escape.Replace(v)
}
diff --git a/vendor/github.com/prometheus/client_golang/text/create_test.go b/vendor/github.com/prometheus/common/expfmt/text_create_test.go
similarity index 98%
rename from vendor/github.com/prometheus/client_golang/text/create_test.go
rename to vendor/github.com/prometheus/common/expfmt/text_create_test.go
index fe938de..e4cc5d8 100644
--- a/vendor/github.com/prometheus/client_golang/text/create_test.go
+++ b/vendor/github.com/prometheus/common/expfmt/text_create_test.go
@@ -11,7 +11,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-package text
+package expfmt
import (
"bytes"
@@ -20,6 +20,7 @@ import (
"testing"
"github.com/golang/protobuf/proto"
+
dto "github.com/prometheus/client_model/go"
)
@@ -311,6 +312,24 @@ request_duration_microseconds_bucket{le="172.8"} 1524
request_duration_microseconds_bucket{le="+Inf"} 2693
request_duration_microseconds_sum 1.7560473e+06
request_duration_microseconds_count 2693
+`,
+ },
+ // 6: No metric type, should result in default type Counter.
+ {
+ in: &dto.MetricFamily{
+ Name: proto.String("name"),
+ Help: proto.String("doc string"),
+ Metric: []*dto.Metric{
+ &dto.Metric{
+ Counter: &dto.Counter{
+ Value: proto.Float64(math.Inf(-1)),
+ },
+ },
+ },
+ },
+ out: `# HELP name doc string
+# TYPE name counter
+name -Inf
`,
},
}
@@ -378,22 +397,7 @@ func testCreateError(t testing.TB) {
},
err: "MetricFamily has no name",
},
- // 2: No metric type.
- {
- in: &dto.MetricFamily{
- Name: proto.String("name"),
- Help: proto.String("doc string"),
- Metric: []*dto.Metric{
- &dto.Metric{
- Untyped: &dto.Untyped{
- Value: proto.Float64(math.Inf(-1)),
- },
- },
- },
- },
- err: "MetricFamily has no type",
- },
- // 3: Wrong type.
+ // 2: Wrong type.
{
in: &dto.MetricFamily{
Name: proto.String("name"),
diff --git a/vendor/github.com/prometheus/client_golang/text/parse.go b/vendor/github.com/prometheus/common/expfmt/text_parse.go
similarity index 93%
rename from vendor/github.com/prometheus/client_golang/text/parse.go
rename to vendor/github.com/prometheus/common/expfmt/text_parse.go
index 2f337a8..54bcfde 100644
--- a/vendor/github.com/prometheus/client_golang/text/parse.go
+++ b/vendor/github.com/prometheus/common/expfmt/text_parse.go
@@ -11,7 +11,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-package text
+package expfmt
import (
"bufio"
@@ -25,7 +25,7 @@ import (
dto "github.com/prometheus/client_model/go"
"github.com/golang/protobuf/proto"
- "github.com/prometheus/client_golang/model"
+ "github.com/prometheus/common/model"
)
// A stateFn is a function that represents a state in a state machine. By
@@ -46,9 +46,9 @@ func (e ParseError) Error() string {
return fmt.Sprintf("text format parsing error in line %d: %s", e.Line, e.Msg)
}
-// Parser is used to parse the simple and flat text-based exchange format. Its
-// nil value is ready to use.
-type Parser struct {
+// TextParser is used to parse the simple and flat text-based exchange format. Its
+// zero value is ready to use.
+type TextParser struct {
metricFamiliesByName map[string]*dto.MetricFamily
buf *bufio.Reader // Where the parsed input is read through.
err error // Most recent error.
@@ -97,7 +97,7 @@ type Parser struct {
//
// This method must not be called concurrently. If you want to parse different
// input concurrently, instantiate a separate Parser for each goroutine.
-func (p *Parser) TextToMetricFamilies(in io.Reader) (map[string]*dto.MetricFamily, error) {
+func (p *TextParser) TextToMetricFamilies(in io.Reader) (map[string]*dto.MetricFamily, error) {
p.reset(in)
for nextState := p.startOfLine; nextState != nil; nextState = nextState() {
// Magic happens here...
@@ -108,10 +108,17 @@ func (p *Parser) TextToMetricFamilies(in io.Reader) (map[string]*dto.MetricFamil
delete(p.metricFamiliesByName, k)
}
}
+ // If p.err is io.EOF now, we have run into a premature end of the input
+ // stream. Turn this error into something nicer and more
+ // meaningful. (io.EOF is often used as a signal for the legitimate end
+ // of an input stream.)
+ if p.err == io.EOF {
+ p.parseError("unexpected end of input stream")
+ }
return p.metricFamiliesByName, p.err
}
-func (p *Parser) reset(in io.Reader) {
+func (p *TextParser) reset(in io.Reader) {
p.metricFamiliesByName = map[string]*dto.MetricFamily{}
if p.buf == nil {
p.buf = bufio.NewReader(in)
@@ -132,7 +139,7 @@ func (p *Parser) reset(in io.Reader) {
// startOfLine represents the state where the next byte read from p.buf is the
// start of a line (or whitespace leading up to it).
-func (p *Parser) startOfLine() stateFn {
+func (p *TextParser) startOfLine() stateFn {
p.lineCount++
if p.skipBlankTab(); p.err != nil {
// End of input reached. This is the only case where
@@ -151,7 +158,7 @@ func (p *Parser) startOfLine() stateFn {
// startComment represents the state where the next byte read from p.buf is the
// start of a comment (or whitespace leading up to it).
-func (p *Parser) startComment() stateFn {
+func (p *TextParser) startComment() stateFn {
if p.skipBlankTab(); p.err != nil {
return nil // Unexpected end of input.
}
@@ -212,7 +219,7 @@ func (p *Parser) startComment() stateFn {
// readingMetricName represents the state where the last byte read (now in
// p.currentByte) is the first byte of a metric name.
-func (p *Parser) readingMetricName() stateFn {
+func (p *TextParser) readingMetricName() stateFn {
if p.readTokenAsMetricName(); p.err != nil {
return nil
}
@@ -239,7 +246,7 @@ func (p *Parser) readingMetricName() stateFn {
// readingLabels represents the state where the last byte read (now in
// p.currentByte) is either the first byte of the label set (i.e. a '{'), or the
// first byte of the value (otherwise).
-func (p *Parser) readingLabels() stateFn {
+func (p *TextParser) readingLabels() stateFn {
// Summaries/histograms are special. We have to reset the
// currentLabels map, currentQuantile and currentBucket before starting to
// read labels.
@@ -257,7 +264,7 @@ func (p *Parser) readingLabels() stateFn {
// startLabelName represents the state where the next byte read from p.buf is
// the start of a label name (or whitespace leading up to it).
-func (p *Parser) startLabelName() stateFn {
+func (p *TextParser) startLabelName() stateFn {
if p.skipBlankTab(); p.err != nil {
return nil // Unexpected end of input.
}
@@ -297,7 +304,7 @@ func (p *Parser) startLabelName() stateFn {
// startLabelValue represents the state where the next byte read from p.buf is
// the start of a (quoted) label value (or whitespace leading up to it).
-func (p *Parser) startLabelValue() stateFn {
+func (p *TextParser) startLabelValue() stateFn {
if p.skipBlankTab(); p.err != nil {
return nil // Unexpected end of input.
}
@@ -308,6 +315,10 @@ func (p *Parser) startLabelValue() stateFn {
if p.readTokenAsLabelValue(); p.err != nil {
return nil
}
+ if !model.LabelValue(p.currentToken.String()).IsValid() {
+ p.parseError(fmt.Sprintf("invalid label value %q", p.currentToken.String()))
+ return nil
+ }
p.currentLabelPair.Value = proto.String(p.currentToken.String())
// Special treatment of summaries:
// - Quantile labels are special, will result in dto.Quantile later.
@@ -355,7 +366,7 @@ func (p *Parser) startLabelValue() stateFn {
// readingValue represents the state where the last byte read (now in
// p.currentByte) is the first byte of the sample value (i.e. a float).
-func (p *Parser) readingValue() stateFn {
+func (p *TextParser) readingValue() stateFn {
// When we are here, we have read all the labels, so for the
// special case of a summary/histogram, we can finally find out
// if the metric already exists.
@@ -443,7 +454,7 @@ func (p *Parser) readingValue() stateFn {
// startTimestamp represents the state where the next byte read from p.buf is
// the start of the timestamp (or whitespace leading up to it).
-func (p *Parser) startTimestamp() stateFn {
+func (p *TextParser) startTimestamp() stateFn {
if p.skipBlankTab(); p.err != nil {
return nil // Unexpected end of input.
}
@@ -469,7 +480,7 @@ func (p *Parser) startTimestamp() stateFn {
// readingHelp represents the state where the last byte read (now in
// p.currentByte) is the first byte of the docstring after 'HELP'.
-func (p *Parser) readingHelp() stateFn {
+func (p *TextParser) readingHelp() stateFn {
if p.currentMF.Help != nil {
p.parseError(fmt.Sprintf("second HELP line for metric name %q", p.currentMF.GetName()))
return nil
@@ -484,7 +495,7 @@ func (p *Parser) readingHelp() stateFn {
// readingType represents the state where the last byte read (now in
// p.currentByte) is the first byte of the type hint after 'HELP'.
-func (p *Parser) readingType() stateFn {
+func (p *TextParser) readingType() stateFn {
if p.currentMF.Type != nil {
p.parseError(fmt.Sprintf("second TYPE line for metric name %q, or TYPE reported after samples", p.currentMF.GetName()))
return nil
@@ -504,7 +515,7 @@ func (p *Parser) readingType() stateFn {
// parseError sets p.err to a ParseError at the current line with the given
// message.
-func (p *Parser) parseError(msg string) {
+func (p *TextParser) parseError(msg string) {
p.err = ParseError{
Line: p.lineCount,
Msg: msg,
@@ -513,7 +524,7 @@ func (p *Parser) parseError(msg string) {
// skipBlankTab reads (and discards) bytes from p.buf until it encounters a byte
// that is neither ' ' nor '\t'. That byte is left in p.currentByte.
-func (p *Parser) skipBlankTab() {
+func (p *TextParser) skipBlankTab() {
for {
if p.currentByte, p.err = p.buf.ReadByte(); p.err != nil || !isBlankOrTab(p.currentByte) {
return
@@ -523,7 +534,7 @@ func (p *Parser) skipBlankTab() {
// skipBlankTabIfCurrentBlankTab works exactly as skipBlankTab but doesn't do
// anything if p.currentByte is neither ' ' nor '\t'.
-func (p *Parser) skipBlankTabIfCurrentBlankTab() {
+func (p *TextParser) skipBlankTabIfCurrentBlankTab() {
if isBlankOrTab(p.currentByte) {
p.skipBlankTab()
}
@@ -533,7 +544,7 @@ func (p *Parser) skipBlankTabIfCurrentBlankTab() {
// first byte considered is the byte already read (now in p.currentByte). The
// first whitespace byte encountered is still copied into p.currentByte, but not
// into p.currentToken.
-func (p *Parser) readTokenUntilWhitespace() {
+func (p *TextParser) readTokenUntilWhitespace() {
p.currentToken.Reset()
for p.err == nil && !isBlankOrTab(p.currentByte) && p.currentByte != '\n' {
p.currentToken.WriteByte(p.currentByte)
@@ -547,7 +558,7 @@ func (p *Parser) readTokenUntilWhitespace() {
// p.currentToken. If recognizeEscapeSequence is true, two escape sequences are
// recognized: '\\' tranlates into '\', and '\n' into a line-feed character. All
// other escape sequences are invalid and cause an error.
-func (p *Parser) readTokenUntilNewline(recognizeEscapeSequence bool) {
+func (p *TextParser) readTokenUntilNewline(recognizeEscapeSequence bool) {
p.currentToken.Reset()
escaped := false
for p.err == nil {
@@ -580,7 +591,7 @@ func (p *Parser) readTokenUntilNewline(recognizeEscapeSequence bool) {
// The first byte considered is the byte already read (now in p.currentByte).
// The first byte not part of a metric name is still copied into p.currentByte,
// but not into p.currentToken.
-func (p *Parser) readTokenAsMetricName() {
+func (p *TextParser) readTokenAsMetricName() {
p.currentToken.Reset()
if !isValidMetricNameStart(p.currentByte) {
return
@@ -598,7 +609,7 @@ func (p *Parser) readTokenAsMetricName() {
// The first byte considered is the byte already read (now in p.currentByte).
// The first byte not part of a label name is still copied into p.currentByte,
// but not into p.currentToken.
-func (p *Parser) readTokenAsLabelName() {
+func (p *TextParser) readTokenAsLabelName() {
p.currentToken.Reset()
if !isValidLabelNameStart(p.currentByte) {
return
@@ -617,7 +628,7 @@ func (p *Parser) readTokenAsLabelName() {
// last read byte in p.currentByte, this method ignores p.currentByte and starts
// with reading a new byte from p.buf. The first byte not part of a label value
// is still copied into p.currentByte, but not into p.currentToken.
-func (p *Parser) readTokenAsLabelValue() {
+func (p *TextParser) readTokenAsLabelValue() {
p.currentToken.Reset()
escaped := false
for {
@@ -651,7 +662,7 @@ func (p *Parser) readTokenAsLabelValue() {
}
}
-func (p *Parser) setOrCreateCurrentMF() {
+func (p *TextParser) setOrCreateCurrentMF() {
p.currentIsSummaryCount = false
p.currentIsSummarySum = false
p.currentIsHistogramCount = false
diff --git a/vendor/github.com/prometheus/client_golang/text/parse_test.go b/vendor/github.com/prometheus/common/expfmt/text_parse_test.go
similarity index 96%
rename from vendor/github.com/prometheus/client_golang/text/parse_test.go
rename to vendor/github.com/prometheus/common/expfmt/text_parse_test.go
index cc3e647..76c9511 100644
--- a/vendor/github.com/prometheus/client_golang/text/parse_test.go
+++ b/vendor/github.com/prometheus/common/expfmt/text_parse_test.go
@@ -11,7 +11,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-package text
+package expfmt
import (
"math"
@@ -22,9 +22,7 @@ import (
dto "github.com/prometheus/client_model/go"
)
-var parser Parser
-
-func testParse(t testing.TB) {
+func testTextParse(t testing.TB) {
var scenarios = []struct {
in string
out []*dto.MetricFamily
@@ -419,25 +417,27 @@ request_duration_microseconds_count 2693
}
}
-func TestParse(t *testing.T) {
- testParse(t)
+func TestTextParse(t *testing.T) {
+ testTextParse(t)
}
-func BenchmarkParse(b *testing.B) {
+func BenchmarkTextParse(b *testing.B) {
for i := 0; i < b.N; i++ {
- testParse(b)
+ testTextParse(b)
}
}
-func testParseError(t testing.TB) {
+func testTextParseError(t testing.TB) {
var scenarios = []struct {
in string
err string
}{
// 0: No new-line at end of input.
{
- in: `bla 3.14`,
- err: "EOF",
+ in: `
+bla 3.14
+blubber 42`,
+ err: "text format parsing error in line 3: unexpected end of input stream",
},
// 1: Invalid escape sequence in label value.
{
@@ -559,6 +559,11 @@ metric_bucket{le="bla"} 3.14
`,
err: "text format parsing error in line 3: expected float as value for 'le' label",
},
+ // 19: Invalid UTF-8 in label value.
+ {
+ in: "metric{l=\"\xbd\"} 3.14\n",
+ err: "text format parsing error in line 1: invalid label value \"\\xbd\"",
+ },
}
for i, scenario := range scenarios {
@@ -577,12 +582,12 @@ metric_bucket{le="bla"} 3.14
}
-func TestParseError(t *testing.T) {
- testParseError(t)
+func TestTextParseError(t *testing.T) {
+ testTextParseError(t)
}
func BenchmarkParseError(b *testing.B) {
for i := 0; i < b.N; i++ {
- testParseError(b)
+ testTextParseError(b)
}
}
diff --git a/vendor/bitbucket.org/ww/goautoneg/README.txt b/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt
similarity index 100%
rename from vendor/bitbucket.org/ww/goautoneg/README.txt
rename to vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/README.txt
diff --git a/vendor/bitbucket.org/ww/goautoneg/autoneg.go b/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go
similarity index 100%
rename from vendor/bitbucket.org/ww/goautoneg/autoneg.go
rename to vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go
diff --git a/vendor/bitbucket.org/ww/goautoneg/autoneg_test.go b/vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg_test.go
similarity index 100%
rename from vendor/bitbucket.org/ww/goautoneg/autoneg_test.go
rename to vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg_test.go
diff --git a/vendor/github.com/prometheus/common/log/eventlog_formatter.go b/vendor/github.com/prometheus/common/log/eventlog_formatter.go
new file mode 100644
index 0000000..bcf68e6
--- /dev/null
+++ b/vendor/github.com/prometheus/common/log/eventlog_formatter.go
@@ -0,0 +1,89 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build windows
+
+package log
+
+import (
+ "fmt"
+ "os"
+
+ "golang.org/x/sys/windows/svc/eventlog"
+
+ "github.com/sirupsen/logrus"
+)
+
+func init() {
+ setEventlogFormatter = func(l logger, name string, debugAsInfo bool) error {
+ if name == "" {
+ return fmt.Errorf("missing name parameter")
+ }
+
+ fmter, err := newEventlogger(name, debugAsInfo, l.entry.Logger.Formatter)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "error creating eventlog formatter: %v\n", err)
+ l.Errorf("can't connect logger to eventlog: %v", err)
+ return err
+ }
+ l.entry.Logger.Formatter = fmter
+ return nil
+ }
+}
+
+type eventlogger struct {
+ log *eventlog.Log
+ debugAsInfo bool
+ wrap logrus.Formatter
+}
+
+func newEventlogger(name string, debugAsInfo bool, fmter logrus.Formatter) (*eventlogger, error) {
+ logHandle, err := eventlog.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ return &eventlogger{log: logHandle, debugAsInfo: debugAsInfo, wrap: fmter}, nil
+}
+
+func (s *eventlogger) Format(e *logrus.Entry) ([]byte, error) {
+ data, err := s.wrap.Format(e)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "eventlogger: can't format entry: %v\n", err)
+ return data, err
+ }
+
+ switch e.Level {
+ case logrus.PanicLevel:
+ fallthrough
+ case logrus.FatalLevel:
+ fallthrough
+ case logrus.ErrorLevel:
+ err = s.log.Error(102, e.Message)
+ case logrus.WarnLevel:
+ err = s.log.Warning(101, e.Message)
+ case logrus.InfoLevel:
+ err = s.log.Info(100, e.Message)
+ case logrus.DebugLevel:
+ if s.debugAsInfo {
+ err = s.log.Info(100, e.Message)
+ }
+ default:
+ err = s.log.Info(100, e.Message)
+ }
+
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "eventlogger: can't send log to eventlog: %v\n", err)
+ }
+
+ return data, err
+}
diff --git a/vendor/github.com/prometheus/common/log/log.go b/vendor/github.com/prometheus/common/log/log.go
new file mode 100644
index 0000000..1088302
--- /dev/null
+++ b/vendor/github.com/prometheus/common/log/log.go
@@ -0,0 +1,364 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package log
+
+import (
+ "fmt"
+ "io"
+ "io/ioutil"
+ "log"
+ "net/url"
+ "os"
+ "runtime"
+ "strconv"
+ "strings"
+
+ "github.com/sirupsen/logrus"
+ "gopkg.in/alecthomas/kingpin.v2"
+)
+
+// setSyslogFormatter is nil if the target architecture does not support syslog.
+var setSyslogFormatter func(logger, string, string) error
+
+// setEventlogFormatter is nil if the target OS does not support Eventlog (i.e., is not Windows).
+var setEventlogFormatter func(logger, string, bool) error
+
+func setJSONFormatter() {
+ origLogger.Formatter = &logrus.JSONFormatter{}
+}
+
+type loggerSettings struct {
+ level string
+ format string
+}
+
+func (s *loggerSettings) apply(ctx *kingpin.ParseContext) error {
+ err := baseLogger.SetLevel(s.level)
+ if err != nil {
+ return err
+ }
+ err = baseLogger.SetFormat(s.format)
+ return err
+}
+
+// AddFlags adds the flags used by this package to the Kingpin application.
+// To use the default Kingpin application, call AddFlags(kingpin.CommandLine)
+func AddFlags(a *kingpin.Application) {
+ s := loggerSettings{}
+ a.Flag("log.level", "Only log messages with the given severity or above. Valid levels: [debug, info, warn, error, fatal]").
+ Default(origLogger.Level.String()).
+ StringVar(&s.level)
+ defaultFormat := url.URL{Scheme: "logger", Opaque: "stderr"}
+ a.Flag("log.format", `Set the log target and format. Example: "logger:syslog?appname=bob&local=7" or "logger:stdout?json=true"`).
+ Default(defaultFormat.String()).
+ StringVar(&s.format)
+ a.Action(s.apply)
+}
+
+// Logger is the interface for loggers used in the Prometheus components.
+type Logger interface {
+ Debug(...interface{})
+ Debugln(...interface{})
+ Debugf(string, ...interface{})
+
+ Info(...interface{})
+ Infoln(...interface{})
+ Infof(string, ...interface{})
+
+ Warn(...interface{})
+ Warnln(...interface{})
+ Warnf(string, ...interface{})
+
+ Error(...interface{})
+ Errorln(...interface{})
+ Errorf(string, ...interface{})
+
+ Fatal(...interface{})
+ Fatalln(...interface{})
+ Fatalf(string, ...interface{})
+
+ With(key string, value interface{}) Logger
+
+ SetFormat(string) error
+ SetLevel(string) error
+}
+
+type logger struct {
+ entry *logrus.Entry
+}
+
+func (l logger) With(key string, value interface{}) Logger {
+ return logger{l.entry.WithField(key, value)}
+}
+
+// Debug logs a message at level Debug on the standard logger.
+func (l logger) Debug(args ...interface{}) {
+ l.sourced().Debug(args...)
+}
+
+// Debug logs a message at level Debug on the standard logger.
+func (l logger) Debugln(args ...interface{}) {
+ l.sourced().Debugln(args...)
+}
+
+// Debugf logs a message at level Debug on the standard logger.
+func (l logger) Debugf(format string, args ...interface{}) {
+ l.sourced().Debugf(format, args...)
+}
+
+// Info logs a message at level Info on the standard logger.
+func (l logger) Info(args ...interface{}) {
+ l.sourced().Info(args...)
+}
+
+// Info logs a message at level Info on the standard logger.
+func (l logger) Infoln(args ...interface{}) {
+ l.sourced().Infoln(args...)
+}
+
+// Infof logs a message at level Info on the standard logger.
+func (l logger) Infof(format string, args ...interface{}) {
+ l.sourced().Infof(format, args...)
+}
+
+// Warn logs a message at level Warn on the standard logger.
+func (l logger) Warn(args ...interface{}) {
+ l.sourced().Warn(args...)
+}
+
+// Warn logs a message at level Warn on the standard logger.
+func (l logger) Warnln(args ...interface{}) {
+ l.sourced().Warnln(args...)
+}
+
+// Warnf logs a message at level Warn on the standard logger.
+func (l logger) Warnf(format string, args ...interface{}) {
+ l.sourced().Warnf(format, args...)
+}
+
+// Error logs a message at level Error on the standard logger.
+func (l logger) Error(args ...interface{}) {
+ l.sourced().Error(args...)
+}
+
+// Error logs a message at level Error on the standard logger.
+func (l logger) Errorln(args ...interface{}) {
+ l.sourced().Errorln(args...)
+}
+
+// Errorf logs a message at level Error on the standard logger.
+func (l logger) Errorf(format string, args ...interface{}) {
+ l.sourced().Errorf(format, args...)
+}
+
+// Fatal logs a message at level Fatal on the standard logger.
+func (l logger) Fatal(args ...interface{}) {
+ l.sourced().Fatal(args...)
+}
+
+// Fatal logs a message at level Fatal on the standard logger.
+func (l logger) Fatalln(args ...interface{}) {
+ l.sourced().Fatalln(args...)
+}
+
+// Fatalf logs a message at level Fatal on the standard logger.
+func (l logger) Fatalf(format string, args ...interface{}) {
+ l.sourced().Fatalf(format, args...)
+}
+
+func (l logger) SetLevel(level string) error {
+ lvl, err := logrus.ParseLevel(level)
+ if err != nil {
+ return err
+ }
+
+ l.entry.Logger.Level = lvl
+ return nil
+}
+
+func (l logger) SetFormat(format string) error {
+ u, err := url.Parse(format)
+ if err != nil {
+ return err
+ }
+ if u.Scheme != "logger" {
+ return fmt.Errorf("invalid scheme %s", u.Scheme)
+ }
+ jsonq := u.Query().Get("json")
+ if jsonq == "true" {
+ setJSONFormatter()
+ }
+
+ switch u.Opaque {
+ case "syslog":
+ if setSyslogFormatter == nil {
+ return fmt.Errorf("system does not support syslog")
+ }
+ appname := u.Query().Get("appname")
+ facility := u.Query().Get("local")
+ return setSyslogFormatter(l, appname, facility)
+ case "eventlog":
+ if setEventlogFormatter == nil {
+ return fmt.Errorf("system does not support eventlog")
+ }
+ name := u.Query().Get("name")
+ debugAsInfo := false
+ debugAsInfoRaw := u.Query().Get("debugAsInfo")
+ if parsedDebugAsInfo, err := strconv.ParseBool(debugAsInfoRaw); err == nil {
+ debugAsInfo = parsedDebugAsInfo
+ }
+ return setEventlogFormatter(l, name, debugAsInfo)
+ case "stdout":
+ l.entry.Logger.Out = os.Stdout
+ case "stderr":
+ l.entry.Logger.Out = os.Stderr
+ default:
+ return fmt.Errorf("unsupported logger %q", u.Opaque)
+ }
+ return nil
+}
+
+// sourced adds a source field to the logger that contains
+// the file name and line where the logging happened.
+func (l logger) sourced() *logrus.Entry {
+ _, file, line, ok := runtime.Caller(2)
+ if !ok {
+ file = "??>"
+ line = 1
+ } else {
+ slash := strings.LastIndex(file, "/")
+ file = file[slash+1:]
+ }
+ return l.entry.WithField("source", fmt.Sprintf("%s:%d", file, line))
+}
+
+var origLogger = logrus.New()
+var baseLogger = logger{entry: logrus.NewEntry(origLogger)}
+
+// Base returns the default Logger logging to
+func Base() Logger {
+ return baseLogger
+}
+
+// NewLogger returns a new Logger logging to out.
+func NewLogger(w io.Writer) Logger {
+ l := logrus.New()
+ l.Out = w
+ return logger{entry: logrus.NewEntry(l)}
+}
+
+// NewNopLogger returns a logger that discards all log messages.
+func NewNopLogger() Logger {
+ l := logrus.New()
+ l.Out = ioutil.Discard
+ return logger{entry: logrus.NewEntry(l)}
+}
+
+// With adds a field to the logger.
+func With(key string, value interface{}) Logger {
+ return baseLogger.With(key, value)
+}
+
+// Debug logs a message at level Debug on the standard logger.
+func Debug(args ...interface{}) {
+ baseLogger.sourced().Debug(args...)
+}
+
+// Debugln logs a message at level Debug on the standard logger.
+func Debugln(args ...interface{}) {
+ baseLogger.sourced().Debugln(args...)
+}
+
+// Debugf logs a message at level Debug on the standard logger.
+func Debugf(format string, args ...interface{}) {
+ baseLogger.sourced().Debugf(format, args...)
+}
+
+// Info logs a message at level Info on the standard logger.
+func Info(args ...interface{}) {
+ baseLogger.sourced().Info(args...)
+}
+
+// Infoln logs a message at level Info on the standard logger.
+func Infoln(args ...interface{}) {
+ baseLogger.sourced().Infoln(args...)
+}
+
+// Infof logs a message at level Info on the standard logger.
+func Infof(format string, args ...interface{}) {
+ baseLogger.sourced().Infof(format, args...)
+}
+
+// Warn logs a message at level Warn on the standard logger.
+func Warn(args ...interface{}) {
+ baseLogger.sourced().Warn(args...)
+}
+
+// Warnln logs a message at level Warn on the standard logger.
+func Warnln(args ...interface{}) {
+ baseLogger.sourced().Warnln(args...)
+}
+
+// Warnf logs a message at level Warn on the standard logger.
+func Warnf(format string, args ...interface{}) {
+ baseLogger.sourced().Warnf(format, args...)
+}
+
+// Error logs a message at level Error on the standard logger.
+func Error(args ...interface{}) {
+ baseLogger.sourced().Error(args...)
+}
+
+// Errorln logs a message at level Error on the standard logger.
+func Errorln(args ...interface{}) {
+ baseLogger.sourced().Errorln(args...)
+}
+
+// Errorf logs a message at level Error on the standard logger.
+func Errorf(format string, args ...interface{}) {
+ baseLogger.sourced().Errorf(format, args...)
+}
+
+// Fatal logs a message at level Fatal on the standard logger.
+func Fatal(args ...interface{}) {
+ baseLogger.sourced().Fatal(args...)
+}
+
+// Fatalln logs a message at level Fatal on the standard logger.
+func Fatalln(args ...interface{}) {
+ baseLogger.sourced().Fatalln(args...)
+}
+
+// Fatalf logs a message at level Fatal on the standard logger.
+func Fatalf(format string, args ...interface{}) {
+ baseLogger.sourced().Fatalf(format, args...)
+}
+
+// AddHook adds hook to Prometheus' original logger.
+func AddHook(hook logrus.Hook) {
+ origLogger.Hooks.Add(hook)
+}
+
+type errorLogWriter struct{}
+
+func (errorLogWriter) Write(b []byte) (int, error) {
+ baseLogger.sourced().Error(string(b))
+ return len(b), nil
+}
+
+// NewErrorLogger returns a log.Logger that is meant to be used
+// in the ErrorLog field of an http.Server to log HTTP server errors.
+func NewErrorLogger() *log.Logger {
+ return log.New(&errorLogWriter{}, "", 0)
+}
diff --git a/vendor/github.com/prometheus/common/log/log_test.go b/vendor/github.com/prometheus/common/log/log_test.go
new file mode 100644
index 0000000..f63b441
--- /dev/null
+++ b/vendor/github.com/prometheus/common/log/log_test.go
@@ -0,0 +1,39 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package log
+
+import (
+ "bytes"
+ "regexp"
+ "testing"
+
+ "github.com/sirupsen/logrus"
+)
+
+func TestFileLineLogging(t *testing.T) {
+ var buf bytes.Buffer
+ origLogger.Out = &buf
+ origLogger.Formatter = &logrus.TextFormatter{
+ DisableColors: true,
+ }
+
+ // The default logging level should be "info".
+ Debug("This debug-level line should not show up in the output.")
+ Infof("This %s-level line should show up in the output.", "info")
+
+ re := `^time=".*" level=info msg="This info-level line should show up in the output." source="log_test.go:33"\n$`
+ if !regexp.MustCompile(re).Match(buf.Bytes()) {
+ t.Fatalf("%q did not match expected regex %q", buf.String(), re)
+ }
+}
diff --git a/vendor/github.com/prometheus/common/log/syslog_formatter.go b/vendor/github.com/prometheus/common/log/syslog_formatter.go
new file mode 100644
index 0000000..f882f2f
--- /dev/null
+++ b/vendor/github.com/prometheus/common/log/syslog_formatter.go
@@ -0,0 +1,126 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build !windows,!nacl,!plan9
+
+package log
+
+import (
+ "fmt"
+ "log/syslog"
+ "os"
+
+ "github.com/sirupsen/logrus"
+)
+
+var _ logrus.Formatter = (*syslogger)(nil)
+
+func init() {
+ setSyslogFormatter = func(l logger, appname, local string) error {
+ if appname == "" {
+ return fmt.Errorf("missing appname parameter")
+ }
+ if local == "" {
+ return fmt.Errorf("missing local parameter")
+ }
+
+ fmter, err := newSyslogger(appname, local, l.entry.Logger.Formatter)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "error creating syslog formatter: %v\n", err)
+ l.entry.Errorf("can't connect logger to syslog: %v", err)
+ return err
+ }
+ l.entry.Logger.Formatter = fmter
+ return nil
+ }
+}
+
+var prefixTag []byte
+
+type syslogger struct {
+ wrap logrus.Formatter
+ out *syslog.Writer
+}
+
+func newSyslogger(appname string, facility string, fmter logrus.Formatter) (*syslogger, error) {
+ priority, err := getFacility(facility)
+ if err != nil {
+ return nil, err
+ }
+ out, err := syslog.New(priority, appname)
+ _, isJSON := fmter.(*logrus.JSONFormatter)
+ if isJSON {
+ // add cee tag to json formatted syslogs
+ prefixTag = []byte("@cee:")
+ }
+ return &syslogger{
+ out: out,
+ wrap: fmter,
+ }, err
+}
+
+func getFacility(facility string) (syslog.Priority, error) {
+ switch facility {
+ case "0":
+ return syslog.LOG_LOCAL0, nil
+ case "1":
+ return syslog.LOG_LOCAL1, nil
+ case "2":
+ return syslog.LOG_LOCAL2, nil
+ case "3":
+ return syslog.LOG_LOCAL3, nil
+ case "4":
+ return syslog.LOG_LOCAL4, nil
+ case "5":
+ return syslog.LOG_LOCAL5, nil
+ case "6":
+ return syslog.LOG_LOCAL6, nil
+ case "7":
+ return syslog.LOG_LOCAL7, nil
+ }
+ return syslog.LOG_LOCAL0, fmt.Errorf("invalid local(%s) for syslog", facility)
+}
+
+func (s *syslogger) Format(e *logrus.Entry) ([]byte, error) {
+ data, err := s.wrap.Format(e)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "syslogger: can't format entry: %v\n", err)
+ return data, err
+ }
+ // only append tag to data sent to syslog (line), not to what
+ // is returned
+ line := string(append(prefixTag, data...))
+
+ switch e.Level {
+ case logrus.PanicLevel:
+ err = s.out.Crit(line)
+ case logrus.FatalLevel:
+ err = s.out.Crit(line)
+ case logrus.ErrorLevel:
+ err = s.out.Err(line)
+ case logrus.WarnLevel:
+ err = s.out.Warning(line)
+ case logrus.InfoLevel:
+ err = s.out.Info(line)
+ case logrus.DebugLevel:
+ err = s.out.Debug(line)
+ default:
+ err = s.out.Notice(line)
+ }
+
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "syslogger: can't send log to syslog: %v\n", err)
+ }
+
+ return data, err
+}
diff --git a/vendor/github.com/prometheus/common/log/syslog_formatter_test.go b/vendor/github.com/prometheus/common/log/syslog_formatter_test.go
new file mode 100644
index 0000000..b7e6884
--- /dev/null
+++ b/vendor/github.com/prometheus/common/log/syslog_formatter_test.go
@@ -0,0 +1,52 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// +build !windows,!nacl,!plan9
+
+package log
+
+import (
+ "errors"
+ "log/syslog"
+ "testing"
+)
+
+func TestGetFacility(t *testing.T) {
+ testCases := []struct {
+ facility string
+ expectedPriority syslog.Priority
+ expectedErr error
+ }{
+ {"0", syslog.LOG_LOCAL0, nil},
+ {"1", syslog.LOG_LOCAL1, nil},
+ {"2", syslog.LOG_LOCAL2, nil},
+ {"3", syslog.LOG_LOCAL3, nil},
+ {"4", syslog.LOG_LOCAL4, nil},
+ {"5", syslog.LOG_LOCAL5, nil},
+ {"6", syslog.LOG_LOCAL6, nil},
+ {"7", syslog.LOG_LOCAL7, nil},
+ {"8", syslog.LOG_LOCAL0, errors.New("invalid local(8) for syslog")},
+ }
+ for _, tc := range testCases {
+ priority, err := getFacility(tc.facility)
+ if err != tc.expectedErr {
+ if err.Error() != tc.expectedErr.Error() {
+ t.Errorf("want %s, got %s", tc.expectedErr.Error(), err.Error())
+ }
+ }
+
+ if priority != tc.expectedPriority {
+ t.Errorf("want %q, got %q", tc.expectedPriority, priority)
+ }
+ }
+}
diff --git a/vendor/github.com/prometheus/common/model/alert.go b/vendor/github.com/prometheus/common/model/alert.go
new file mode 100644
index 0000000..35e739c
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/alert.go
@@ -0,0 +1,136 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "fmt"
+ "time"
+)
+
+type AlertStatus string
+
+const (
+ AlertFiring AlertStatus = "firing"
+ AlertResolved AlertStatus = "resolved"
+)
+
+// Alert is a generic representation of an alert in the Prometheus eco-system.
+type Alert struct {
+ // Label value pairs for purpose of aggregation, matching, and disposition
+ // dispatching. This must minimally include an "alertname" label.
+ Labels LabelSet `json:"labels"`
+
+ // Extra key/value information which does not define alert identity.
+ Annotations LabelSet `json:"annotations"`
+
+ // The known time range for this alert. Both ends are optional.
+ StartsAt time.Time `json:"startsAt,omitempty"`
+ EndsAt time.Time `json:"endsAt,omitempty"`
+ GeneratorURL string `json:"generatorURL"`
+}
+
+// Name returns the name of the alert. It is equivalent to the "alertname" label.
+func (a *Alert) Name() string {
+ return string(a.Labels[AlertNameLabel])
+}
+
+// Fingerprint returns a unique hash for the alert. It is equivalent to
+// the fingerprint of the alert's label set.
+func (a *Alert) Fingerprint() Fingerprint {
+ return a.Labels.Fingerprint()
+}
+
+func (a *Alert) String() string {
+ s := fmt.Sprintf("%s[%s]", a.Name(), a.Fingerprint().String()[:7])
+ if a.Resolved() {
+ return s + "[resolved]"
+ }
+ return s + "[active]"
+}
+
+// Resolved returns true iff the activity interval ended in the past.
+func (a *Alert) Resolved() bool {
+ return a.ResolvedAt(time.Now())
+}
+
+// ResolvedAt returns true off the activity interval ended before
+// the given timestamp.
+func (a *Alert) ResolvedAt(ts time.Time) bool {
+ if a.EndsAt.IsZero() {
+ return false
+ }
+ return !a.EndsAt.After(ts)
+}
+
+// Status returns the status of the alert.
+func (a *Alert) Status() AlertStatus {
+ if a.Resolved() {
+ return AlertResolved
+ }
+ return AlertFiring
+}
+
+// Validate checks whether the alert data is inconsistent.
+func (a *Alert) Validate() error {
+ if a.StartsAt.IsZero() {
+ return fmt.Errorf("start time missing")
+ }
+ if !a.EndsAt.IsZero() && a.EndsAt.Before(a.StartsAt) {
+ return fmt.Errorf("start time must be before end time")
+ }
+ if err := a.Labels.Validate(); err != nil {
+ return fmt.Errorf("invalid label set: %s", err)
+ }
+ if len(a.Labels) == 0 {
+ return fmt.Errorf("at least one label pair required")
+ }
+ if err := a.Annotations.Validate(); err != nil {
+ return fmt.Errorf("invalid annotations: %s", err)
+ }
+ return nil
+}
+
+// Alert is a list of alerts that can be sorted in chronological order.
+type Alerts []*Alert
+
+func (as Alerts) Len() int { return len(as) }
+func (as Alerts) Swap(i, j int) { as[i], as[j] = as[j], as[i] }
+
+func (as Alerts) Less(i, j int) bool {
+ if as[i].StartsAt.Before(as[j].StartsAt) {
+ return true
+ }
+ if as[i].EndsAt.Before(as[j].EndsAt) {
+ return true
+ }
+ return as[i].Fingerprint() < as[j].Fingerprint()
+}
+
+// HasFiring returns true iff one of the alerts is not resolved.
+func (as Alerts) HasFiring() bool {
+ for _, a := range as {
+ if !a.Resolved() {
+ return true
+ }
+ }
+ return false
+}
+
+// Status returns StatusFiring iff at least one of the alerts is firing.
+func (as Alerts) Status() AlertStatus {
+ if as.HasFiring() {
+ return AlertFiring
+ }
+ return AlertResolved
+}
diff --git a/vendor/github.com/prometheus/common/model/alert_test.go b/vendor/github.com/prometheus/common/model/alert_test.go
new file mode 100644
index 0000000..9692bca
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/alert_test.go
@@ -0,0 +1,118 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestAlertValidate(t *testing.T) {
+ ts := time.Now()
+
+ var cases = []struct {
+ alert *Alert
+ err string
+ }{
+ {
+ alert: &Alert{
+ Labels: LabelSet{"a": "b"},
+ StartsAt: ts,
+ },
+ },
+ {
+ alert: &Alert{
+ Labels: LabelSet{"a": "b"},
+ },
+ err: "start time missing",
+ },
+ {
+ alert: &Alert{
+ Labels: LabelSet{"a": "b"},
+ StartsAt: ts,
+ EndsAt: ts,
+ },
+ },
+ {
+ alert: &Alert{
+ Labels: LabelSet{"a": "b"},
+ StartsAt: ts,
+ EndsAt: ts.Add(1 * time.Minute),
+ },
+ },
+ {
+ alert: &Alert{
+ Labels: LabelSet{"a": "b"},
+ StartsAt: ts,
+ EndsAt: ts.Add(-1 * time.Minute),
+ },
+ err: "start time must be before end time",
+ },
+ {
+ alert: &Alert{
+ StartsAt: ts,
+ },
+ err: "at least one label pair required",
+ },
+ {
+ alert: &Alert{
+ Labels: LabelSet{"a": "b", "!bad": "label"},
+ StartsAt: ts,
+ },
+ err: "invalid label set: invalid name",
+ },
+ {
+ alert: &Alert{
+ Labels: LabelSet{"a": "b", "bad": "\xfflabel"},
+ StartsAt: ts,
+ },
+ err: "invalid label set: invalid value",
+ },
+ {
+ alert: &Alert{
+ Labels: LabelSet{"a": "b"},
+ Annotations: LabelSet{"!bad": "label"},
+ StartsAt: ts,
+ },
+ err: "invalid annotations: invalid name",
+ },
+ {
+ alert: &Alert{
+ Labels: LabelSet{"a": "b"},
+ Annotations: LabelSet{"bad": "\xfflabel"},
+ StartsAt: ts,
+ },
+ err: "invalid annotations: invalid value",
+ },
+ }
+
+ for i, c := range cases {
+ err := c.alert.Validate()
+ if err == nil {
+ if c.err == "" {
+ continue
+ }
+ t.Errorf("%d. Expected error %q but got none", i, c.err)
+ continue
+ }
+ if c.err == "" && err != nil {
+ t.Errorf("%d. Expected no error but got %q", i, err)
+ continue
+ }
+ if !strings.Contains(err.Error(), c.err) {
+ t.Errorf("%d. Expected error to contain %q but got %q", i, c.err, err)
+ }
+ }
+}
diff --git a/vendor/github.com/prometheus/client_golang/model/fingerprinting.go b/vendor/github.com/prometheus/common/model/fingerprinting.go
similarity index 85%
rename from vendor/github.com/prometheus/client_golang/model/fingerprinting.go
rename to vendor/github.com/prometheus/common/model/fingerprinting.go
index 5b2ffe3..fc4de41 100644
--- a/vendor/github.com/prometheus/client_golang/model/fingerprinting.go
+++ b/vendor/github.com/prometheus/common/model/fingerprinting.go
@@ -22,28 +22,23 @@ import (
// For our purposes, FNV-1A 64-bit is used.
type Fingerprint uint64
-func (f Fingerprint) String() string {
- return fmt.Sprintf("%016x", uint64(f))
+// FingerprintFromString transforms a string representation into a Fingerprint.
+func FingerprintFromString(s string) (Fingerprint, error) {
+ num, err := strconv.ParseUint(s, 16, 64)
+ return Fingerprint(num), err
}
-// Less implements sort.Interface.
-func (f Fingerprint) Less(o Fingerprint) bool {
- return f < o
-}
-
-// Equal implements sort.Interface.
-func (f Fingerprint) Equal(o Fingerprint) bool {
- return f == o
-}
-
-// LoadFromString transforms a string representation into a Fingerprint.
-func (f *Fingerprint) LoadFromString(s string) error {
+// ParseFingerprint parses the input string into a fingerprint.
+func ParseFingerprint(s string) (Fingerprint, error) {
num, err := strconv.ParseUint(s, 16, 64)
if err != nil {
- return err
+ return 0, err
}
- *f = Fingerprint(num)
- return nil
+ return Fingerprint(num), nil
+}
+
+func (f Fingerprint) String() string {
+ return fmt.Sprintf("%016x", uint64(f))
}
// Fingerprints represents a collection of Fingerprint subject to a given
diff --git a/vendor/github.com/prometheus/common/model/fnv.go b/vendor/github.com/prometheus/common/model/fnv.go
new file mode 100644
index 0000000..038fc1c
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/fnv.go
@@ -0,0 +1,42 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+// Inline and byte-free variant of hash/fnv's fnv64a.
+
+const (
+ offset64 = 14695981039346656037
+ prime64 = 1099511628211
+)
+
+// hashNew initializies a new fnv64a hash value.
+func hashNew() uint64 {
+ return offset64
+}
+
+// hashAdd adds a string to a fnv64a hash value, returning the updated hash.
+func hashAdd(h uint64, s string) uint64 {
+ for i := 0; i < len(s); i++ {
+ h ^= uint64(s[i])
+ h *= prime64
+ }
+ return h
+}
+
+// hashAddByte adds a byte to a fnv64a hash value, returning the updated hash.
+func hashAddByte(h uint64, b byte) uint64 {
+ h ^= uint64(b)
+ h *= prime64
+ return h
+}
diff --git a/vendor/github.com/prometheus/client_golang/model/labelname.go b/vendor/github.com/prometheus/common/model/labels.go
similarity index 55%
rename from vendor/github.com/prometheus/client_golang/model/labelname.go
rename to vendor/github.com/prometheus/common/model/labels.go
index 7d071bd..41051a0 100644
--- a/vendor/github.com/prometheus/client_golang/model/labelname.go
+++ b/vendor/github.com/prometheus/common/model/labels.go
@@ -18,24 +18,32 @@ import (
"fmt"
"regexp"
"strings"
+ "unicode/utf8"
)
const (
+ // AlertNameLabel is the name of the label containing the an alert's name.
+ AlertNameLabel = "alertname"
+
// ExportedLabelPrefix is the prefix to prepend to the label names present in
// exported metrics if a label of the same name is added by the server.
- ExportedLabelPrefix LabelName = "exported_"
+ ExportedLabelPrefix = "exported_"
// MetricNameLabel is the label name indicating the metric name of a
// timeseries.
- MetricNameLabel LabelName = "__name__"
+ MetricNameLabel = "__name__"
+
+ // SchemeLabel is the name of the label that holds the scheme on which to
+ // scrape a target.
+ SchemeLabel = "__scheme__"
// AddressLabel is the name of the label that holds the address of
// a scrape target.
- AddressLabel LabelName = "__address__"
+ AddressLabel = "__address__"
// MetricsPathLabel is the name of the label that holds the path on which to
// scrape a target.
- MetricsPathLabel LabelName = "__metrics_path__"
+ MetricsPathLabel = "__metrics_path__"
// ReservedLabelPrefix is a prefix which is not legal in user-supplied
// label names.
@@ -46,12 +54,22 @@ const (
// will not be attached to time series.
MetaLabelPrefix = "__meta_"
+ // TmpLabelPrefix is a prefix for temporary labels as part of relabelling.
+ // Labels with this prefix are used for intermediate label processing and
+ // will not be attached to time series. This is reserved for use in
+ // Prometheus configuration files by users.
+ TmpLabelPrefix = "__tmp_"
+
+ // ParamLabelPrefix is a prefix for labels that provide URL parameters
+ // used to scrape a target.
+ ParamLabelPrefix = "__param_"
+
// JobLabel is the label name indicating the job from which a timeseries
// was scraped.
- JobLabel LabelName = "job"
+ JobLabel = "job"
// InstanceLabel is the label name used for the instance label.
- InstanceLabel LabelName = "instance"
+ InstanceLabel = "instance"
// BucketLabel is used for the label that defines the upper bound of a
// bucket of a histogram ("le" -> "less or equal").
@@ -62,20 +80,37 @@ const (
QuantileLabel = "quantile"
)
-// LabelNameRE is a regular expression matching valid label names.
+// LabelNameRE is a regular expression matching valid label names. Note that the
+// IsValid method of LabelName performs the same check but faster than a match
+// with this regular expression.
var LabelNameRE = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
// A LabelName is a key for a LabelSet or Metric. It has a value associated
// therewith.
type LabelName string
+// IsValid is true iff the label name matches the pattern of LabelNameRE. This
+// method, however, does not use LabelNameRE for the check but a much faster
+// hardcoded implementation.
+func (ln LabelName) IsValid() bool {
+ if len(ln) == 0 {
+ return false
+ }
+ for i, b := range ln {
+ if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || (b >= '0' && b <= '9' && i > 0)) {
+ return false
+ }
+ }
+ return true
+}
+
// UnmarshalYAML implements the yaml.Unmarshaler interface.
func (ln *LabelName) UnmarshalYAML(unmarshal func(interface{}) error) error {
var s string
if err := unmarshal(&s); err != nil {
return err
}
- if !LabelNameRE.MatchString(s) {
+ if !LabelName(s).IsValid() {
return fmt.Errorf("%q is not a valid label name", s)
}
*ln = LabelName(s)
@@ -88,7 +123,7 @@ func (ln *LabelName) UnmarshalJSON(b []byte) error {
if err := json.Unmarshal(b, &s); err != nil {
return err
}
- if !LabelNameRE.MatchString(s) {
+ if !LabelName(s).IsValid() {
return fmt.Errorf("%q is not a valid label name", s)
}
*ln = LabelName(s)
@@ -117,3 +152,59 @@ func (l LabelNames) String() string {
}
return strings.Join(labelStrings, ", ")
}
+
+// A LabelValue is an associated value for a LabelName.
+type LabelValue string
+
+// IsValid returns true iff the string is a valid UTF8.
+func (lv LabelValue) IsValid() bool {
+ return utf8.ValidString(string(lv))
+}
+
+// LabelValues is a sortable LabelValue slice. It implements sort.Interface.
+type LabelValues []LabelValue
+
+func (l LabelValues) Len() int {
+ return len(l)
+}
+
+func (l LabelValues) Less(i, j int) bool {
+ return string(l[i]) < string(l[j])
+}
+
+func (l LabelValues) Swap(i, j int) {
+ l[i], l[j] = l[j], l[i]
+}
+
+// LabelPair pairs a name with a value.
+type LabelPair struct {
+ Name LabelName
+ Value LabelValue
+}
+
+// LabelPairs is a sortable slice of LabelPair pointers. It implements
+// sort.Interface.
+type LabelPairs []*LabelPair
+
+func (l LabelPairs) Len() int {
+ return len(l)
+}
+
+func (l LabelPairs) Less(i, j int) bool {
+ switch {
+ case l[i].Name > l[j].Name:
+ return false
+ case l[i].Name < l[j].Name:
+ return true
+ case l[i].Value > l[j].Value:
+ return false
+ case l[i].Value < l[j].Value:
+ return true
+ default:
+ return false
+ }
+}
+
+func (l LabelPairs) Swap(i, j int) {
+ l[i], l[j] = l[j], l[i]
+}
diff --git a/vendor/github.com/prometheus/common/model/labels_test.go b/vendor/github.com/prometheus/common/model/labels_test.go
new file mode 100644
index 0000000..e8df28f
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/labels_test.go
@@ -0,0 +1,140 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "sort"
+ "testing"
+)
+
+func testLabelNames(t testing.TB) {
+ var scenarios = []struct {
+ in LabelNames
+ out LabelNames
+ }{
+ {
+ in: LabelNames{"ZZZ", "zzz"},
+ out: LabelNames{"ZZZ", "zzz"},
+ },
+ {
+ in: LabelNames{"aaa", "AAA"},
+ out: LabelNames{"AAA", "aaa"},
+ },
+ }
+
+ for i, scenario := range scenarios {
+ sort.Sort(scenario.in)
+
+ for j, expected := range scenario.out {
+ if expected != scenario.in[j] {
+ t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j])
+ }
+ }
+ }
+}
+
+func TestLabelNames(t *testing.T) {
+ testLabelNames(t)
+}
+
+func BenchmarkLabelNames(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ testLabelNames(b)
+ }
+}
+
+func testLabelValues(t testing.TB) {
+ var scenarios = []struct {
+ in LabelValues
+ out LabelValues
+ }{
+ {
+ in: LabelValues{"ZZZ", "zzz"},
+ out: LabelValues{"ZZZ", "zzz"},
+ },
+ {
+ in: LabelValues{"aaa", "AAA"},
+ out: LabelValues{"AAA", "aaa"},
+ },
+ }
+
+ for i, scenario := range scenarios {
+ sort.Sort(scenario.in)
+
+ for j, expected := range scenario.out {
+ if expected != scenario.in[j] {
+ t.Errorf("%d.%d expected %s, got %s", i, j, expected, scenario.in[j])
+ }
+ }
+ }
+}
+
+func TestLabelValues(t *testing.T) {
+ testLabelValues(t)
+}
+
+func BenchmarkLabelValues(b *testing.B) {
+ for i := 0; i < b.N; i++ {
+ testLabelValues(b)
+ }
+}
+
+func TestLabelNameIsValid(t *testing.T) {
+ var scenarios = []struct {
+ ln LabelName
+ valid bool
+ }{
+ {
+ ln: "Avalid_23name",
+ valid: true,
+ },
+ {
+ ln: "_Avalid_23name",
+ valid: true,
+ },
+ {
+ ln: "1valid_23name",
+ valid: false,
+ },
+ {
+ ln: "avalid_23name",
+ valid: true,
+ },
+ {
+ ln: "Ava:lid_23name",
+ valid: false,
+ },
+ {
+ ln: "a lid_23name",
+ valid: false,
+ },
+ {
+ ln: ":leading_colon",
+ valid: false,
+ },
+ {
+ ln: "colon:in:the:middle",
+ valid: false,
+ },
+ }
+
+ for _, s := range scenarios {
+ if s.ln.IsValid() != s.valid {
+ t.Errorf("Expected %v for %q using IsValid method", s.valid, s.ln)
+ }
+ if LabelNameRE.MatchString(string(s.ln)) != s.valid {
+ t.Errorf("Expected %v for %q using regexp match", s.valid, s.ln)
+ }
+ }
+}
diff --git a/vendor/github.com/prometheus/common/model/labelset.go b/vendor/github.com/prometheus/common/model/labelset.go
new file mode 100644
index 0000000..6eda08a
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/labelset.go
@@ -0,0 +1,169 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "encoding/json"
+ "fmt"
+ "sort"
+ "strings"
+)
+
+// A LabelSet is a collection of LabelName and LabelValue pairs. The LabelSet
+// may be fully-qualified down to the point where it may resolve to a single
+// Metric in the data store or not. All operations that occur within the realm
+// of a LabelSet can emit a vector of Metric entities to which the LabelSet may
+// match.
+type LabelSet map[LabelName]LabelValue
+
+// Validate checks whether all names and values in the label set
+// are valid.
+func (ls LabelSet) Validate() error {
+ for ln, lv := range ls {
+ if !ln.IsValid() {
+ return fmt.Errorf("invalid name %q", ln)
+ }
+ if !lv.IsValid() {
+ return fmt.Errorf("invalid value %q", lv)
+ }
+ }
+ return nil
+}
+
+// Equal returns true iff both label sets have exactly the same key/value pairs.
+func (ls LabelSet) Equal(o LabelSet) bool {
+ if len(ls) != len(o) {
+ return false
+ }
+ for ln, lv := range ls {
+ olv, ok := o[ln]
+ if !ok {
+ return false
+ }
+ if olv != lv {
+ return false
+ }
+ }
+ return true
+}
+
+// Before compares the metrics, using the following criteria:
+//
+// If m has fewer labels than o, it is before o. If it has more, it is not.
+//
+// If the number of labels is the same, the superset of all label names is
+// sorted alphanumerically. The first differing label pair found in that order
+// determines the outcome: If the label does not exist at all in m, then m is
+// before o, and vice versa. Otherwise the label value is compared
+// alphanumerically.
+//
+// If m and o are equal, the method returns false.
+func (ls LabelSet) Before(o LabelSet) bool {
+ if len(ls) < len(o) {
+ return true
+ }
+ if len(ls) > len(o) {
+ return false
+ }
+
+ lns := make(LabelNames, 0, len(ls)+len(o))
+ for ln := range ls {
+ lns = append(lns, ln)
+ }
+ for ln := range o {
+ lns = append(lns, ln)
+ }
+ // It's probably not worth it to de-dup lns.
+ sort.Sort(lns)
+ for _, ln := range lns {
+ mlv, ok := ls[ln]
+ if !ok {
+ return true
+ }
+ olv, ok := o[ln]
+ if !ok {
+ return false
+ }
+ if mlv < olv {
+ return true
+ }
+ if mlv > olv {
+ return false
+ }
+ }
+ return false
+}
+
+// Clone returns a copy of the label set.
+func (ls LabelSet) Clone() LabelSet {
+ lsn := make(LabelSet, len(ls))
+ for ln, lv := range ls {
+ lsn[ln] = lv
+ }
+ return lsn
+}
+
+// Merge is a helper function to non-destructively merge two label sets.
+func (l LabelSet) Merge(other LabelSet) LabelSet {
+ result := make(LabelSet, len(l))
+
+ for k, v := range l {
+ result[k] = v
+ }
+
+ for k, v := range other {
+ result[k] = v
+ }
+
+ return result
+}
+
+func (l LabelSet) String() string {
+ lstrs := make([]string, 0, len(l))
+ for l, v := range l {
+ lstrs = append(lstrs, fmt.Sprintf("%s=%q", l, v))
+ }
+
+ sort.Strings(lstrs)
+ return fmt.Sprintf("{%s}", strings.Join(lstrs, ", "))
+}
+
+// Fingerprint returns the LabelSet's fingerprint.
+func (ls LabelSet) Fingerprint() Fingerprint {
+ return labelSetToFingerprint(ls)
+}
+
+// FastFingerprint returns the LabelSet's Fingerprint calculated by a faster hashing
+// algorithm, which is, however, more susceptible to hash collisions.
+func (ls LabelSet) FastFingerprint() Fingerprint {
+ return labelSetToFastFingerprint(ls)
+}
+
+// UnmarshalJSON implements the json.Unmarshaler interface.
+func (l *LabelSet) UnmarshalJSON(b []byte) error {
+ var m map[LabelName]LabelValue
+ if err := json.Unmarshal(b, &m); err != nil {
+ return err
+ }
+ // encoding/json only unmarshals maps of the form map[string]T. It treats
+ // LabelName as a string and does not call its UnmarshalJSON method.
+ // Thus, we have to replicate the behavior here.
+ for ln := range m {
+ if !ln.IsValid() {
+ return fmt.Errorf("%q is not a valid label name", ln)
+ }
+ }
+ *l = LabelSet(m)
+ return nil
+}
diff --git a/vendor/github.com/prometheus/common/model/metric.go b/vendor/github.com/prometheus/common/model/metric.go
new file mode 100644
index 0000000..f725090
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/metric.go
@@ -0,0 +1,103 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "fmt"
+ "regexp"
+ "sort"
+ "strings"
+)
+
+var (
+ separator = []byte{0}
+ // MetricNameRE is a regular expression matching valid metric
+ // names. Note that the IsValidMetricName function performs the same
+ // check but faster than a match with this regular expression.
+ MetricNameRE = regexp.MustCompile(`^[a-zA-Z_:][a-zA-Z0-9_:]*$`)
+)
+
+// A Metric is similar to a LabelSet, but the key difference is that a Metric is
+// a singleton and refers to one and only one stream of samples.
+type Metric LabelSet
+
+// Equal compares the metrics.
+func (m Metric) Equal(o Metric) bool {
+ return LabelSet(m).Equal(LabelSet(o))
+}
+
+// Before compares the metrics' underlying label sets.
+func (m Metric) Before(o Metric) bool {
+ return LabelSet(m).Before(LabelSet(o))
+}
+
+// Clone returns a copy of the Metric.
+func (m Metric) Clone() Metric {
+ clone := make(Metric, len(m))
+ for k, v := range m {
+ clone[k] = v
+ }
+ return clone
+}
+
+func (m Metric) String() string {
+ metricName, hasName := m[MetricNameLabel]
+ numLabels := len(m) - 1
+ if !hasName {
+ numLabels = len(m)
+ }
+ labelStrings := make([]string, 0, numLabels)
+ for label, value := range m {
+ if label != MetricNameLabel {
+ labelStrings = append(labelStrings, fmt.Sprintf("%s=%q", label, value))
+ }
+ }
+
+ switch numLabels {
+ case 0:
+ if hasName {
+ return string(metricName)
+ }
+ return "{}"
+ default:
+ sort.Strings(labelStrings)
+ return fmt.Sprintf("%s{%s}", metricName, strings.Join(labelStrings, ", "))
+ }
+}
+
+// Fingerprint returns a Metric's Fingerprint.
+func (m Metric) Fingerprint() Fingerprint {
+ return LabelSet(m).Fingerprint()
+}
+
+// FastFingerprint returns a Metric's Fingerprint calculated by a faster hashing
+// algorithm, which is, however, more susceptible to hash collisions.
+func (m Metric) FastFingerprint() Fingerprint {
+ return LabelSet(m).FastFingerprint()
+}
+
+// IsValidMetricName returns true iff name matches the pattern of MetricNameRE.
+// This function, however, does not use MetricNameRE for the check but a much
+// faster hardcoded implementation.
+func IsValidMetricName(n LabelValue) bool {
+ if len(n) == 0 {
+ return false
+ }
+ for i, b := range n {
+ if !((b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || b == '_' || b == ':' || (b >= '0' && b <= '9' && i > 0)) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/vendor/github.com/prometheus/client_golang/model/metric_test.go b/vendor/github.com/prometheus/common/model/metric_test.go
similarity index 59%
rename from vendor/github.com/prometheus/client_golang/model/metric_test.go
rename to vendor/github.com/prometheus/common/model/metric_test.go
index 5dbc023..06f9de5 100644
--- a/vendor/github.com/prometheus/client_golang/model/metric_test.go
+++ b/vendor/github.com/prometheus/common/model/metric_test.go
@@ -17,17 +17,17 @@ import "testing"
func testMetric(t testing.TB) {
var scenarios = []struct {
- input Metric
+ input LabelSet
fingerprint Fingerprint
fastFingerprint Fingerprint
}{
{
- input: Metric{},
+ input: LabelSet{},
fingerprint: 14695981039346656037,
fastFingerprint: 14695981039346656037,
},
{
- input: Metric{
+ input: LabelSet{
"first_name": "electro",
"occupation": "robot",
"manufacturer": "westinghouse",
@@ -36,14 +36,14 @@ func testMetric(t testing.TB) {
fastFingerprint: 11310079640881077873,
},
{
- input: Metric{
+ input: LabelSet{
"x": "y",
},
fingerprint: 8241431561484471700,
fastFingerprint: 13948396922932177635,
},
{
- input: Metric{
+ input: LabelSet{
"a": "bb",
"b": "c",
},
@@ -51,7 +51,7 @@ func testMetric(t testing.TB) {
fastFingerprint: 3198632812309449502,
},
{
- input: Metric{
+ input: LabelSet{
"a": "b",
"bb": "c",
},
@@ -61,11 +61,13 @@ func testMetric(t testing.TB) {
}
for i, scenario := range scenarios {
- if scenario.fingerprint != scenario.input.Fingerprint() {
- t.Errorf("%d. expected %d, got %d", i, scenario.fingerprint, scenario.input.Fingerprint())
+ input := Metric(scenario.input)
+
+ if scenario.fingerprint != input.Fingerprint() {
+ t.Errorf("%d. expected %d, got %d", i, scenario.fingerprint, input.Fingerprint())
}
- if scenario.fastFingerprint != scenario.input.FastFingerprint() {
- t.Errorf("%d. expected %d, got %d", i, scenario.fastFingerprint, scenario.input.FastFingerprint())
+ if scenario.fastFingerprint != input.FastFingerprint() {
+ t.Errorf("%d. expected %d, got %d", i, scenario.fastFingerprint, input.FastFingerprint())
}
}
}
@@ -80,51 +82,51 @@ func BenchmarkMetric(b *testing.B) {
}
}
-func TestCOWMetric(t *testing.T) {
- testMetric := Metric{
- "to_delete": "test1",
- "to_change": "test2",
- }
-
- scenarios := []struct {
- fn func(*COWMetric)
- out Metric
+func TestMetricNameIsValid(t *testing.T) {
+ var scenarios = []struct {
+ mn LabelValue
+ valid bool
}{
{
- fn: func(cm *COWMetric) {
- cm.Delete("to_delete")
- },
- out: Metric{
- "to_change": "test2",
- },
+ mn: "Avalid_23name",
+ valid: true,
},
{
- fn: func(cm *COWMetric) {
- cm.Set("to_change", "changed")
- },
- out: Metric{
- "to_delete": "test1",
- "to_change": "changed",
- },
+ mn: "_Avalid_23name",
+ valid: true,
+ },
+ {
+ mn: "1valid_23name",
+ valid: false,
+ },
+ {
+ mn: "avalid_23name",
+ valid: true,
+ },
+ {
+ mn: "Ava:lid_23name",
+ valid: true,
+ },
+ {
+ mn: "a lid_23name",
+ valid: false,
+ },
+ {
+ mn: ":leading_colon",
+ valid: true,
+ },
+ {
+ mn: "colon:in:the:middle",
+ valid: true,
},
}
- for i, s := range scenarios {
- orig := testMetric.Clone()
- cm := &COWMetric{
- Metric: orig,
+ for _, s := range scenarios {
+ if IsValidMetricName(s.mn) != s.valid {
+ t.Errorf("Expected %v for %q using IsValidMetricName function", s.valid, s.mn)
}
-
- s.fn(cm)
-
- // Test that the original metric was not modified.
- if !orig.Equal(testMetric) {
- t.Fatalf("%d. original metric changed; expected %v, got %v", i, testMetric, orig)
- }
-
- // Test that the new metric has the right changes.
- if !cm.Metric.Equal(s.out) {
- t.Fatalf("%d. copied metric doesn't contain expected changes; expected %v, got %v", i, s.out, cm.Metric)
+ if MetricNameRE.MatchString(string(s.mn)) != s.valid {
+ t.Errorf("Expected %v for %q using regexp matching", s.valid, s.mn)
}
}
}
diff --git a/vendor/github.com/prometheus/client_golang/model/model.go b/vendor/github.com/prometheus/common/model/model.go
similarity index 84%
rename from vendor/github.com/prometheus/client_golang/model/model.go
rename to vendor/github.com/prometheus/common/model/model.go
index 189c5dc..a7b9691 100644
--- a/vendor/github.com/prometheus/client_golang/model/model.go
+++ b/vendor/github.com/prometheus/common/model/model.go
@@ -11,5 +11,6 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-// Package model contains core representation of Prometheus client primitives.
+// Package model contains common data structures that are shared across
+// Prometheus components and libraries.
package model
diff --git a/vendor/github.com/prometheus/client_golang/model/signature.go b/vendor/github.com/prometheus/common/model/signature.go
similarity index 57%
rename from vendor/github.com/prometheus/client_golang/model/signature.go
rename to vendor/github.com/prometheus/common/model/signature.go
index 7bd58f4..8762b13 100644
--- a/vendor/github.com/prometheus/client_golang/model/signature.go
+++ b/vendor/github.com/prometheus/common/model/signature.go
@@ -14,11 +14,7 @@
package model
import (
- "bytes"
- "hash"
- "hash/fnv"
"sort"
- "sync"
)
// SeparatorByte is a byte that cannot occur in valid UTF-8 sequences and is
@@ -28,30 +24,9 @@ const SeparatorByte byte = 255
var (
// cache the signature of an empty label set.
- emptyLabelSignature = fnv.New64a().Sum64()
-
- hashAndBufPool sync.Pool
+ emptyLabelSignature = hashNew()
)
-type hashAndBuf struct {
- h hash.Hash64
- b bytes.Buffer
-}
-
-func getHashAndBuf() *hashAndBuf {
- hb := hashAndBufPool.Get()
- if hb == nil {
- return &hashAndBuf{h: fnv.New64a()}
- }
- return hb.(*hashAndBuf)
-}
-
-func putHashAndBuf(hb *hashAndBuf) {
- hb.h.Reset()
- hb.b.Reset()
- hashAndBufPool.Put(hb)
-}
-
// LabelsToSignature returns a quasi-unique signature (i.e., fingerprint) for a
// given label set. (Collisions are possible but unlikely if the number of label
// sets the function is applied to is small.)
@@ -66,67 +41,54 @@ func LabelsToSignature(labels map[string]string) uint64 {
}
sort.Strings(labelNames)
- hb := getHashAndBuf()
- defer putHashAndBuf(hb)
-
+ sum := hashNew()
for _, labelName := range labelNames {
- hb.b.WriteString(labelName)
- hb.b.WriteByte(SeparatorByte)
- hb.b.WriteString(labels[labelName])
- hb.b.WriteByte(SeparatorByte)
- hb.h.Write(hb.b.Bytes())
- hb.b.Reset()
+ sum = hashAdd(sum, labelName)
+ sum = hashAddByte(sum, SeparatorByte)
+ sum = hashAdd(sum, labels[labelName])
+ sum = hashAddByte(sum, SeparatorByte)
}
- return hb.h.Sum64()
+ return sum
}
-// metricToFingerprint works exactly as LabelsToSignature but takes a Metric as
+// labelSetToFingerprint works exactly as LabelsToSignature but takes a LabelSet as
// parameter (rather than a label map) and returns a Fingerprint.
-func metricToFingerprint(m Metric) Fingerprint {
- if len(m) == 0 {
+func labelSetToFingerprint(ls LabelSet) Fingerprint {
+ if len(ls) == 0 {
return Fingerprint(emptyLabelSignature)
}
- labelNames := make(LabelNames, 0, len(m))
- for labelName := range m {
+ labelNames := make(LabelNames, 0, len(ls))
+ for labelName := range ls {
labelNames = append(labelNames, labelName)
}
sort.Sort(labelNames)
- hb := getHashAndBuf()
- defer putHashAndBuf(hb)
-
+ sum := hashNew()
for _, labelName := range labelNames {
- hb.b.WriteString(string(labelName))
- hb.b.WriteByte(SeparatorByte)
- hb.b.WriteString(string(m[labelName]))
- hb.b.WriteByte(SeparatorByte)
- hb.h.Write(hb.b.Bytes())
- hb.b.Reset()
+ sum = hashAdd(sum, string(labelName))
+ sum = hashAddByte(sum, SeparatorByte)
+ sum = hashAdd(sum, string(ls[labelName]))
+ sum = hashAddByte(sum, SeparatorByte)
}
- return Fingerprint(hb.h.Sum64())
+ return Fingerprint(sum)
}
-// metricToFastFingerprint works similar to metricToFingerprint but uses a
+// labelSetToFastFingerprint works similar to labelSetToFingerprint but uses a
// faster and less allocation-heavy hash function, which is more susceptible to
// create hash collisions. Therefore, collision detection should be applied.
-func metricToFastFingerprint(m Metric) Fingerprint {
- if len(m) == 0 {
+func labelSetToFastFingerprint(ls LabelSet) Fingerprint {
+ if len(ls) == 0 {
return Fingerprint(emptyLabelSignature)
}
var result uint64
- hb := getHashAndBuf()
- defer putHashAndBuf(hb)
-
- for labelName, labelValue := range m {
- hb.b.WriteString(string(labelName))
- hb.b.WriteByte(SeparatorByte)
- hb.b.WriteString(string(labelValue))
- hb.h.Write(hb.b.Bytes())
- result ^= hb.h.Sum64()
- hb.h.Reset()
- hb.b.Reset()
+ for labelName, labelValue := range ls {
+ sum := hashNew()
+ sum = hashAdd(sum, string(labelName))
+ sum = hashAddByte(sum, SeparatorByte)
+ sum = hashAdd(sum, string(labelValue))
+ result ^= sum
}
return Fingerprint(result)
}
@@ -135,25 +97,21 @@ func metricToFastFingerprint(m Metric) Fingerprint {
// parameter (rather than a label map) and only includes the labels with the
// specified LabelNames into the signature calculation. The labels passed in
// will be sorted by this function.
-func SignatureForLabels(m Metric, labels LabelNames) uint64 {
- if len(m) == 0 || len(labels) == 0 {
+func SignatureForLabels(m Metric, labels ...LabelName) uint64 {
+ if len(labels) == 0 {
return emptyLabelSignature
}
- sort.Sort(labels)
-
- hb := getHashAndBuf()
- defer putHashAndBuf(hb)
+ sort.Sort(LabelNames(labels))
+ sum := hashNew()
for _, label := range labels {
- hb.b.WriteString(string(label))
- hb.b.WriteByte(SeparatorByte)
- hb.b.WriteString(string(m[label]))
- hb.b.WriteByte(SeparatorByte)
- hb.h.Write(hb.b.Bytes())
- hb.b.Reset()
+ sum = hashAdd(sum, string(label))
+ sum = hashAddByte(sum, SeparatorByte)
+ sum = hashAdd(sum, string(m[label]))
+ sum = hashAddByte(sum, SeparatorByte)
}
- return hb.h.Sum64()
+ return sum
}
// SignatureWithoutLabels works like LabelsToSignature but takes a Metric as
@@ -175,16 +133,12 @@ func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64 {
}
sort.Sort(labelNames)
- hb := getHashAndBuf()
- defer putHashAndBuf(hb)
-
+ sum := hashNew()
for _, labelName := range labelNames {
- hb.b.WriteString(string(labelName))
- hb.b.WriteByte(SeparatorByte)
- hb.b.WriteString(string(m[labelName]))
- hb.b.WriteByte(SeparatorByte)
- hb.h.Write(hb.b.Bytes())
- hb.b.Reset()
+ sum = hashAdd(sum, string(labelName))
+ sum = hashAddByte(sum, SeparatorByte)
+ sum = hashAdd(sum, string(m[labelName]))
+ sum = hashAddByte(sum, SeparatorByte)
}
- return hb.h.Sum64()
+ return sum
}
diff --git a/vendor/github.com/prometheus/client_golang/model/signature_test.go b/vendor/github.com/prometheus/common/model/signature_test.go
similarity index 68%
rename from vendor/github.com/prometheus/client_golang/model/signature_test.go
rename to vendor/github.com/prometheus/common/model/signature_test.go
index 01db531..d59c8a8 100644
--- a/vendor/github.com/prometheus/client_golang/model/signature_test.go
+++ b/vendor/github.com/prometheus/common/model/signature_test.go
@@ -45,21 +45,21 @@ func TestLabelsToSignature(t *testing.T) {
func TestMetricToFingerprint(t *testing.T) {
var scenarios = []struct {
- in Metric
+ in LabelSet
out Fingerprint
}{
{
- in: Metric{},
+ in: LabelSet{},
out: 14695981039346656037,
},
{
- in: Metric{"name": "garland, briggs", "fear": "love is not enough"},
+ in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"},
out: 5799056148416392346,
},
}
for i, scenario := range scenarios {
- actual := metricToFingerprint(scenario.in)
+ actual := labelSetToFingerprint(scenario.in)
if actual != scenario.out {
t.Errorf("%d. expected %d, got %d", i, scenario.out, actual)
@@ -69,21 +69,21 @@ func TestMetricToFingerprint(t *testing.T) {
func TestMetricToFastFingerprint(t *testing.T) {
var scenarios = []struct {
- in Metric
+ in LabelSet
out Fingerprint
}{
{
- in: Metric{},
+ in: LabelSet{},
out: 14695981039346656037,
},
{
- in: Metric{"name": "garland, briggs", "fear": "love is not enough"},
+ in: LabelSet{"name": "garland, briggs", "fear": "love is not enough"},
out: 12952432476264840823,
},
}
for i, scenario := range scenarios {
- actual := metricToFastFingerprint(scenario.in)
+ actual := labelSetToFastFingerprint(scenario.in)
if actual != scenario.out {
t.Errorf("%d. expected %d, got %d", i, scenario.out, actual)
@@ -102,6 +102,16 @@ func TestSignatureForLabels(t *testing.T) {
labels: nil,
out: 14695981039346656037,
},
+ {
+ in: Metric{},
+ labels: LabelNames{"empty"},
+ out: 7187873163539638612,
+ },
+ {
+ in: Metric{"name": "garland, briggs", "fear": "love is not enough"},
+ labels: LabelNames{"empty"},
+ out: 7187873163539638612,
+ },
{
in: Metric{"name": "garland, briggs", "fear": "love is not enough"},
labels: LabelNames{"fear", "name"},
@@ -125,7 +135,7 @@ func TestSignatureForLabels(t *testing.T) {
}
for i, scenario := range scenarios {
- actual := SignatureForLabels(scenario.in, scenario.labels)
+ actual := SignatureForLabels(scenario.in, scenario.labels...)
if actual != scenario.out {
t.Errorf("%d. expected %d, got %d", i, scenario.out, actual)
@@ -199,10 +209,10 @@ func BenchmarkLabelToSignatureTriple(b *testing.B) {
benchmarkLabelToSignature(b, map[string]string{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121)
}
-func benchmarkMetricToFingerprint(b *testing.B, m Metric, e Fingerprint) {
+func benchmarkMetricToFingerprint(b *testing.B, ls LabelSet, e Fingerprint) {
for i := 0; i < b.N; i++ {
- if a := metricToFingerprint(m); a != e {
- b.Fatalf("expected signature of %d for %s, got %d", e, m, a)
+ if a := labelSetToFingerprint(ls); a != e {
+ b.Fatalf("expected signature of %d for %s, got %d", e, ls, a)
}
}
}
@@ -212,21 +222,21 @@ func BenchmarkMetricToFingerprintScalar(b *testing.B) {
}
func BenchmarkMetricToFingerprintSingle(b *testing.B) {
- benchmarkMetricToFingerprint(b, Metric{"first-label": "first-label-value"}, 5146282821936882169)
+ benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5146282821936882169)
}
func BenchmarkMetricToFingerprintDouble(b *testing.B) {
- benchmarkMetricToFingerprint(b, Metric{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717)
+ benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 3195800080984914717)
}
func BenchmarkMetricToFingerprintTriple(b *testing.B) {
- benchmarkMetricToFingerprint(b, Metric{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121)
+ benchmarkMetricToFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 13843036195897128121)
}
-func benchmarkMetricToFastFingerprint(b *testing.B, m Metric, e Fingerprint) {
+func benchmarkMetricToFastFingerprint(b *testing.B, ls LabelSet, e Fingerprint) {
for i := 0; i < b.N; i++ {
- if a := metricToFastFingerprint(m); a != e {
- b.Fatalf("expected signature of %d for %s, got %d", e, m, a)
+ if a := labelSetToFastFingerprint(ls); a != e {
+ b.Fatalf("expected signature of %d for %s, got %d", e, ls, a)
}
}
}
@@ -236,18 +246,18 @@ func BenchmarkMetricToFastFingerprintScalar(b *testing.B) {
}
func BenchmarkMetricToFastFingerprintSingle(b *testing.B) {
- benchmarkMetricToFastFingerprint(b, Metric{"first-label": "first-label-value"}, 5147259542624943964)
+ benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value"}, 5147259542624943964)
}
func BenchmarkMetricToFastFingerprintDouble(b *testing.B) {
- benchmarkMetricToFastFingerprint(b, Metric{"first-label": "first-label-value", "second-label": "second-label-value"}, 18269973311206963528)
+ benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value"}, 18269973311206963528)
}
func BenchmarkMetricToFastFingerprintTriple(b *testing.B) {
- benchmarkMetricToFastFingerprint(b, Metric{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676)
+ benchmarkMetricToFastFingerprint(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676)
}
-func TestEmptyLabelSignature(t *testing.T) {
+func BenchmarkEmptyLabelSignature(b *testing.B) {
input := []map[string]string{nil, {}}
var ms runtime.MemStats
@@ -262,11 +272,11 @@ func TestEmptyLabelSignature(t *testing.T) {
runtime.ReadMemStats(&ms)
if got := ms.Alloc; alloc != got {
- t.Fatal("expected LabelsToSignature with empty labels not to perform allocations")
+ b.Fatal("expected LabelsToSignature with empty labels not to perform allocations")
}
}
-func benchmarkMetricToFastFingerprintConc(b *testing.B, m Metric, e Fingerprint, concLevel int) {
+func benchmarkMetricToFastFingerprintConc(b *testing.B, ls LabelSet, e Fingerprint, concLevel int) {
var start, end sync.WaitGroup
start.Add(1)
end.Add(concLevel)
@@ -275,8 +285,8 @@ func benchmarkMetricToFastFingerprintConc(b *testing.B, m Metric, e Fingerprint,
go func() {
start.Wait()
for j := b.N / concLevel; j >= 0; j-- {
- if a := metricToFastFingerprint(m); a != e {
- b.Fatalf("expected signature of %d for %s, got %d", e, m, a)
+ if a := labelSetToFastFingerprint(ls); a != e {
+ b.Fatalf("expected signature of %d for %s, got %d", e, ls, a)
}
}
end.Done()
@@ -288,17 +298,17 @@ func benchmarkMetricToFastFingerprintConc(b *testing.B, m Metric, e Fingerprint,
}
func BenchmarkMetricToFastFingerprintTripleConc1(b *testing.B) {
- benchmarkMetricToFastFingerprintConc(b, Metric{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 1)
+ benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 1)
}
func BenchmarkMetricToFastFingerprintTripleConc2(b *testing.B) {
- benchmarkMetricToFastFingerprintConc(b, Metric{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 2)
+ benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 2)
}
func BenchmarkMetricToFastFingerprintTripleConc4(b *testing.B) {
- benchmarkMetricToFastFingerprintConc(b, Metric{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 4)
+ benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 4)
}
func BenchmarkMetricToFastFingerprintTripleConc8(b *testing.B) {
- benchmarkMetricToFastFingerprintConc(b, Metric{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 8)
+ benchmarkMetricToFastFingerprintConc(b, LabelSet{"first-label": "first-label-value", "second-label": "second-label-value", "third-label": "third-label-value"}, 15738406913934009676, 8)
}
diff --git a/vendor/github.com/prometheus/common/model/silence.go b/vendor/github.com/prometheus/common/model/silence.go
new file mode 100644
index 0000000..7538e29
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/silence.go
@@ -0,0 +1,106 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "encoding/json"
+ "fmt"
+ "regexp"
+ "time"
+)
+
+// Matcher describes a matches the value of a given label.
+type Matcher struct {
+ Name LabelName `json:"name"`
+ Value string `json:"value"`
+ IsRegex bool `json:"isRegex"`
+}
+
+func (m *Matcher) UnmarshalJSON(b []byte) error {
+ type plain Matcher
+ if err := json.Unmarshal(b, (*plain)(m)); err != nil {
+ return err
+ }
+
+ if len(m.Name) == 0 {
+ return fmt.Errorf("label name in matcher must not be empty")
+ }
+ if m.IsRegex {
+ if _, err := regexp.Compile(m.Value); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// Validate returns true iff all fields of the matcher have valid values.
+func (m *Matcher) Validate() error {
+ if !m.Name.IsValid() {
+ return fmt.Errorf("invalid name %q", m.Name)
+ }
+ if m.IsRegex {
+ if _, err := regexp.Compile(m.Value); err != nil {
+ return fmt.Errorf("invalid regular expression %q", m.Value)
+ }
+ } else if !LabelValue(m.Value).IsValid() || len(m.Value) == 0 {
+ return fmt.Errorf("invalid value %q", m.Value)
+ }
+ return nil
+}
+
+// Silence defines the representation of a silence definiton
+// in the Prometheus eco-system.
+type Silence struct {
+ ID uint64 `json:"id,omitempty"`
+
+ Matchers []*Matcher `json:"matchers"`
+
+ StartsAt time.Time `json:"startsAt"`
+ EndsAt time.Time `json:"endsAt"`
+
+ CreatedAt time.Time `json:"createdAt,omitempty"`
+ CreatedBy string `json:"createdBy"`
+ Comment string `json:"comment,omitempty"`
+}
+
+// Validate returns true iff all fields of the silence have valid values.
+func (s *Silence) Validate() error {
+ if len(s.Matchers) == 0 {
+ return fmt.Errorf("at least one matcher required")
+ }
+ for _, m := range s.Matchers {
+ if err := m.Validate(); err != nil {
+ return fmt.Errorf("invalid matcher: %s", err)
+ }
+ }
+ if s.StartsAt.IsZero() {
+ return fmt.Errorf("start time missing")
+ }
+ if s.EndsAt.IsZero() {
+ return fmt.Errorf("end time missing")
+ }
+ if s.EndsAt.Before(s.StartsAt) {
+ return fmt.Errorf("start time must be before end time")
+ }
+ if s.CreatedBy == "" {
+ return fmt.Errorf("creator information missing")
+ }
+ if s.Comment == "" {
+ return fmt.Errorf("comment missing")
+ }
+ if s.CreatedAt.IsZero() {
+ return fmt.Errorf("creation timestamp missing")
+ }
+ return nil
+}
diff --git a/vendor/github.com/prometheus/common/model/silence_test.go b/vendor/github.com/prometheus/common/model/silence_test.go
new file mode 100644
index 0000000..8eaaf07
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/silence_test.go
@@ -0,0 +1,228 @@
+// Copyright 2015 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestMatcherValidate(t *testing.T) {
+ var cases = []struct {
+ matcher *Matcher
+ err string
+ }{
+ {
+ matcher: &Matcher{
+ Name: "name",
+ Value: "value",
+ },
+ },
+ {
+ matcher: &Matcher{
+ Name: "name",
+ Value: "value",
+ IsRegex: true,
+ },
+ },
+ {
+ matcher: &Matcher{
+ Name: "name!",
+ Value: "value",
+ },
+ err: "invalid name",
+ },
+ {
+ matcher: &Matcher{
+ Name: "",
+ Value: "value",
+ },
+ err: "invalid name",
+ },
+ {
+ matcher: &Matcher{
+ Name: "name",
+ Value: "value\xff",
+ },
+ err: "invalid value",
+ },
+ {
+ matcher: &Matcher{
+ Name: "name",
+ Value: "",
+ },
+ err: "invalid value",
+ },
+ }
+
+ for i, c := range cases {
+ err := c.matcher.Validate()
+ if err == nil {
+ if c.err == "" {
+ continue
+ }
+ t.Errorf("%d. Expected error %q but got none", i, c.err)
+ continue
+ }
+ if c.err == "" && err != nil {
+ t.Errorf("%d. Expected no error but got %q", i, err)
+ continue
+ }
+ if !strings.Contains(err.Error(), c.err) {
+ t.Errorf("%d. Expected error to contain %q but got %q", i, c.err, err)
+ }
+ }
+}
+
+func TestSilenceValidate(t *testing.T) {
+ ts := time.Now()
+
+ var cases = []struct {
+ sil *Silence
+ err string
+ }{
+ {
+ sil: &Silence{
+ Matchers: []*Matcher{
+ {Name: "name", Value: "value"},
+ },
+ StartsAt: ts,
+ EndsAt: ts,
+ CreatedAt: ts,
+ CreatedBy: "name",
+ Comment: "comment",
+ },
+ },
+ {
+ sil: &Silence{
+ Matchers: []*Matcher{
+ {Name: "name", Value: "value"},
+ {Name: "name", Value: "value"},
+ {Name: "name", Value: "value"},
+ {Name: "name", Value: "value", IsRegex: true},
+ },
+ StartsAt: ts,
+ EndsAt: ts,
+ CreatedAt: ts,
+ CreatedBy: "name",
+ Comment: "comment",
+ },
+ },
+ {
+ sil: &Silence{
+ Matchers: []*Matcher{
+ {Name: "name", Value: "value"},
+ },
+ StartsAt: ts,
+ EndsAt: ts.Add(-1 * time.Minute),
+ CreatedAt: ts,
+ CreatedBy: "name",
+ Comment: "comment",
+ },
+ err: "start time must be before end time",
+ },
+ {
+ sil: &Silence{
+ Matchers: []*Matcher{
+ {Name: "name", Value: "value"},
+ },
+ StartsAt: ts,
+ CreatedAt: ts,
+ CreatedBy: "name",
+ Comment: "comment",
+ },
+ err: "end time missing",
+ },
+ {
+ sil: &Silence{
+ Matchers: []*Matcher{
+ {Name: "name", Value: "value"},
+ },
+ EndsAt: ts,
+ CreatedAt: ts,
+ CreatedBy: "name",
+ Comment: "comment",
+ },
+ err: "start time missing",
+ },
+ {
+ sil: &Silence{
+ Matchers: []*Matcher{
+ {Name: "!name", Value: "value"},
+ },
+ StartsAt: ts,
+ EndsAt: ts,
+ CreatedAt: ts,
+ CreatedBy: "name",
+ Comment: "comment",
+ },
+ err: "invalid matcher",
+ },
+ {
+ sil: &Silence{
+ Matchers: []*Matcher{
+ {Name: "name", Value: "value"},
+ },
+ StartsAt: ts,
+ EndsAt: ts,
+ CreatedAt: ts,
+ CreatedBy: "name",
+ },
+ err: "comment missing",
+ },
+ {
+ sil: &Silence{
+ Matchers: []*Matcher{
+ {Name: "name", Value: "value"},
+ },
+ StartsAt: ts,
+ EndsAt: ts,
+ CreatedBy: "name",
+ Comment: "comment",
+ },
+ err: "creation timestamp missing",
+ },
+ {
+ sil: &Silence{
+ Matchers: []*Matcher{
+ {Name: "name", Value: "value"},
+ },
+ StartsAt: ts,
+ EndsAt: ts,
+ CreatedAt: ts,
+ Comment: "comment",
+ },
+ err: "creator information missing",
+ },
+ }
+
+ for i, c := range cases {
+ err := c.sil.Validate()
+ if err == nil {
+ if c.err == "" {
+ continue
+ }
+ t.Errorf("%d. Expected error %q but got none", i, c.err)
+ continue
+ }
+ if c.err == "" && err != nil {
+ t.Errorf("%d. Expected no error but got %q", i, err)
+ continue
+ }
+ if !strings.Contains(err.Error(), c.err) {
+ t.Errorf("%d. Expected error to contain %q but got %q", i, c.err, err)
+ }
+ }
+}
diff --git a/vendor/github.com/prometheus/common/model/time.go b/vendor/github.com/prometheus/common/model/time.go
new file mode 100644
index 0000000..7e87f1a
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/time.go
@@ -0,0 +1,261 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "fmt"
+ "math"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+)
+
+const (
+ // MinimumTick is the minimum supported time resolution. This has to be
+ // at least time.Second in order for the code below to work.
+ minimumTick = time.Millisecond
+ // second is the Time duration equivalent to one second.
+ second = int64(time.Second / minimumTick)
+ // The number of nanoseconds per minimum tick.
+ nanosPerTick = int64(minimumTick / time.Nanosecond)
+
+ // Earliest is the earliest Time representable. Handy for
+ // initializing a high watermark.
+ Earliest = Time(math.MinInt64)
+ // Latest is the latest Time representable. Handy for initializing
+ // a low watermark.
+ Latest = Time(math.MaxInt64)
+)
+
+// Time is the number of milliseconds since the epoch
+// (1970-01-01 00:00 UTC) excluding leap seconds.
+type Time int64
+
+// Interval describes and interval between two timestamps.
+type Interval struct {
+ Start, End Time
+}
+
+// Now returns the current time as a Time.
+func Now() Time {
+ return TimeFromUnixNano(time.Now().UnixNano())
+}
+
+// TimeFromUnix returns the Time equivalent to the Unix Time t
+// provided in seconds.
+func TimeFromUnix(t int64) Time {
+ return Time(t * second)
+}
+
+// TimeFromUnixNano returns the Time equivalent to the Unix Time
+// t provided in nanoseconds.
+func TimeFromUnixNano(t int64) Time {
+ return Time(t / nanosPerTick)
+}
+
+// Equal reports whether two Times represent the same instant.
+func (t Time) Equal(o Time) bool {
+ return t == o
+}
+
+// Before reports whether the Time t is before o.
+func (t Time) Before(o Time) bool {
+ return t < o
+}
+
+// After reports whether the Time t is after o.
+func (t Time) After(o Time) bool {
+ return t > o
+}
+
+// Add returns the Time t + d.
+func (t Time) Add(d time.Duration) Time {
+ return t + Time(d/minimumTick)
+}
+
+// Sub returns the Duration t - o.
+func (t Time) Sub(o Time) time.Duration {
+ return time.Duration(t-o) * minimumTick
+}
+
+// Time returns the time.Time representation of t.
+func (t Time) Time() time.Time {
+ return time.Unix(int64(t)/second, (int64(t)%second)*nanosPerTick)
+}
+
+// Unix returns t as a Unix time, the number of seconds elapsed
+// since January 1, 1970 UTC.
+func (t Time) Unix() int64 {
+ return int64(t) / second
+}
+
+// UnixNano returns t as a Unix time, the number of nanoseconds elapsed
+// since January 1, 1970 UTC.
+func (t Time) UnixNano() int64 {
+ return int64(t) * nanosPerTick
+}
+
+// The number of digits after the dot.
+var dotPrecision = int(math.Log10(float64(second)))
+
+// String returns a string representation of the Time.
+func (t Time) String() string {
+ return strconv.FormatFloat(float64(t)/float64(second), 'f', -1, 64)
+}
+
+// MarshalJSON implements the json.Marshaler interface.
+func (t Time) MarshalJSON() ([]byte, error) {
+ return []byte(t.String()), nil
+}
+
+// UnmarshalJSON implements the json.Unmarshaler interface.
+func (t *Time) UnmarshalJSON(b []byte) error {
+ p := strings.Split(string(b), ".")
+ switch len(p) {
+ case 1:
+ v, err := strconv.ParseInt(string(p[0]), 10, 64)
+ if err != nil {
+ return err
+ }
+ *t = Time(v * second)
+
+ case 2:
+ v, err := strconv.ParseInt(string(p[0]), 10, 64)
+ if err != nil {
+ return err
+ }
+ v *= second
+
+ prec := dotPrecision - len(p[1])
+ if prec < 0 {
+ p[1] = p[1][:dotPrecision]
+ } else if prec > 0 {
+ p[1] = p[1] + strings.Repeat("0", prec)
+ }
+
+ va, err := strconv.ParseInt(p[1], 10, 32)
+ if err != nil {
+ return err
+ }
+
+ *t = Time(v + va)
+
+ default:
+ return fmt.Errorf("invalid time %q", string(b))
+ }
+ return nil
+}
+
+// Duration wraps time.Duration. It is used to parse the custom duration format
+// from YAML.
+// This type should not propagate beyond the scope of input/output processing.
+type Duration time.Duration
+
+// Set implements pflag/flag.Value
+func (d *Duration) Set(s string) error {
+ var err error
+ *d, err = ParseDuration(s)
+ return err
+}
+
+// Type implements pflag.Value
+func (d *Duration) Type() string {
+ return "duration"
+}
+
+var durationRE = regexp.MustCompile("^([0-9]+)(y|w|d|h|m|s|ms)$")
+
+// ParseDuration parses a string into a time.Duration, assuming that a year
+// always has 365d, a week always has 7d, and a day always has 24h.
+func ParseDuration(durationStr string) (Duration, error) {
+ matches := durationRE.FindStringSubmatch(durationStr)
+ if len(matches) != 3 {
+ return 0, fmt.Errorf("not a valid duration string: %q", durationStr)
+ }
+ var (
+ n, _ = strconv.Atoi(matches[1])
+ dur = time.Duration(n) * time.Millisecond
+ )
+ switch unit := matches[2]; unit {
+ case "y":
+ dur *= 1000 * 60 * 60 * 24 * 365
+ case "w":
+ dur *= 1000 * 60 * 60 * 24 * 7
+ case "d":
+ dur *= 1000 * 60 * 60 * 24
+ case "h":
+ dur *= 1000 * 60 * 60
+ case "m":
+ dur *= 1000 * 60
+ case "s":
+ dur *= 1000
+ case "ms":
+ // Value already correct
+ default:
+ return 0, fmt.Errorf("invalid time unit in duration string: %q", unit)
+ }
+ return Duration(dur), nil
+}
+
+func (d Duration) String() string {
+ var (
+ ms = int64(time.Duration(d) / time.Millisecond)
+ unit = "ms"
+ )
+ factors := map[string]int64{
+ "y": 1000 * 60 * 60 * 24 * 365,
+ "w": 1000 * 60 * 60 * 24 * 7,
+ "d": 1000 * 60 * 60 * 24,
+ "h": 1000 * 60 * 60,
+ "m": 1000 * 60,
+ "s": 1000,
+ "ms": 1,
+ }
+
+ switch int64(0) {
+ case ms % factors["y"]:
+ unit = "y"
+ case ms % factors["w"]:
+ unit = "w"
+ case ms % factors["d"]:
+ unit = "d"
+ case ms % factors["h"]:
+ unit = "h"
+ case ms % factors["m"]:
+ unit = "m"
+ case ms % factors["s"]:
+ unit = "s"
+ }
+ return fmt.Sprintf("%v%v", ms/factors[unit], unit)
+}
+
+// MarshalYAML implements the yaml.Marshaler interface.
+func (d Duration) MarshalYAML() (interface{}, error) {
+ return d.String(), nil
+}
+
+// UnmarshalYAML implements the yaml.Unmarshaler interface.
+func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
+ var s string
+ if err := unmarshal(&s); err != nil {
+ return err
+ }
+ dur, err := ParseDuration(s)
+ if err != nil {
+ return err
+ }
+ *d = dur
+ return nil
+}
diff --git a/vendor/github.com/prometheus/client_golang/model/timestamp_test.go b/vendor/github.com/prometheus/common/model/time_test.go
similarity index 59%
rename from vendor/github.com/prometheus/client_golang/model/timestamp_test.go
rename to vendor/github.com/prometheus/common/model/time_test.go
index fa028a4..45ffd87 100644
--- a/vendor/github.com/prometheus/client_golang/model/timestamp_test.go
+++ b/vendor/github.com/prometheus/common/model/time_test.go
@@ -15,13 +15,13 @@ package model
import (
"testing"
- native_time "time"
+ "time"
)
func TestComparators(t *testing.T) {
- t1a := TimestampFromUnix(0)
- t1b := TimestampFromUnix(0)
- t2 := TimestampFromUnix(2*second - 1)
+ t1a := TimeFromUnix(0)
+ t1b := TimeFromUnix(0)
+ t2 := TimeFromUnix(2*second - 1)
if !t1a.Equal(t1b) {
t.Fatalf("Expected %s to be equal to %s", t1a, t1b)
@@ -45,21 +45,21 @@ func TestComparators(t *testing.T) {
}
}
-func TestTimestampConversions(t *testing.T) {
+func TestTimeConversions(t *testing.T) {
unixSecs := int64(1136239445)
unixNsecs := int64(123456789)
- unixNano := unixSecs*1000000000 + unixNsecs
+ unixNano := unixSecs*1e9 + unixNsecs
- t1 := native_time.Unix(unixSecs, unixNsecs-unixNsecs%nanosPerTick)
- t2 := native_time.Unix(unixSecs, unixNsecs)
+ t1 := time.Unix(unixSecs, unixNsecs-unixNsecs%nanosPerTick)
+ t2 := time.Unix(unixSecs, unixNsecs)
- ts := TimestampFromUnixNano(unixNano)
+ ts := TimeFromUnixNano(unixNano)
if !ts.Time().Equal(t1) {
t.Fatalf("Expected %s, got %s", t1, ts.Time())
}
// Test available precision.
- ts = TimestampFromTime(t2)
+ ts = TimeFromUnixNano(t2.UnixNano())
if !ts.Time().Equal(t1) {
t.Fatalf("Expected %s, got %s", t1, ts.Time())
}
@@ -70,10 +70,10 @@ func TestTimestampConversions(t *testing.T) {
}
func TestDuration(t *testing.T) {
- duration := native_time.Second + native_time.Minute + native_time.Hour
- goTime := native_time.Unix(1136239445, 0)
+ duration := time.Second + time.Minute + time.Hour
+ goTime := time.Unix(1136239445, 0)
- ts := TimestampFromTime(goTime)
+ ts := TimeFromUnix(goTime.Unix())
if !goTime.Add(duration).Equal(ts.Add(duration).Time()) {
t.Fatalf("Expected %s to be equal to %s", goTime.Add(duration), ts.Add(duration))
}
@@ -84,3 +84,46 @@ func TestDuration(t *testing.T) {
t.Fatalf("Expected %s to be equal to %s", delta, duration)
}
}
+
+func TestParseDuration(t *testing.T) {
+ var cases = []struct {
+ in string
+ out time.Duration
+ }{
+ {
+ in: "324ms",
+ out: 324 * time.Millisecond,
+ }, {
+ in: "3s",
+ out: 3 * time.Second,
+ }, {
+ in: "5m",
+ out: 5 * time.Minute,
+ }, {
+ in: "1h",
+ out: time.Hour,
+ }, {
+ in: "4d",
+ out: 4 * 24 * time.Hour,
+ }, {
+ in: "3w",
+ out: 3 * 7 * 24 * time.Hour,
+ }, {
+ in: "10y",
+ out: 10 * 365 * 24 * time.Hour,
+ },
+ }
+
+ for _, c := range cases {
+ d, err := ParseDuration(c.in)
+ if err != nil {
+ t.Errorf("Unexpected error on input %q", c.in)
+ }
+ if time.Duration(d) != c.out {
+ t.Errorf("Expected %v but got %v", c.out, d)
+ }
+ if d.String() != c.in {
+ t.Errorf("Expected duration string %q but got %q", c.in, d.String())
+ }
+ }
+}
diff --git a/vendor/github.com/prometheus/common/model/value.go b/vendor/github.com/prometheus/common/model/value.go
new file mode 100644
index 0000000..c9ed3ff
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/value.go
@@ -0,0 +1,416 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "encoding/json"
+ "fmt"
+ "math"
+ "sort"
+ "strconv"
+ "strings"
+)
+
+var (
+ // ZeroSamplePair is the pseudo zero-value of SamplePair used to signal a
+ // non-existing sample pair. It is a SamplePair with timestamp Earliest and
+ // value 0.0. Note that the natural zero value of SamplePair has a timestamp
+ // of 0, which is possible to appear in a real SamplePair and thus not
+ // suitable to signal a non-existing SamplePair.
+ ZeroSamplePair = SamplePair{Timestamp: Earliest}
+
+ // ZeroSample is the pseudo zero-value of Sample used to signal a
+ // non-existing sample. It is a Sample with timestamp Earliest, value 0.0,
+ // and metric nil. Note that the natural zero value of Sample has a timestamp
+ // of 0, which is possible to appear in a real Sample and thus not suitable
+ // to signal a non-existing Sample.
+ ZeroSample = Sample{Timestamp: Earliest}
+)
+
+// A SampleValue is a representation of a value for a given sample at a given
+// time.
+type SampleValue float64
+
+// MarshalJSON implements json.Marshaler.
+func (v SampleValue) MarshalJSON() ([]byte, error) {
+ return json.Marshal(v.String())
+}
+
+// UnmarshalJSON implements json.Unmarshaler.
+func (v *SampleValue) UnmarshalJSON(b []byte) error {
+ if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' {
+ return fmt.Errorf("sample value must be a quoted string")
+ }
+ f, err := strconv.ParseFloat(string(b[1:len(b)-1]), 64)
+ if err != nil {
+ return err
+ }
+ *v = SampleValue(f)
+ return nil
+}
+
+// Equal returns true if the value of v and o is equal or if both are NaN. Note
+// that v==o is false if both are NaN. If you want the conventional float
+// behavior, use == to compare two SampleValues.
+func (v SampleValue) Equal(o SampleValue) bool {
+ if v == o {
+ return true
+ }
+ return math.IsNaN(float64(v)) && math.IsNaN(float64(o))
+}
+
+func (v SampleValue) String() string {
+ return strconv.FormatFloat(float64(v), 'f', -1, 64)
+}
+
+// SamplePair pairs a SampleValue with a Timestamp.
+type SamplePair struct {
+ Timestamp Time
+ Value SampleValue
+}
+
+// MarshalJSON implements json.Marshaler.
+func (s SamplePair) MarshalJSON() ([]byte, error) {
+ t, err := json.Marshal(s.Timestamp)
+ if err != nil {
+ return nil, err
+ }
+ v, err := json.Marshal(s.Value)
+ if err != nil {
+ return nil, err
+ }
+ return []byte(fmt.Sprintf("[%s,%s]", t, v)), nil
+}
+
+// UnmarshalJSON implements json.Unmarshaler.
+func (s *SamplePair) UnmarshalJSON(b []byte) error {
+ v := [...]json.Unmarshaler{&s.Timestamp, &s.Value}
+ return json.Unmarshal(b, &v)
+}
+
+// Equal returns true if this SamplePair and o have equal Values and equal
+// Timestamps. The sematics of Value equality is defined by SampleValue.Equal.
+func (s *SamplePair) Equal(o *SamplePair) bool {
+ return s == o || (s.Value.Equal(o.Value) && s.Timestamp.Equal(o.Timestamp))
+}
+
+func (s SamplePair) String() string {
+ return fmt.Sprintf("%s @[%s]", s.Value, s.Timestamp)
+}
+
+// Sample is a sample pair associated with a metric.
+type Sample struct {
+ Metric Metric `json:"metric"`
+ Value SampleValue `json:"value"`
+ Timestamp Time `json:"timestamp"`
+}
+
+// Equal compares first the metrics, then the timestamp, then the value. The
+// sematics of value equality is defined by SampleValue.Equal.
+func (s *Sample) Equal(o *Sample) bool {
+ if s == o {
+ return true
+ }
+
+ if !s.Metric.Equal(o.Metric) {
+ return false
+ }
+ if !s.Timestamp.Equal(o.Timestamp) {
+ return false
+ }
+
+ return s.Value.Equal(o.Value)
+}
+
+func (s Sample) String() string {
+ return fmt.Sprintf("%s => %s", s.Metric, SamplePair{
+ Timestamp: s.Timestamp,
+ Value: s.Value,
+ })
+}
+
+// MarshalJSON implements json.Marshaler.
+func (s Sample) MarshalJSON() ([]byte, error) {
+ v := struct {
+ Metric Metric `json:"metric"`
+ Value SamplePair `json:"value"`
+ }{
+ Metric: s.Metric,
+ Value: SamplePair{
+ Timestamp: s.Timestamp,
+ Value: s.Value,
+ },
+ }
+
+ return json.Marshal(&v)
+}
+
+// UnmarshalJSON implements json.Unmarshaler.
+func (s *Sample) UnmarshalJSON(b []byte) error {
+ v := struct {
+ Metric Metric `json:"metric"`
+ Value SamplePair `json:"value"`
+ }{
+ Metric: s.Metric,
+ Value: SamplePair{
+ Timestamp: s.Timestamp,
+ Value: s.Value,
+ },
+ }
+
+ if err := json.Unmarshal(b, &v); err != nil {
+ return err
+ }
+
+ s.Metric = v.Metric
+ s.Timestamp = v.Value.Timestamp
+ s.Value = v.Value.Value
+
+ return nil
+}
+
+// Samples is a sortable Sample slice. It implements sort.Interface.
+type Samples []*Sample
+
+func (s Samples) Len() int {
+ return len(s)
+}
+
+// Less compares first the metrics, then the timestamp.
+func (s Samples) Less(i, j int) bool {
+ switch {
+ case s[i].Metric.Before(s[j].Metric):
+ return true
+ case s[j].Metric.Before(s[i].Metric):
+ return false
+ case s[i].Timestamp.Before(s[j].Timestamp):
+ return true
+ default:
+ return false
+ }
+}
+
+func (s Samples) Swap(i, j int) {
+ s[i], s[j] = s[j], s[i]
+}
+
+// Equal compares two sets of samples and returns true if they are equal.
+func (s Samples) Equal(o Samples) bool {
+ if len(s) != len(o) {
+ return false
+ }
+
+ for i, sample := range s {
+ if !sample.Equal(o[i]) {
+ return false
+ }
+ }
+ return true
+}
+
+// SampleStream is a stream of Values belonging to an attached COWMetric.
+type SampleStream struct {
+ Metric Metric `json:"metric"`
+ Values []SamplePair `json:"values"`
+}
+
+func (ss SampleStream) String() string {
+ vals := make([]string, len(ss.Values))
+ for i, v := range ss.Values {
+ vals[i] = v.String()
+ }
+ return fmt.Sprintf("%s =>\n%s", ss.Metric, strings.Join(vals, "\n"))
+}
+
+// Value is a generic interface for values resulting from a query evaluation.
+type Value interface {
+ Type() ValueType
+ String() string
+}
+
+func (Matrix) Type() ValueType { return ValMatrix }
+func (Vector) Type() ValueType { return ValVector }
+func (*Scalar) Type() ValueType { return ValScalar }
+func (*String) Type() ValueType { return ValString }
+
+type ValueType int
+
+const (
+ ValNone ValueType = iota
+ ValScalar
+ ValVector
+ ValMatrix
+ ValString
+)
+
+// MarshalJSON implements json.Marshaler.
+func (et ValueType) MarshalJSON() ([]byte, error) {
+ return json.Marshal(et.String())
+}
+
+func (et *ValueType) UnmarshalJSON(b []byte) error {
+ var s string
+ if err := json.Unmarshal(b, &s); err != nil {
+ return err
+ }
+ switch s {
+ case "":
+ *et = ValNone
+ case "scalar":
+ *et = ValScalar
+ case "vector":
+ *et = ValVector
+ case "matrix":
+ *et = ValMatrix
+ case "string":
+ *et = ValString
+ default:
+ return fmt.Errorf("unknown value type %q", s)
+ }
+ return nil
+}
+
+func (e ValueType) String() string {
+ switch e {
+ case ValNone:
+ return ""
+ case ValScalar:
+ return "scalar"
+ case ValVector:
+ return "vector"
+ case ValMatrix:
+ return "matrix"
+ case ValString:
+ return "string"
+ }
+ panic("ValueType.String: unhandled value type")
+}
+
+// Scalar is a scalar value evaluated at the set timestamp.
+type Scalar struct {
+ Value SampleValue `json:"value"`
+ Timestamp Time `json:"timestamp"`
+}
+
+func (s Scalar) String() string {
+ return fmt.Sprintf("scalar: %v @[%v]", s.Value, s.Timestamp)
+}
+
+// MarshalJSON implements json.Marshaler.
+func (s Scalar) MarshalJSON() ([]byte, error) {
+ v := strconv.FormatFloat(float64(s.Value), 'f', -1, 64)
+ return json.Marshal([...]interface{}{s.Timestamp, string(v)})
+}
+
+// UnmarshalJSON implements json.Unmarshaler.
+func (s *Scalar) UnmarshalJSON(b []byte) error {
+ var f string
+ v := [...]interface{}{&s.Timestamp, &f}
+
+ if err := json.Unmarshal(b, &v); err != nil {
+ return err
+ }
+
+ value, err := strconv.ParseFloat(f, 64)
+ if err != nil {
+ return fmt.Errorf("error parsing sample value: %s", err)
+ }
+ s.Value = SampleValue(value)
+ return nil
+}
+
+// String is a string value evaluated at the set timestamp.
+type String struct {
+ Value string `json:"value"`
+ Timestamp Time `json:"timestamp"`
+}
+
+func (s *String) String() string {
+ return s.Value
+}
+
+// MarshalJSON implements json.Marshaler.
+func (s String) MarshalJSON() ([]byte, error) {
+ return json.Marshal([]interface{}{s.Timestamp, s.Value})
+}
+
+// UnmarshalJSON implements json.Unmarshaler.
+func (s *String) UnmarshalJSON(b []byte) error {
+ v := [...]interface{}{&s.Timestamp, &s.Value}
+ return json.Unmarshal(b, &v)
+}
+
+// Vector is basically only an alias for Samples, but the
+// contract is that in a Vector, all Samples have the same timestamp.
+type Vector []*Sample
+
+func (vec Vector) String() string {
+ entries := make([]string, len(vec))
+ for i, s := range vec {
+ entries[i] = s.String()
+ }
+ return strings.Join(entries, "\n")
+}
+
+func (vec Vector) Len() int { return len(vec) }
+func (vec Vector) Swap(i, j int) { vec[i], vec[j] = vec[j], vec[i] }
+
+// Less compares first the metrics, then the timestamp.
+func (vec Vector) Less(i, j int) bool {
+ switch {
+ case vec[i].Metric.Before(vec[j].Metric):
+ return true
+ case vec[j].Metric.Before(vec[i].Metric):
+ return false
+ case vec[i].Timestamp.Before(vec[j].Timestamp):
+ return true
+ default:
+ return false
+ }
+}
+
+// Equal compares two sets of samples and returns true if they are equal.
+func (vec Vector) Equal(o Vector) bool {
+ if len(vec) != len(o) {
+ return false
+ }
+
+ for i, sample := range vec {
+ if !sample.Equal(o[i]) {
+ return false
+ }
+ }
+ return true
+}
+
+// Matrix is a list of time series.
+type Matrix []*SampleStream
+
+func (m Matrix) Len() int { return len(m) }
+func (m Matrix) Less(i, j int) bool { return m[i].Metric.Before(m[j].Metric) }
+func (m Matrix) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
+
+func (mat Matrix) String() string {
+ matCp := make(Matrix, len(mat))
+ copy(matCp, mat)
+ sort.Sort(matCp)
+
+ strs := make([]string, len(matCp))
+
+ for i, ss := range matCp {
+ strs[i] = ss.String()
+ }
+
+ return strings.Join(strs, "\n")
+}
diff --git a/vendor/github.com/prometheus/common/model/value_test.go b/vendor/github.com/prometheus/common/model/value_test.go
new file mode 100644
index 0000000..b97dcf8
--- /dev/null
+++ b/vendor/github.com/prometheus/common/model/value_test.go
@@ -0,0 +1,468 @@
+// Copyright 2013 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package model
+
+import (
+ "encoding/json"
+ "math"
+ "reflect"
+ "sort"
+ "testing"
+)
+
+func TestEqualValues(t *testing.T) {
+ tests := map[string]struct {
+ in1, in2 SampleValue
+ want bool
+ }{
+ "equal floats": {
+ in1: 3.14,
+ in2: 3.14,
+ want: true,
+ },
+ "unequal floats": {
+ in1: 3.14,
+ in2: 3.1415,
+ want: false,
+ },
+ "positive inifinities": {
+ in1: SampleValue(math.Inf(+1)),
+ in2: SampleValue(math.Inf(+1)),
+ want: true,
+ },
+ "negative inifinities": {
+ in1: SampleValue(math.Inf(-1)),
+ in2: SampleValue(math.Inf(-1)),
+ want: true,
+ },
+ "different inifinities": {
+ in1: SampleValue(math.Inf(+1)),
+ in2: SampleValue(math.Inf(-1)),
+ want: false,
+ },
+ "number and infinity": {
+ in1: 42,
+ in2: SampleValue(math.Inf(+1)),
+ want: false,
+ },
+ "number and NaN": {
+ in1: 42,
+ in2: SampleValue(math.NaN()),
+ want: false,
+ },
+ "NaNs": {
+ in1: SampleValue(math.NaN()),
+ in2: SampleValue(math.NaN()),
+ want: true, // !!!
+ },
+ }
+
+ for name, test := range tests {
+ got := test.in1.Equal(test.in2)
+ if got != test.want {
+ t.Errorf("Comparing %s, %f and %f: got %t, want %t", name, test.in1, test.in2, got, test.want)
+ }
+ }
+}
+
+func TestEqualSamples(t *testing.T) {
+ testSample := &Sample{}
+
+ tests := map[string]struct {
+ in1, in2 *Sample
+ want bool
+ }{
+ "equal pointers": {
+ in1: testSample,
+ in2: testSample,
+ want: true,
+ },
+ "different metrics": {
+ in1: &Sample{Metric: Metric{"foo": "bar"}},
+ in2: &Sample{Metric: Metric{"foo": "biz"}},
+ want: false,
+ },
+ "different timestamp": {
+ in1: &Sample{Timestamp: 0},
+ in2: &Sample{Timestamp: 1},
+ want: false,
+ },
+ "different value": {
+ in1: &Sample{Value: 0},
+ in2: &Sample{Value: 1},
+ want: false,
+ },
+ "equal samples": {
+ in1: &Sample{
+ Metric: Metric{"foo": "bar"},
+ Timestamp: 0,
+ Value: 1,
+ },
+ in2: &Sample{
+ Metric: Metric{"foo": "bar"},
+ Timestamp: 0,
+ Value: 1,
+ },
+ want: true,
+ },
+ }
+
+ for name, test := range tests {
+ got := test.in1.Equal(test.in2)
+ if got != test.want {
+ t.Errorf("Comparing %s, %v and %v: got %t, want %t", name, test.in1, test.in2, got, test.want)
+ }
+ }
+
+}
+
+func TestSamplePairJSON(t *testing.T) {
+ input := []struct {
+ plain string
+ value SamplePair
+ }{
+ {
+ plain: `[1234.567,"123.1"]`,
+ value: SamplePair{
+ Value: 123.1,
+ Timestamp: 1234567,
+ },
+ },
+ }
+
+ for _, test := range input {
+ b, err := json.Marshal(test.value)
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+
+ if string(b) != test.plain {
+ t.Errorf("encoding error: expected %q, got %q", test.plain, b)
+ continue
+ }
+
+ var sp SamplePair
+ err = json.Unmarshal(b, &sp)
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+
+ if sp != test.value {
+ t.Errorf("decoding error: expected %v, got %v", test.value, sp)
+ }
+ }
+}
+
+func TestSampleJSON(t *testing.T) {
+ input := []struct {
+ plain string
+ value Sample
+ }{
+ {
+ plain: `{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}`,
+ value: Sample{
+ Metric: Metric{
+ MetricNameLabel: "test_metric",
+ },
+ Value: 123.1,
+ Timestamp: 1234567,
+ },
+ },
+ }
+
+ for _, test := range input {
+ b, err := json.Marshal(test.value)
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+
+ if string(b) != test.plain {
+ t.Errorf("encoding error: expected %q, got %q", test.plain, b)
+ continue
+ }
+
+ var sv Sample
+ err = json.Unmarshal(b, &sv)
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+
+ if !reflect.DeepEqual(sv, test.value) {
+ t.Errorf("decoding error: expected %v, got %v", test.value, sv)
+ }
+ }
+}
+
+func TestVectorJSON(t *testing.T) {
+ input := []struct {
+ plain string
+ value Vector
+ }{
+ {
+ plain: `[]`,
+ value: Vector{},
+ },
+ {
+ plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]}]`,
+ value: Vector{&Sample{
+ Metric: Metric{
+ MetricNameLabel: "test_metric",
+ },
+ Value: 123.1,
+ Timestamp: 1234567,
+ }},
+ },
+ {
+ plain: `[{"metric":{"__name__":"test_metric"},"value":[1234.567,"123.1"]},{"metric":{"foo":"bar"},"value":[1.234,"+Inf"]}]`,
+ value: Vector{
+ &Sample{
+ Metric: Metric{
+ MetricNameLabel: "test_metric",
+ },
+ Value: 123.1,
+ Timestamp: 1234567,
+ },
+ &Sample{
+ Metric: Metric{
+ "foo": "bar",
+ },
+ Value: SampleValue(math.Inf(1)),
+ Timestamp: 1234,
+ },
+ },
+ },
+ }
+
+ for _, test := range input {
+ b, err := json.Marshal(test.value)
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+
+ if string(b) != test.plain {
+ t.Errorf("encoding error: expected %q, got %q", test.plain, b)
+ continue
+ }
+
+ var vec Vector
+ err = json.Unmarshal(b, &vec)
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+
+ if !reflect.DeepEqual(vec, test.value) {
+ t.Errorf("decoding error: expected %v, got %v", test.value, vec)
+ }
+ }
+}
+
+func TestScalarJSON(t *testing.T) {
+ input := []struct {
+ plain string
+ value Scalar
+ }{
+ {
+ plain: `[123.456,"456"]`,
+ value: Scalar{
+ Timestamp: 123456,
+ Value: 456,
+ },
+ },
+ {
+ plain: `[123123.456,"+Inf"]`,
+ value: Scalar{
+ Timestamp: 123123456,
+ Value: SampleValue(math.Inf(1)),
+ },
+ },
+ {
+ plain: `[123123.456,"-Inf"]`,
+ value: Scalar{
+ Timestamp: 123123456,
+ Value: SampleValue(math.Inf(-1)),
+ },
+ },
+ }
+
+ for _, test := range input {
+ b, err := json.Marshal(test.value)
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+
+ if string(b) != test.plain {
+ t.Errorf("encoding error: expected %q, got %q", test.plain, b)
+ continue
+ }
+
+ var sv Scalar
+ err = json.Unmarshal(b, &sv)
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+
+ if sv != test.value {
+ t.Errorf("decoding error: expected %v, got %v", test.value, sv)
+ }
+ }
+}
+
+func TestStringJSON(t *testing.T) {
+ input := []struct {
+ plain string
+ value String
+ }{
+ {
+ plain: `[123.456,"test"]`,
+ value: String{
+ Timestamp: 123456,
+ Value: "test",
+ },
+ },
+ {
+ plain: `[123123.456,"台北"]`,
+ value: String{
+ Timestamp: 123123456,
+ Value: "台北",
+ },
+ },
+ }
+
+ for _, test := range input {
+ b, err := json.Marshal(test.value)
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+
+ if string(b) != test.plain {
+ t.Errorf("encoding error: expected %q, got %q", test.plain, b)
+ continue
+ }
+
+ var sv String
+ err = json.Unmarshal(b, &sv)
+ if err != nil {
+ t.Error(err)
+ continue
+ }
+
+ if sv != test.value {
+ t.Errorf("decoding error: expected %v, got %v", test.value, sv)
+ }
+ }
+}
+
+func TestVectorSort(t *testing.T) {
+ input := Vector{
+ &Sample{
+ Metric: Metric{
+ MetricNameLabel: "A",
+ },
+ Timestamp: 1,
+ },
+ &Sample{
+ Metric: Metric{
+ MetricNameLabel: "A",
+ },
+ Timestamp: 2,
+ },
+ &Sample{
+ Metric: Metric{
+ MetricNameLabel: "C",
+ },
+ Timestamp: 1,
+ },
+ &Sample{
+ Metric: Metric{
+ MetricNameLabel: "C",
+ },
+ Timestamp: 2,
+ },
+ &Sample{
+ Metric: Metric{
+ MetricNameLabel: "B",
+ },
+ Timestamp: 1,
+ },
+ &Sample{
+ Metric: Metric{
+ MetricNameLabel: "B",
+ },
+ Timestamp: 2,
+ },
+ }
+
+ expected := Vector{
+ &Sample{
+ Metric: Metric{
+ MetricNameLabel: "A",
+ },
+ Timestamp: 1,
+ },
+ &Sample{
+ Metric: Metric{
+ MetricNameLabel: "A",
+ },
+ Timestamp: 2,
+ },
+ &Sample{
+ Metric: Metric{
+ MetricNameLabel: "B",
+ },
+ Timestamp: 1,
+ },
+ &Sample{
+ Metric: Metric{
+ MetricNameLabel: "B",
+ },
+ Timestamp: 2,
+ },
+ &Sample{
+ Metric: Metric{
+ MetricNameLabel: "C",
+ },
+ Timestamp: 1,
+ },
+ &Sample{
+ Metric: Metric{
+ MetricNameLabel: "C",
+ },
+ Timestamp: 2,
+ },
+ }
+
+ sort.Sort(input)
+
+ for i, actual := range input {
+ actualFp := actual.Metric.Fingerprint()
+ expectedFp := expected[i].Metric.Fingerprint()
+
+ if actualFp != expectedFp {
+ t.Fatalf("%d. Incorrect fingerprint. Got %s; want %s", i, actualFp.String(), expectedFp.String())
+ }
+
+ if actual.Timestamp != expected[i].Timestamp {
+ t.Fatalf("%d. Incorrect timestamp. Got %s; want %s", i, actual.Timestamp, expected[i].Timestamp)
+ }
+ }
+}
diff --git a/vendor/github.com/prometheus/common/promlog/flag/flag.go b/vendor/github.com/prometheus/common/promlog/flag/flag.go
new file mode 100644
index 0000000..b9d361e
--- /dev/null
+++ b/vendor/github.com/prometheus/common/promlog/flag/flag.go
@@ -0,0 +1,33 @@
+// Copyright 2017 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package flag
+
+import (
+ "github.com/prometheus/common/promlog"
+ kingpin "gopkg.in/alecthomas/kingpin.v2"
+)
+
+// LevelFlagName is the canonical flag name to configure the allowed log level
+// within Prometheus projects.
+const LevelFlagName = "log.level"
+
+// LevelFlagHelp is the help description for the log.level flag.
+const LevelFlagHelp = "Only log messages with the given severity or above. One of: [debug, info, warn, error]"
+
+// AddFlags adds the flags used by this package to the Kingpin application.
+// To use the default Kingpin application, call AddFlags(kingpin.CommandLine)
+func AddFlags(a *kingpin.Application, logLevel *promlog.AllowedLevel) {
+ a.Flag(LevelFlagName, LevelFlagHelp).
+ Default("info").SetValue(logLevel)
+}
diff --git a/vendor/github.com/prometheus/common/promlog/log.go b/vendor/github.com/prometheus/common/promlog/log.go
new file mode 100644
index 0000000..cf8307a
--- /dev/null
+++ b/vendor/github.com/prometheus/common/promlog/log.go
@@ -0,0 +1,63 @@
+// Copyright 2017 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package promlog defines standardised ways to initialize Go kit loggers
+// across Prometheus components.
+// It should typically only ever be imported by main packages.
+package promlog
+
+import (
+ "os"
+
+ "github.com/go-kit/kit/log"
+ "github.com/go-kit/kit/log/level"
+ "github.com/pkg/errors"
+)
+
+// AllowedLevel is a settable identifier for the minimum level a log entry
+// must be have.
+type AllowedLevel struct {
+ s string
+ o level.Option
+}
+
+func (l *AllowedLevel) String() string {
+ return l.s
+}
+
+// Set updates the value of the allowed level.
+func (l *AllowedLevel) Set(s string) error {
+ switch s {
+ case "debug":
+ l.o = level.AllowDebug()
+ case "info":
+ l.o = level.AllowInfo()
+ case "warn":
+ l.o = level.AllowWarn()
+ case "error":
+ l.o = level.AllowError()
+ default:
+ return errors.Errorf("unrecognized log level %q", s)
+ }
+ l.s = s
+ return nil
+}
+
+// New returns a new leveled oklog logger in the logfmt format. Each logged line will be annotated
+// with a timestamp. The output always goes to stderr.
+func New(al AllowedLevel) log.Logger {
+ l := log.NewLogfmtLogger(log.NewSyncWriter(os.Stderr))
+ l = level.NewFilter(l, al.o)
+ l = log.With(l, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller)
+ return l
+}
diff --git a/vendor/github.com/prometheus/common/route/route.go b/vendor/github.com/prometheus/common/route/route.go
new file mode 100644
index 0000000..bb46881
--- /dev/null
+++ b/vendor/github.com/prometheus/common/route/route.go
@@ -0,0 +1,100 @@
+package route
+
+import (
+ "net/http"
+
+ "github.com/julienschmidt/httprouter"
+ "golang.org/x/net/context"
+)
+
+type param string
+
+// Param returns param p for the context.
+func Param(ctx context.Context, p string) string {
+ return ctx.Value(param(p)).(string)
+}
+
+// WithParam returns a new context with param p set to v.
+func WithParam(ctx context.Context, p, v string) context.Context {
+ return context.WithValue(ctx, param(p), v)
+}
+
+// Router wraps httprouter.Router and adds support for prefixed sub-routers
+// and per-request context injections.
+type Router struct {
+ rtr *httprouter.Router
+ prefix string
+}
+
+// New returns a new Router.
+func New() *Router {
+ return &Router{
+ rtr: httprouter.New(),
+ }
+}
+
+// WithPrefix returns a router that prefixes all registered routes with prefix.
+func (r *Router) WithPrefix(prefix string) *Router {
+ return &Router{rtr: r.rtr, prefix: r.prefix + prefix}
+}
+
+// handle turns a HandlerFunc into an httprouter.Handle.
+func (r *Router) handle(h http.HandlerFunc) httprouter.Handle {
+ return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
+ ctx, cancel := context.WithCancel(req.Context())
+ defer cancel()
+
+ for _, p := range params {
+ ctx = context.WithValue(ctx, param(p.Key), p.Value)
+ }
+ h(w, req.WithContext(ctx))
+ }
+}
+
+// Get registers a new GET route.
+func (r *Router) Get(path string, h http.HandlerFunc) {
+ r.rtr.GET(r.prefix+path, r.handle(h))
+}
+
+// Options registers a new OPTIONS route.
+func (r *Router) Options(path string, h http.HandlerFunc) {
+ r.rtr.OPTIONS(r.prefix+path, r.handle(h))
+}
+
+// Del registers a new DELETE route.
+func (r *Router) Del(path string, h http.HandlerFunc) {
+ r.rtr.DELETE(r.prefix+path, r.handle(h))
+}
+
+// Put registers a new PUT route.
+func (r *Router) Put(path string, h http.HandlerFunc) {
+ r.rtr.PUT(r.prefix+path, r.handle(h))
+}
+
+// Post registers a new POST route.
+func (r *Router) Post(path string, h http.HandlerFunc) {
+ r.rtr.POST(r.prefix+path, r.handle(h))
+}
+
+// Redirect takes an absolute path and sends an internal HTTP redirect for it,
+// prefixed by the router's path prefix. Note that this method does not include
+// functionality for handling relative paths or full URL redirects.
+func (r *Router) Redirect(w http.ResponseWriter, req *http.Request, path string, code int) {
+ http.Redirect(w, req, r.prefix+path, code)
+}
+
+// ServeHTTP implements http.Handler.
+func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
+ r.rtr.ServeHTTP(w, req)
+}
+
+// FileServe returns a new http.HandlerFunc that serves files from dir.
+// Using routes must provide the *filepath parameter.
+func FileServe(dir string) http.HandlerFunc {
+ fs := http.FileServer(http.Dir(dir))
+
+ return func(w http.ResponseWriter, r *http.Request) {
+ r.URL.Path = Param(r.Context(), "filepath")
+ fs.ServeHTTP(w, r)
+ }
+}
diff --git a/vendor/github.com/prometheus/common/route/route_test.go b/vendor/github.com/prometheus/common/route/route_test.go
new file mode 100644
index 0000000..a9bb209
--- /dev/null
+++ b/vendor/github.com/prometheus/common/route/route_test.go
@@ -0,0 +1,44 @@
+package route
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestRedirect(t *testing.T) {
+ router := New().WithPrefix("/test/prefix")
+ w := httptest.NewRecorder()
+ r, err := http.NewRequest("GET", "http://localhost:9090/foo", nil)
+ if err != nil {
+ t.Fatalf("Error building test request: %s", err)
+ }
+
+ router.Redirect(w, r, "/some/endpoint", http.StatusFound)
+ if w.Code != http.StatusFound {
+ t.Fatalf("Unexpected redirect status code: got %d, want %d", w.Code, http.StatusFound)
+ }
+
+ want := "/test/prefix/some/endpoint"
+ got := w.Header()["Location"][0]
+ if want != got {
+ t.Fatalf("Unexpected redirect location: got %s, want %s", got, want)
+ }
+}
+
+func TestContext(t *testing.T) {
+ router := New()
+ router.Get("/test/:foo/", func(w http.ResponseWriter, r *http.Request) {
+ want := "bar"
+ got := Param(r.Context(), "foo")
+ if want != got {
+ t.Fatalf("Unexpected context value: want %q, got %q", want, got)
+ }
+ })
+
+ r, err := http.NewRequest("GET", "http://localhost:9090/test/bar/", nil)
+ if err != nil {
+ t.Fatalf("Error building test request: %s", err)
+ }
+ router.ServeHTTP(nil, r)
+}
diff --git a/vendor/github.com/prometheus/common/version/info.go b/vendor/github.com/prometheus/common/version/info.go
new file mode 100644
index 0000000..84489a5
--- /dev/null
+++ b/vendor/github.com/prometheus/common/version/info.go
@@ -0,0 +1,89 @@
+// Copyright 2016 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package version
+
+import (
+ "bytes"
+ "fmt"
+ "runtime"
+ "strings"
+ "text/template"
+
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+// Build information. Populated at build-time.
+var (
+ Version string
+ Revision string
+ Branch string
+ BuildUser string
+ BuildDate string
+ GoVersion = runtime.Version()
+)
+
+// NewCollector returns a collector which exports metrics about current version information.
+func NewCollector(program string) *prometheus.GaugeVec {
+ buildInfo := prometheus.NewGaugeVec(
+ prometheus.GaugeOpts{
+ Namespace: program,
+ Name: "build_info",
+ Help: fmt.Sprintf(
+ "A metric with a constant '1' value labeled by version, revision, branch, and goversion from which %s was built.",
+ program,
+ ),
+ },
+ []string{"version", "revision", "branch", "goversion"},
+ )
+ buildInfo.WithLabelValues(Version, Revision, Branch, GoVersion).Set(1)
+ return buildInfo
+}
+
+// versionInfoTmpl contains the template used by Info.
+var versionInfoTmpl = `
+{{.program}}, version {{.version}} (branch: {{.branch}}, revision: {{.revision}})
+ build user: {{.buildUser}}
+ build date: {{.buildDate}}
+ go version: {{.goVersion}}
+`
+
+// Print returns version information.
+func Print(program string) string {
+ m := map[string]string{
+ "program": program,
+ "version": Version,
+ "revision": Revision,
+ "branch": Branch,
+ "buildUser": BuildUser,
+ "buildDate": BuildDate,
+ "goVersion": GoVersion,
+ }
+ t := template.Must(template.New("version").Parse(versionInfoTmpl))
+
+ var buf bytes.Buffer
+ if err := t.ExecuteTemplate(&buf, "version", m); err != nil {
+ panic(err)
+ }
+ return strings.TrimSpace(buf.String())
+}
+
+// Info returns version, branch and revision information.
+func Info() string {
+ return fmt.Sprintf("(version=%s, branch=%s, revision=%s)", Version, Branch, Revision)
+}
+
+// BuildContext returns goVersion, buildUser and buildDate information.
+func BuildContext() string {
+ return fmt.Sprintf("(go=%s, user=%s, date=%s)", GoVersion, BuildUser, BuildDate)
+}
diff --git a/vendor/github.com/prometheus/procfs/.travis.yml b/vendor/github.com/prometheus/procfs/.travis.yml
index b1e6743..ee09bb7 100644
--- a/vendor/github.com/prometheus/procfs/.travis.yml
+++ b/vendor/github.com/prometheus/procfs/.travis.yml
@@ -1,5 +1,5 @@
+sudo: false
language: go
go:
- - 1.3
- - 1.4
- - tip
+ - 1.7.6
+ - 1.8.3
diff --git a/vendor/github.com/prometheus/procfs/AUTHORS.md b/vendor/github.com/prometheus/procfs/AUTHORS.md
deleted file mode 100644
index 8dde8e3..0000000
--- a/vendor/github.com/prometheus/procfs/AUTHORS.md
+++ /dev/null
@@ -1,12 +0,0 @@
-The Prometheus project was started by Matt T. Proud (emeritus) and
-Julius Volz in 2012.
-
-Maintainers of this repository:
-
-* Tobias Schmidt
-
-The following individuals have contributed code to this repository
-(listed in alphabetical order):
-
-* Ji-Hoon, Seol
-* Tobias Schmidt
diff --git a/vendor/github.com/prometheus/procfs/CONTRIBUTING.md b/vendor/github.com/prometheus/procfs/CONTRIBUTING.md
index 5705f0f..40503ed 100644
--- a/vendor/github.com/prometheus/procfs/CONTRIBUTING.md
+++ b/vendor/github.com/prometheus/procfs/CONTRIBUTING.md
@@ -2,9 +2,9 @@
Prometheus uses GitHub to manage reviews of pull requests.
-* If you have a trivial fix or improvement, go ahead and create a pull
- request, addressing (with `@...`) one or more of the maintainers
- (see [AUTHORS.md](AUTHORS.md)) in the description of the pull request.
+* If you have a trivial fix or improvement, go ahead and create a pull request,
+ addressing (with `@...`) the maintainer of this repository (see
+ [MAINTAINERS.md](MAINTAINERS.md)) in the description of the pull request.
* If you plan to do something more involved, first discuss your ideas
on our [mailing list](https://groups.google.com/forum/?fromgroups#!forum/prometheus-developers).
diff --git a/vendor/github.com/prometheus/procfs/MAINTAINERS.md b/vendor/github.com/prometheus/procfs/MAINTAINERS.md
new file mode 100644
index 0000000..35993c4
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/MAINTAINERS.md
@@ -0,0 +1 @@
+* Tobias Schmidt
diff --git a/vendor/github.com/prometheus/procfs/Makefile b/vendor/github.com/prometheus/procfs/Makefile
new file mode 100644
index 0000000..dd48afd
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/Makefile
@@ -0,0 +1,18 @@
+ci: fmt lint test
+
+fmt:
+ ! gofmt -l *.go | read nothing
+ go vet
+
+lint:
+ go get github.com/golang/lint/golint
+ golint *.go
+
+test: sysfs/fixtures/.unpacked
+ go test -v ./...
+
+sysfs/fixtures/.unpacked: sysfs/fixtures.ttar
+ ./ttar -C sysfs -x -f sysfs/fixtures.ttar
+ touch $@
+
+.PHONY: fmt lint test ci
diff --git a/vendor/github.com/prometheus/procfs/README.md b/vendor/github.com/prometheus/procfs/README.md
index 6e7ee6b..2095494 100644
--- a/vendor/github.com/prometheus/procfs/README.md
+++ b/vendor/github.com/prometheus/procfs/README.md
@@ -8,3 +8,4 @@ backwards-incompatible ways without warnings. Use it at your own risk.
[![GoDoc](https://godoc.org/github.com/prometheus/procfs?status.png)](https://godoc.org/github.com/prometheus/procfs)
[![Build Status](https://travis-ci.org/prometheus/procfs.svg?branch=master)](https://travis-ci.org/prometheus/procfs)
+[![Go Report Card](https://goreportcard.com/badge/github.com/prometheus/procfs)](https://goreportcard.com/report/github.com/prometheus/procfs)
diff --git a/vendor/github.com/prometheus/procfs/bcache/bcache.go b/vendor/github.com/prometheus/procfs/bcache/bcache.go
new file mode 100644
index 0000000..1db178c
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/bcache/bcache.go
@@ -0,0 +1,84 @@
+// Copyright 2017 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package bcache provides access to statistics exposed by the bcache (Linux
+// block cache).
+package bcache
+
+// Stats contains bcache runtime statistics, parsed from /sys/fs/bcache/.
+//
+// The names and meanings of each statistic were taken from bcache.txt and
+// files in drivers/md/bcache in the Linux kernel source. Counters are uint64
+// (in-kernel counters are mostly unsigned long).
+type Stats struct {
+ // The name of the bcache used to source these statistics.
+ Name string
+ Bcache BcacheStats
+ Bdevs []BdevStats
+ Caches []CacheStats
+}
+
+// BcacheStats contains statistics tied to a bcache ID.
+type BcacheStats struct {
+ AverageKeySize uint64
+ BtreeCacheSize uint64
+ CacheAvailablePercent uint64
+ Congested uint64
+ RootUsagePercent uint64
+ TreeDepth uint64
+ Internal InternalStats
+ FiveMin PeriodStats
+ Total PeriodStats
+}
+
+// BdevStats contains statistics for one backing device.
+type BdevStats struct {
+ Name string
+ DirtyData uint64
+ FiveMin PeriodStats
+ Total PeriodStats
+}
+
+// CacheStats contains statistics for one cache device.
+type CacheStats struct {
+ Name string
+ IOErrors uint64
+ MetadataWritten uint64
+ Written uint64
+ Priority PriorityStats
+}
+
+// PriorityStats contains statistics from the priority_stats file.
+type PriorityStats struct {
+ UnusedPercent uint64
+ MetadataPercent uint64
+}
+
+// InternalStats contains internal bcache statistics.
+type InternalStats struct {
+ ActiveJournalEntries uint64
+ BtreeNodes uint64
+ BtreeReadAverageDurationNanoSeconds uint64
+ CacheReadRaces uint64
+}
+
+// PeriodStats contains statistics for a time period (5 min or total).
+type PeriodStats struct {
+ Bypassed uint64
+ CacheBypassHits uint64
+ CacheBypassMisses uint64
+ CacheHits uint64
+ CacheMissCollisions uint64
+ CacheMisses uint64
+ CacheReadaheads uint64
+}
diff --git a/vendor/github.com/prometheus/procfs/bcache/get.go b/vendor/github.com/prometheus/procfs/bcache/get.go
new file mode 100644
index 0000000..4d56f3d
--- /dev/null
+++ b/vendor/github.com/prometheus/procfs/bcache/get.go
@@ -0,0 +1,330 @@
+// Copyright 2017 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package bcache
+
+import (
+ "bufio"
+ "fmt"
+ "io/ioutil"
+ "os"
+ "path"
+ "path/filepath"
+ "strconv"
+ "strings"
+)
+
+// ParsePseudoFloat parses the peculiar format produced by bcache's bch_hprint.
+func parsePseudoFloat(str string) (float64, error) {
+ ss := strings.Split(str, ".")
+
+ intPart, err := strconv.ParseFloat(ss[0], 64)
+ if err != nil {
+ return 0, err
+ }
+
+ if len(ss) == 1 {
+ // Pure integers are fine.
+ return intPart, nil
+ }
+ fracPart, err := strconv.ParseFloat(ss[1], 64)
+ if err != nil {
+ return 0, err
+ }
+ // fracPart is a number between 0 and 1023 divided by 100; it is off
+ // by a small amount. Unexpected bumps in time lines may occur because
+ // for bch_hprint .1 != .10 and .10 > .9 (at least up to Linux
+ // v4.12-rc3).
+
+ // Restore the proper order:
+ fracPart = fracPart / 10.24
+ return intPart + fracPart, nil
+}
+
+// Dehumanize converts a human-readable byte slice into a uint64.
+func dehumanize(hbytes []byte) (uint64, error) {
+ ll := len(hbytes)
+ if ll == 0 {
+ return 0, fmt.Errorf("zero-length reply")
+ }
+ lastByte := hbytes[ll-1]
+ mul := float64(1)
+ var (
+ mant float64
+ err error
+ )
+ // If lastByte is beyond the range of ASCII digits, it must be a
+ // multiplier.
+ if lastByte > 57 {
+ // Remove multiplier from slice.
+ hbytes = hbytes[:len(hbytes)-1]
+
+ const (
+ _ = 1 << (10 * iota)
+ KiB
+ MiB
+ GiB
+ TiB
+ PiB
+ EiB
+ ZiB
+ YiB
+ )
+
+ multipliers := map[rune]float64{
+ // Source for conversion rules:
+ // linux-kernel/drivers/md/bcache/util.c:bch_hprint()
+ 'k': KiB,
+ 'M': MiB,
+ 'G': GiB,
+ 'T': TiB,
+ 'P': PiB,
+ 'E': EiB,
+ 'Z': ZiB,
+ 'Y': YiB,
+ }
+ mul = float64(multipliers[rune(lastByte)])
+ mant, err = parsePseudoFloat(string(hbytes))
+ if err != nil {
+ return 0, err
+ }
+ } else {
+ // Not humanized by bch_hprint
+ mant, err = strconv.ParseFloat(string(hbytes), 64)
+ if err != nil {
+ return 0, err
+ }
+ }
+ res := uint64(mant * mul)
+ return res, nil
+}
+
+type parser struct {
+ uuidPath string
+ subDir string
+ currentDir string
+ err error
+}
+
+func (p *parser) setSubDir(pathElements ...string) {
+ p.subDir = path.Join(pathElements...)
+ p.currentDir = path.Join(p.uuidPath, p.subDir)
+}
+
+func (p *parser) readValue(fileName string) uint64 {
+ if p.err != nil {
+ return 0
+ }
+ path := path.Join(p.currentDir, fileName)
+ byt, err := ioutil.ReadFile(path)
+ if err != nil {
+ p.err = fmt.Errorf("failed to read: %s", path)
+ return 0
+ }
+ // Remove trailing newline.
+ byt = byt[:len(byt)-1]
+ res, err := dehumanize(byt)
+ p.err = err
+ return res
+}
+
+// ParsePriorityStats parses lines from the priority_stats file.
+func parsePriorityStats(line string, ps *PriorityStats) (error) {
+ var (
+ value uint64
+ err error
+ )
+ switch {
+ case strings.HasPrefix(line, "Unused:"):
+ fields := strings.Fields(line)
+ rawValue := fields[len(fields)-1]
+ valueStr := strings.TrimSuffix(rawValue, "%")
+ value, err = strconv.ParseUint(valueStr, 10, 64)
+ if err != nil {
+ return err
+ }
+ ps.UnusedPercent = value
+ case strings.HasPrefix(line, "Metadata:"):
+ fields := strings.Fields(line)
+ rawValue := fields[len(fields)-1]
+ valueStr := strings.TrimSuffix(rawValue, "%")
+ value, err = strconv.ParseUint(valueStr, 10, 64)
+ if err != nil {
+ return err
+ }
+ ps.MetadataPercent = value
+ }
+ return nil
+}
+
+func (p *parser) getPriorityStats() PriorityStats {
+ var res PriorityStats
+
+ if p.err != nil {
+ return res
+ }
+
+ path := path.Join(p.currentDir, "priority_stats")
+
+ file, err := os.Open(path)
+ if err != nil {
+ p.err = fmt.Errorf("failed to read: %s", path)
+ return res
+ }
+ defer file.Close()
+
+ scanner := bufio.NewScanner(file)
+ for scanner.Scan() {
+ err = parsePriorityStats(scanner.Text(), &res)
+ if err != nil {
+ p.err = fmt.Errorf("failed to parse: %s (%s)", path, err)
+ return res
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ p.err = fmt.Errorf("failed to parse: %s (%s)", path, err)
+ return res
+ }
+ return res
+}
+
+// GetStats collects from sysfs files data tied to one bcache ID.
+func GetStats(uuidPath string) (*Stats, error) {
+ var bs Stats
+
+ par := parser{uuidPath: uuidPath}
+
+ // bcache stats
+
+ // dir
+ par.setSubDir("")
+ bs.Bcache.AverageKeySize = par.readValue("average_key_size")
+ bs.Bcache.BtreeCacheSize = par.readValue("btree_cache_size")
+ bs.Bcache.CacheAvailablePercent = par.readValue("cache_available_percent")
+ bs.Bcache.Congested = par.readValue("congested")
+ bs.Bcache.RootUsagePercent = par.readValue("root_usage_percent")
+ bs.Bcache.TreeDepth = par.readValue("tree_depth")
+
+ // bcache stats (internal)
+
+ // dir /internal
+ par.setSubDir("internal")
+ bs.Bcache.Internal.ActiveJournalEntries = par.readValue("active_journal_entries")
+ bs.Bcache.Internal.BtreeNodes = par.readValue("btree_nodes")
+ bs.Bcache.Internal.BtreeReadAverageDurationNanoSeconds = par.readValue("btree_read_average_duration_us")
+ bs.Bcache.Internal.CacheReadRaces = par.readValue("cache_read_races")
+
+ // bcache stats (period)
+
+ // dir /stats_five_minute
+ par.setSubDir("stats_five_minute")
+ bs.Bcache.FiveMin.Bypassed = par.readValue("bypassed")
+ bs.Bcache.FiveMin.CacheHits = par.readValue("cache_hits")
+
+ bs.Bcache.FiveMin.Bypassed = par.readValue("bypassed")
+ bs.Bcache.FiveMin.CacheBypassHits = par.readValue("cache_bypass_hits")
+ bs.Bcache.FiveMin.CacheBypassMisses = par.readValue("cache_bypass_misses")
+ bs.Bcache.FiveMin.CacheHits = par.readValue("cache_hits")
+ bs.Bcache.FiveMin.CacheMissCollisions = par.readValue("cache_miss_collisions")
+ bs.Bcache.FiveMin.CacheMisses = par.readValue("cache_misses")
+ bs.Bcache.FiveMin.CacheReadaheads = par.readValue("cache_readaheads")
+
+ // dir /stats_total
+ par.setSubDir("stats_total")
+ bs.Bcache.Total.Bypassed = par.readValue("bypassed")
+ bs.Bcache.Total.CacheHits = par.readValue("cache_hits")
+
+ bs.Bcache.Total.Bypassed = par.readValue("bypassed")
+ bs.Bcache.Total.CacheBypassHits = par.readValue("cache_bypass_hits")
+ bs.Bcache.Total.CacheBypassMisses = par.readValue("cache_bypass_misses")
+ bs.Bcache.Total.CacheHits = par.readValue("cache_hits")
+ bs.Bcache.Total.CacheMissCollisions = par.readValue("cache_miss_collisions")
+ bs.Bcache.Total.CacheMisses = par.readValue("cache_misses")
+ bs.Bcache.Total.CacheReadaheads = par.readValue("cache_readaheads")
+
+ if par.err != nil {
+ return nil, par.err
+ }
+
+ // bdev stats
+
+ reg := path.Join(uuidPath, "bdev[0-9]*")
+ bdevDirs, err := filepath.Glob(reg)
+ if err != nil {
+ return nil, err
+ }
+
+ bs.Bdevs = make([]BdevStats, len(bdevDirs))
+
+ for ii, bdevDir := range bdevDirs {
+ var bds = &bs.Bdevs[ii]
+
+ bds.Name = filepath.Base(bdevDir)
+
+ par.setSubDir(bds.Name)
+ bds.DirtyData = par.readValue("dirty_data")
+
+ // dir //stats_five_minute
+ par.setSubDir(bds.Name, "stats_five_minute")
+ bds.FiveMin.Bypassed = par.readValue("bypassed")
+ bds.FiveMin.CacheBypassHits = par.readValue("cache_bypass_hits")
+ bds.FiveMin.CacheBypassMisses = par.readValue("cache_bypass_misses")
+ bds.FiveMin.CacheHits = par.readValue("cache_hits")
+ bds.FiveMin.CacheMissCollisions = par.readValue("cache_miss_collisions")
+ bds.FiveMin.CacheMisses = par.readValue("cache_misses")
+ bds.FiveMin.CacheReadaheads = par.readValue("cache_readaheads")
+
+ // dir