From 132452f394c7a854ad311102805c11ebb4f0eba3 Mon Sep 17 00:00:00 2001 From: Omar Elazhary Date: Wed, 6 Apr 2016 15:18:11 +0000 Subject: [PATCH] Revert "CFA-2114 Added Godeps and relevant dependencies." This reverts commit ee4057565e0e7992aeb72a8b2dfa5f8d8d381be2. --- Godeps | 9 + Godeps/Godeps.json | 136 - Godeps/Readme | 5 - Godeps/_workspace/.gitignore | 2 - .../src/github.com/18F/hmacauth/.about.yml | 97 - .../src/github.com/18F/hmacauth/.gitignore | 4 - .../src/github.com/18F/hmacauth/.travis.yml | 14 - .../src/github.com/18F/hmacauth/README.md | 35 - .../src/github.com/18F/hmacauth/hmacauth.go | 238 - .../src/github.com/BurntSushi/toml/.gitignore | 5 - .../github.com/BurntSushi/toml/.travis.yml | 12 - .../src/github.com/BurntSushi/toml/COMPATIBLE | 3 - .../src/github.com/BurntSushi/toml/COPYING | 14 - .../src/github.com/BurntSushi/toml/Makefile | 19 - .../src/github.com/BurntSushi/toml/README.md | 220 - .../src/github.com/BurntSushi/toml/decode.go | 492 - .../github.com/BurntSushi/toml/decode_meta.go | 122 - .../src/github.com/BurntSushi/toml/doc.go | 27 - .../src/github.com/BurntSushi/toml/encode.go | 551 - .../BurntSushi/toml/encoding_types.go | 19 - .../BurntSushi/toml/encoding_types_1.1.go | 18 - .../src/github.com/BurntSushi/toml/lex.go | 872 - .../src/github.com/BurntSushi/toml/parse.go | 498 - .../github.com/BurntSushi/toml/session.vim | 1 - .../github.com/BurntSushi/toml/type_check.go | 91 - .../github.com/BurntSushi/toml/type_fields.go | 241 - .../bitly/go-simplejson/.travis.yml | 10 - .../github.com/bitly/go-simplejson/LICENSE | 17 - .../github.com/bitly/go-simplejson/README.md | 13 - .../bitly/go-simplejson/simplejson.go | 446 - .../bitly/go-simplejson/simplejson_go10.go | 75 - .../bitly/go-simplejson/simplejson_go11.go | 89 - .../github.com/bmizerany/assert/.gitignore | 7 - .../src/github.com/bmizerany/assert/README.md | 45 - .../src/github.com/bmizerany/assert/assert.go | 76 - .../src/github.com/golang/protobuf/LICENSE | 31 - .../github.com/golang/protobuf/proto/Makefile | 43 - .../github.com/golang/protobuf/proto/clone.go | 223 - .../golang/protobuf/proto/decode.go | 868 - .../golang/protobuf/proto/encode.go | 1331 -- .../github.com/golang/protobuf/proto/equal.go | 276 - .../golang/protobuf/proto/extensions.go | 399 - .../github.com/golang/protobuf/proto/lib.go | 894 - .../golang/protobuf/proto/message_set.go | 280 - .../golang/protobuf/proto/pointer_reflect.go | 479 - .../golang/protobuf/proto/pointer_unsafe.go | 266 - .../golang/protobuf/proto/properties.go | 846 - .../github.com/golang/protobuf/proto/text.go | 849 - .../golang/protobuf/proto/text_parser.go | 871 - .../src/github.com/kr/pretty/.gitignore | 4 - .../src/github.com/kr/pretty/License | 21 - .../src/github.com/kr/pretty/Readme | 9 - .../src/github.com/kr/pretty/diff.go | 158 - .../src/github.com/kr/pretty/formatter.go | 337 - .../src/github.com/kr/pretty/pretty.go | 98 - .../src/github.com/kr/pretty/zero.go | 41 - .../_workspace/src/github.com/kr/text/License | 19 - .../_workspace/src/github.com/kr/text/Readme | 3 - .../_workspace/src/github.com/kr/text/doc.go | 3 - .../src/github.com/kr/text/indent.go | 74 - .../_workspace/src/github.com/kr/text/wrap.go | 86 - .../mreiferson/go-options/.travis.yml | 7 - .../github.com/mreiferson/go-options/LICENSE | 17 - .../mreiferson/go-options/README.md | 5 - .../mreiferson/go-options/options.go | 264 - .../_workspace/src/golang.org/x/net/LICENSE | 27 - .../_workspace/src/golang.org/x/net/PATENTS | 22 - .../src/golang.org/x/net/context/context.go | 447 - .../x/net/context/ctxhttp/cancelreq.go | 19 - .../x/net/context/ctxhttp/cancelreq_go14.go | 23 - .../x/net/context/ctxhttp/ctxhttp.go | 140 - .../src/golang.org/x/oauth2/.travis.yml | 14 - .../src/golang.org/x/oauth2/AUTHORS | 3 - .../src/golang.org/x/oauth2/CONTRIBUTING.md | 31 - .../src/golang.org/x/oauth2/CONTRIBUTORS | 3 - .../src/golang.org/x/oauth2/LICENSE | 27 - .../src/golang.org/x/oauth2/README.md | 64 - .../golang.org/x/oauth2/client_appengine.go | 25 - .../golang.org/x/oauth2/google/appengine.go | 86 - .../x/oauth2/google/appengine_hook.go | 13 - .../x/oauth2/google/appenginevm_hook.go | 14 - .../src/golang.org/x/oauth2/google/default.go | 155 - .../src/golang.org/x/oauth2/google/google.go | 145 - .../src/golang.org/x/oauth2/google/jwt.go | 71 - .../src/golang.org/x/oauth2/google/sdk.go | 168 - .../golang.org/x/oauth2/internal/oauth2.go | 76 - .../src/golang.org/x/oauth2/internal/token.go | 221 - .../golang.org/x/oauth2/internal/transport.go | 69 - .../src/golang.org/x/oauth2/jws/jws.go | 172 - .../src/golang.org/x/oauth2/jwt/jwt.go | 153 - .../src/golang.org/x/oauth2/oauth2.go | 337 - .../src/golang.org/x/oauth2/token.go | 158 - .../src/golang.org/x/oauth2/transport.go | 132 - .../src/google.golang.org/api/LICENSE | 27 - .../api/admin/directory/v1/admin-api.json | 5585 ------ .../api/admin/directory/v1/admin-gen.go | 15449 ---------------- .../api/gensupport/backoff.go | 34 - .../api/gensupport/buffer.go | 77 - .../google.golang.org/api/gensupport/doc.go | 10 - .../google.golang.org/api/gensupport/json.go | 172 - .../google.golang.org/api/gensupport/media.go | 198 - .../api/gensupport/params.go | 50 - .../api/gensupport/resumable.go | 177 - .../api/googleapi/googleapi.go | 418 - .../googleapi/internal/uritemplates/LICENSE | 18 - .../internal/uritemplates/uritemplates.go | 359 - .../googleapi/internal/uritemplates/utils.go | 13 - .../google.golang.org/api/googleapi/types.go | 182 - .../google.golang.org/appengine/.travis.yml | 18 - .../src/google.golang.org/appengine/LICENSE | 202 - .../src/google.golang.org/appengine/README.md | 75 - .../google.golang.org/appengine/appengine.go | 76 - .../appengine/appengine_vm.go | 56 - .../src/google.golang.org/appengine/errors.go | 46 - .../google.golang.org/appengine/identity.go | 142 - .../appengine/internal/api.go | 640 - .../appengine/internal/api_classic.go | 133 - .../appengine/internal/api_common.go | 101 - .../appengine/internal/app_id.go | 28 - .../app_identity/app_identity_service.pb.go | 296 - .../app_identity/app_identity_service.proto | 64 - .../appengine/internal/base/api_base.pb.go | 133 - .../appengine/internal/base/api_base.proto | 33 - .../internal/datastore/datastore_v3.pb.go | 2778 --- .../internal/datastore/datastore_v3.proto | 541 - .../appengine/internal/identity.go | 14 - .../appengine/internal/identity_classic.go | 27 - .../appengine/internal/identity_vm.go | 97 - .../appengine/internal/internal.go | 144 - .../appengine/internal/log/log_service.pb.go | 899 - .../appengine/internal/log/log_service.proto | 150 - .../appengine/internal/metadata.go | 61 - .../internal/modules/modules_service.pb.go | 375 - .../internal/modules/modules_service.proto | 80 - .../appengine/internal/net.go | 56 - .../appengine/internal/regen.sh | 40 - .../internal/remote_api/remote_api.pb.go | 231 - .../internal/remote_api/remote_api.proto | 44 - .../appengine/internal/transaction.go | 107 - .../google.golang.org/appengine/namespace.go | 25 - .../google.golang.org/appengine/timeout.go | 20 - .../src/google.golang.org/cloud/LICENSE | 202 - .../cloud/compute/metadata/metadata.go | 332 - .../google.golang.org/cloud/internal/cloud.go | 128 - .../src/gopkg.in/fsnotify.v1/.gitignore | 6 - .../src/gopkg.in/fsnotify.v1/.travis.yml | 23 - .../src/gopkg.in/fsnotify.v1/AUTHORS | 40 - .../src/gopkg.in/fsnotify.v1/CHANGELOG.md | 283 - .../src/gopkg.in/fsnotify.v1/CONTRIBUTING.md | 77 - .../src/gopkg.in/fsnotify.v1/LICENSE | 28 - .../src/gopkg.in/fsnotify.v1/README.md | 64 - .../src/gopkg.in/fsnotify.v1/fsnotify.go | 62 - .../src/gopkg.in/fsnotify.v1/inotify.go | 324 - .../gopkg.in/fsnotify.v1/inotify_poller.go | 186 - .../src/gopkg.in/fsnotify.v1/kqueue.go | 502 - .../src/gopkg.in/fsnotify.v1/open_mode_bsd.go | 11 - .../gopkg.in/fsnotify.v1/open_mode_darwin.go | 12 - .../src/gopkg.in/fsnotify.v1/windows.go | 561 - 158 files changed, 9 insertions(+), 49473 deletions(-) create mode 100644 Godeps delete mode 100644 Godeps/Godeps.json delete mode 100644 Godeps/Readme delete mode 100644 Godeps/_workspace/.gitignore delete mode 100644 Godeps/_workspace/src/github.com/18F/hmacauth/.about.yml delete mode 100644 Godeps/_workspace/src/github.com/18F/hmacauth/.gitignore delete mode 100644 Godeps/_workspace/src/github.com/18F/hmacauth/.travis.yml delete mode 100644 Godeps/_workspace/src/github.com/18F/hmacauth/README.md delete mode 100644 Godeps/_workspace/src/github.com/18F/hmacauth/hmacauth.go delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/.gitignore delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/.travis.yml delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/COMPATIBLE delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/COPYING delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/Makefile delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/README.md delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/decode.go delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/decode_meta.go delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/doc.go delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/encode.go delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/encoding_types.go delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/encoding_types_1.1.go delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/lex.go delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/parse.go delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/session.vim delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/type_check.go delete mode 100644 Godeps/_workspace/src/github.com/BurntSushi/toml/type_fields.go delete mode 100644 Godeps/_workspace/src/github.com/bitly/go-simplejson/.travis.yml delete mode 100644 Godeps/_workspace/src/github.com/bitly/go-simplejson/LICENSE delete mode 100644 Godeps/_workspace/src/github.com/bitly/go-simplejson/README.md delete mode 100644 Godeps/_workspace/src/github.com/bitly/go-simplejson/simplejson.go delete mode 100644 Godeps/_workspace/src/github.com/bitly/go-simplejson/simplejson_go10.go delete mode 100644 Godeps/_workspace/src/github.com/bitly/go-simplejson/simplejson_go11.go delete mode 100644 Godeps/_workspace/src/github.com/bmizerany/assert/.gitignore delete mode 100644 Godeps/_workspace/src/github.com/bmizerany/assert/README.md delete mode 100644 Godeps/_workspace/src/github.com/bmizerany/assert/assert.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/LICENSE delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go delete mode 100644 Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go delete mode 100644 Godeps/_workspace/src/github.com/kr/pretty/.gitignore delete mode 100644 Godeps/_workspace/src/github.com/kr/pretty/License delete mode 100644 Godeps/_workspace/src/github.com/kr/pretty/Readme delete mode 100644 Godeps/_workspace/src/github.com/kr/pretty/diff.go delete mode 100644 Godeps/_workspace/src/github.com/kr/pretty/formatter.go delete mode 100644 Godeps/_workspace/src/github.com/kr/pretty/pretty.go delete mode 100644 Godeps/_workspace/src/github.com/kr/pretty/zero.go delete mode 100644 Godeps/_workspace/src/github.com/kr/text/License delete mode 100644 Godeps/_workspace/src/github.com/kr/text/Readme delete mode 100644 Godeps/_workspace/src/github.com/kr/text/doc.go delete mode 100644 Godeps/_workspace/src/github.com/kr/text/indent.go delete mode 100644 Godeps/_workspace/src/github.com/kr/text/wrap.go delete mode 100644 Godeps/_workspace/src/github.com/mreiferson/go-options/.travis.yml delete mode 100644 Godeps/_workspace/src/github.com/mreiferson/go-options/LICENSE delete mode 100644 Godeps/_workspace/src/github.com/mreiferson/go-options/README.md delete mode 100644 Godeps/_workspace/src/github.com/mreiferson/go-options/options.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/LICENSE delete mode 100644 Godeps/_workspace/src/golang.org/x/net/PATENTS delete mode 100644 Godeps/_workspace/src/golang.org/x/net/context/context.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq_go14.go delete mode 100644 Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/.travis.yml delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/AUTHORS delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/CONTRIBUTING.md delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/CONTRIBUTORS delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/LICENSE delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/README.md delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/client_appengine.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/google/appengine.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/google/appengine_hook.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/google/appenginevm_hook.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/google/default.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/google/google.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/google/jwt.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/google/sdk.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/internal/oauth2.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/internal/token.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/internal/transport.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/jws/jws.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/oauth2.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/token.go delete mode 100644 Godeps/_workspace/src/golang.org/x/oauth2/transport.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/LICENSE delete mode 100644 Godeps/_workspace/src/google.golang.org/api/admin/directory/v1/admin-api.json delete mode 100644 Godeps/_workspace/src/google.golang.org/api/admin/directory/v1/admin-gen.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/gensupport/backoff.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/gensupport/buffer.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/gensupport/doc.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/gensupport/json.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/gensupport/media.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/gensupport/params.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/gensupport/resumable.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/googleapi/googleapi.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/googleapi/internal/uritemplates/LICENSE delete mode 100644 Godeps/_workspace/src/google.golang.org/api/googleapi/internal/uritemplates/uritemplates.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/googleapi/internal/uritemplates/utils.go delete mode 100644 Godeps/_workspace/src/google.golang.org/api/googleapi/types.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/.travis.yml delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/LICENSE delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/README.md delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/appengine.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/appengine_vm.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/errors.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/identity.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/api.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/api_classic.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/api_common.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/app_id.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/app_identity/app_identity_service.pb.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/app_identity/app_identity_service.proto delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/base/api_base.pb.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/base/api_base.proto delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/datastore/datastore_v3.pb.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/datastore/datastore_v3.proto delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/identity.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/identity_classic.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/identity_vm.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/internal.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/log/log_service.pb.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/log/log_service.proto delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/metadata.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/modules/modules_service.pb.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/modules/modules_service.proto delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/net.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/regen.sh delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/remote_api/remote_api.pb.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/remote_api/remote_api.proto delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/internal/transaction.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/namespace.go delete mode 100644 Godeps/_workspace/src/google.golang.org/appengine/timeout.go delete mode 100644 Godeps/_workspace/src/google.golang.org/cloud/LICENSE delete mode 100644 Godeps/_workspace/src/google.golang.org/cloud/compute/metadata/metadata.go delete mode 100644 Godeps/_workspace/src/google.golang.org/cloud/internal/cloud.go delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/.gitignore delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/.travis.yml delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/AUTHORS delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/CHANGELOG.md delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/CONTRIBUTING.md delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/LICENSE delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/README.md delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/fsnotify.go delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/inotify.go delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/inotify_poller.go delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/kqueue.go delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/open_mode_bsd.go delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/open_mode_darwin.go delete mode 100644 Godeps/_workspace/src/gopkg.in/fsnotify.v1/windows.go diff --git a/Godeps b/Godeps new file mode 100644 index 000000000..b6bc08dd5 --- /dev/null +++ b/Godeps @@ -0,0 +1,9 @@ +github.com/18F/hmacauth 1.0.1 +github.com/BurntSushi/toml 3883ac1ce943878302255f538fce319d23226223 +github.com/bitly/go-simplejson 3378bdcb5cebedcbf8b5750edee28010f128fe24 +github.com/mreiferson/go-options ee94b57f2fbf116075426f853e5abbcdfeca8b3d +github.com/bmizerany/assert e17e99893cb6509f428e1728281c2ad60a6b31e3 +gopkg.in/fsnotify.v1 v1.2.0 +golang.org/x/oauth2 397fe7649477ff2e8ced8fc0b2696f781e53745a +golang.org/x/oauth2/google 397fe7649477ff2e8ced8fc0b2696f781e53745a +google.golang.org/api/admin/directory/v1 a5c3e2a4792aff40e59840d9ecdff0542a202a80 diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json deleted file mode 100644 index 1937ff679..000000000 --- a/Godeps/Godeps.json +++ /dev/null @@ -1,136 +0,0 @@ -{ - "ImportPath": "github.com/bitly/oauth2_proxy", - "GoVersion": "go1.5", - "GodepVersion": "v60", - "Packages": [ - "." - ], - "Deps": [ - { - "ImportPath": "github.com/18F/hmacauth", - "Comment": "1.0.1", - "Rev": "9232a6386b737d7d1e5c1c6e817aa48d5d8ee7cd" - }, - { - "ImportPath": "github.com/BurntSushi/toml", - "Comment": "v0.1.0-23-g5c4df71", - "Rev": "5c4df71dfe9ac89ef6287afc05e4c1b16ae65a1e" - }, - { - "ImportPath": "github.com/bitly/go-simplejson", - "Comment": "v0.5.0", - "Rev": "aabad6e819789e569bd6aabf444c935aa9ba1e44" - }, - { - "ImportPath": "github.com/bmizerany/assert", - "Comment": "release.r60-6-ge17e998", - "Rev": "e17e99893cb6509f428e1728281c2ad60a6b31e3" - }, - { - "ImportPath": "github.com/golang/protobuf/proto", - "Rev": "dda510ac0fd43b39770f22ac6260eb91d377bce3" - }, - { - "ImportPath": "github.com/kr/pretty", - "Comment": "go.weekly.2011-12-22-27-ge6ac2fc", - "Rev": "e6ac2fc51e89a3249e82157fa0bb7a18ef9dd5bb" - }, - { - "ImportPath": "github.com/kr/text", - "Rev": "bb797dc4fb8320488f47bf11de07a733d7233e1f" - }, - { - "ImportPath": "github.com/mreiferson/go-options", - "Rev": "7c174072188d0cfbe6f01bb457626abb22bdff52" - }, - { - "ImportPath": "golang.org/x/net/context", - "Rev": "7f88271ea9913b72aca44fa7fc8af919eacc17ce" - }, - { - "ImportPath": "golang.org/x/net/context/ctxhttp", - "Rev": "7f88271ea9913b72aca44fa7fc8af919eacc17ce" - }, - { - "ImportPath": "golang.org/x/oauth2", - "Rev": "8a57ed94ffd43444c0879fe75701732a38afc985" - }, - { - "ImportPath": "golang.org/x/oauth2/google", - "Rev": "8a57ed94ffd43444c0879fe75701732a38afc985" - }, - { - "ImportPath": "golang.org/x/oauth2/internal", - "Rev": "8a57ed94ffd43444c0879fe75701732a38afc985" - }, - { - "ImportPath": "golang.org/x/oauth2/jws", - "Rev": "8a57ed94ffd43444c0879fe75701732a38afc985" - }, - { - "ImportPath": "golang.org/x/oauth2/jwt", - "Rev": "8a57ed94ffd43444c0879fe75701732a38afc985" - }, - { - "ImportPath": "google.golang.org/api/admin/directory/v1", - "Rev": "ddff2aff599105a55549cf173852507dfa094b7f" - }, - { - "ImportPath": "google.golang.org/api/gensupport", - "Rev": "ddff2aff599105a55549cf173852507dfa094b7f" - }, - { - "ImportPath": "google.golang.org/api/googleapi", - "Rev": "ddff2aff599105a55549cf173852507dfa094b7f" - }, - { - "ImportPath": "google.golang.org/api/googleapi/internal/uritemplates", - "Rev": "ddff2aff599105a55549cf173852507dfa094b7f" - }, - { - "ImportPath": "google.golang.org/appengine", - "Rev": "b67c870a16a2d58b3afa024461dcc51805f52e9d" - }, - { - "ImportPath": "google.golang.org/appengine/internal", - "Rev": "b67c870a16a2d58b3afa024461dcc51805f52e9d" - }, - { - "ImportPath": "google.golang.org/appengine/internal/app_identity", - "Rev": "b67c870a16a2d58b3afa024461dcc51805f52e9d" - }, - { - "ImportPath": "google.golang.org/appengine/internal/base", - "Rev": "b67c870a16a2d58b3afa024461dcc51805f52e9d" - }, - { - "ImportPath": "google.golang.org/appengine/internal/datastore", - "Rev": "b67c870a16a2d58b3afa024461dcc51805f52e9d" - }, - { - "ImportPath": "google.golang.org/appengine/internal/log", - "Rev": "b67c870a16a2d58b3afa024461dcc51805f52e9d" - }, - { - "ImportPath": "google.golang.org/appengine/internal/modules", - "Rev": "b67c870a16a2d58b3afa024461dcc51805f52e9d" - }, - { - "ImportPath": "google.golang.org/appengine/internal/remote_api", - "Rev": "b67c870a16a2d58b3afa024461dcc51805f52e9d" - }, - { - "ImportPath": "google.golang.org/cloud/compute/metadata", - "Rev": "5a3b06f8b5da3b7c3a93da43163b872c86c509ef" - }, - { - "ImportPath": "google.golang.org/cloud/internal", - "Rev": "5a3b06f8b5da3b7c3a93da43163b872c86c509ef" - }, - { - "ImportPath": "gopkg.in/fsnotify.v1", - "Comment": "v1.2.9", - "Rev": "8611c35ab31c1c28aa903d33cf8b6e44a399b09e" - } - ] -} diff --git a/Godeps/Readme b/Godeps/Readme deleted file mode 100644 index 4cdaa53d5..000000000 --- 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/Godeps/_workspace/.gitignore b/Godeps/_workspace/.gitignore deleted file mode 100644 index f037d684e..000000000 --- a/Godeps/_workspace/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/pkg -/bin diff --git a/Godeps/_workspace/src/github.com/18F/hmacauth/.about.yml b/Godeps/_workspace/src/github.com/18F/hmacauth/.about.yml deleted file mode 100644 index 2a2fe4163..000000000 --- a/Godeps/_workspace/src/github.com/18F/hmacauth/.about.yml +++ /dev/null @@ -1,97 +0,0 @@ ---- -# .about.yml project metadata -# -# Short name that acts as the project identifier (required) -name: hmacauth - -# Full proper name of the project (required) -full_name: HMAC Authentication package for Go - -# The type of content in the repo -# values: app, docs, policy -type: app - -# Describes whether a project team, working group/guild, etc. owns the repo (required) -# values: guild, working-group, project -owner_type: project - -# Name of the main project repo if this is a sub-repo; name of the working group/guild repo if this is a working group/guild subproject -#parent: - -# Maturity stage of the project (required) -# values: discovery, alpha, beta, live -stage: discovery - -# Whether or not the project is actively maintained (required) -# values: active, deprecated -status: active - -# Description of the project -description: > - Signs and validates HTTP requests based on a shared-secret HMAC signature - -# Should be 'true' if the project has a continuous build (required) -# values: true, false -testable: true - -# Team members contributing to the project (required) -# Items: -# - github: GitHub user name -# id: Internal team identifier/user name -# role: Team member's role; leads should be designated as 'lead' -team: -- github: mbland - role: lead - -# Partners for whom the project is developed -#partners: -#- - -# Brief descriptions of significant project developments -#milestones: -#- - -# Technologies used to build the project -stack: -- Go - -# Brief description of the project's outcomes -#impact: - -# Services used to supply project status information -# Items: -# - name: Name of the service -# category: Type of the service -# url: URL for detailed information -# badge: URL for the status badge -#services: -#- - -# Licenses that apply to the project and/or its components (required) -# Items by property name pattern: -# .*: -# name: Name of the license from the Software Package Data Exchange (SPDX): https://spdx.org/licenses/ -# url: URL for the text of the license -licenses: - hmacauth: - name: CC0 - url: https://github.com/18F/hmacauth/blob/master/LICENSE.md - -# Blogs or websites associated with project development -#blog: -#- - -# Links to project artifacts -# Items: -# - url: URL for the link -# text: Anchor text for the link -#links: -#- url: -# text: - -# Email addresses of points-of-contact -contact: -- url: mailto:michael.bland@acm.org - text: Mike Bland -- url: https://github.com/18F/hmacauth/issues - text: 18F/hmacauth issues diff --git a/Godeps/_workspace/src/github.com/18F/hmacauth/.gitignore b/Godeps/_workspace/src/github.com/18F/hmacauth/.gitignore deleted file mode 100644 index 50697abd9..000000000 --- a/Godeps/_workspace/src/github.com/18F/hmacauth/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.DS_Store -*.log -.*.swp -coverage.out diff --git a/Godeps/_workspace/src/github.com/18F/hmacauth/.travis.yml b/Godeps/_workspace/src/github.com/18F/hmacauth/.travis.yml deleted file mode 100644 index cba557ef1..000000000 --- a/Godeps/_workspace/src/github.com/18F/hmacauth/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: go -go: -- 1.4.2 -script: -- go test ./... -- go get -u github.com/axw/gocov/gocov -- go get -u github.com/mattn/goveralls -- go get golang.org/x/tools/cmd/cover -- go test -v -covermode=count $pkg -coverprofile=profile.cov -- go tool cover -func profile.cov -- goveralls -coverprofile=profile.cov -service=travis-ci -branches: - only: - - master diff --git a/Godeps/_workspace/src/github.com/18F/hmacauth/README.md b/Godeps/_workspace/src/github.com/18F/hmacauth/README.md deleted file mode 100644 index 5afe3af09..000000000 --- a/Godeps/_workspace/src/github.com/18F/hmacauth/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# hmacauth HMAC authentication package for Go - -[![Build Status](https://travis-ci.org/18F/hmacauth.svg?branch=master)](https://travis-ci.org/18F/hmacauth) - -[![Coverage Status](https://coveralls.io/repos/18F/hmacauth/badge.svg?branch=master&service=github)](https://coveralls.io/github/18F/hmacauth?branch=master) - -Signs and authenticates HTTP requests based on a shared-secret HMAC signature. - -Developed in parallel with the following packages for other languages: -- Node.js: [hmac-authentication](https://www.npmjs.com/package/hmac-authentication) -- Ruby: [hmac_authentication](https://rubygems.org/gems/hmac_authentication) - -## Installation - -```go -import "github.com/18F/hmacauth" -``` - -## Validating incoming requests - -Coming soon... - -## Signing outgoing requests - -Coming soon... - -## Public domain - -This project is in the worldwide [public domain](LICENSE.md). As stated in [CONTRIBUTING](CONTRIBUTING.md): - -> This project is in the public domain within the United States, and copyright and related rights in the work worldwide are waived through the [CC0 1.0 Universal public domain dedication](https://creativecommons.org/publicdomain/zero/1.0/). -> -> All contributions to this project will be released under the CC0 ->dedication. By submitting a pull request, you are agreeing to comply ->with this waiver of copyright interest. diff --git a/Godeps/_workspace/src/github.com/18F/hmacauth/hmacauth.go b/Godeps/_workspace/src/github.com/18F/hmacauth/hmacauth.go deleted file mode 100644 index 3357bb469..000000000 --- a/Godeps/_workspace/src/github.com/18F/hmacauth/hmacauth.go +++ /dev/null @@ -1,238 +0,0 @@ -package hmacauth - -import ( - "bytes" - "crypto" - "crypto/hmac" - "encoding/base64" - "errors" - "io/ioutil" - "net/http" - "strconv" - "strings" -) - -// HmacAuth signs outbound requests and authenticates inbound requests. -type HmacAuth interface { - // Produces the string that will be prefixed to the request body and - // used to generate the signature. - StringToSign(req *http.Request) string - - // Adds a signature header to the request. - SignRequest(req *http.Request) - - // Generates a signature for the request. - RequestSignature(req *http.Request) string - - // Retrieves the signature included in the request header. - SignatureFromHeader(req *http.Request) string - - // Authenticates the request, returning the result code, the signature - // from the header, and the locally-computed signature. - AuthenticateRequest(request *http.Request) ( - result AuthenticationResult, - headerSignature, computedSignature string) -} - -var supportedAlgorithms = map[string]crypto.Hash{ - "md4": crypto.MD4, - "md5": crypto.MD5, - "sha1": crypto.SHA1, - "sha224": crypto.SHA224, - "sha256": crypto.SHA256, - "sha384": crypto.SHA384, - "sha512": crypto.SHA512, - "ripemd160": crypto.RIPEMD160, -} - -var algorithmName map[crypto.Hash]string - -func init() { - algorithmName = make(map[crypto.Hash]string) - for name, algorithm := range supportedAlgorithms { - algorithmName[algorithm] = name - // Make sure the algorithm is linked into the binary, per - // https://golang.org/pkg/crypto/#Hash.Available - // - // Note that both sides of the client/server connection must - // have an algorithm available in order to successfully - // authenticate using that algorithm - if algorithm.Available() == false { - delete(supportedAlgorithms, name) - } - } -} - -// DigestNameToCryptoHash returns the crypto.Hash value corresponding to the -// algorithm name, or an error if the algorithm is not supported. -func DigestNameToCryptoHash(name string) (result crypto.Hash, err error) { - var supported bool - if result, supported = supportedAlgorithms[name]; !supported { - err = errors.New("hmacauth: hash algorithm not supported: " + - name) - } - return -} - -// CryptoHashToDigestName returns the algorithm name corresponding to the -// crypto.Hash ID, or an error if the algorithm is not supported. -func CryptoHashToDigestName(id crypto.Hash) (result string, err error) { - var supported bool - if result, supported = algorithmName[id]; !supported { - err = errors.New("hmacauth: unsupported crypto.Hash #" + - strconv.Itoa(int(id))) - } - return -} - -type hmacAuth struct { - hash crypto.Hash - key []byte - header string - headers []string -} - -// NewHmacAuth returns an HmacAuth object that can be used to sign or -// authenticate HTTP requests based on the supplied parameters. -func NewHmacAuth(hash crypto.Hash, key []byte, header string, - headers []string) HmacAuth { - if hash.Available() == false { - var name string - var supported bool - if name, supported = algorithmName[hash]; !supported { - name = "#" + strconv.Itoa(int(hash)) - } - panic("hmacauth: hash algorithm " + name + " is unavailable") - } - canonicalHeaders := make([]string, len(headers)) - for i, h := range headers { - canonicalHeaders[i] = http.CanonicalHeaderKey(h) - } - return &hmacAuth{hash, key, header, canonicalHeaders} -} - -func (auth *hmacAuth) StringToSign(req *http.Request) string { - var buffer bytes.Buffer - _, _ = buffer.WriteString(req.Method) - _, _ = buffer.WriteString("\n") - - for _, header := range auth.headers { - values := req.Header[header] - lastIndex := len(values) - 1 - for i, value := range values { - _, _ = buffer.WriteString(value) - if i != lastIndex { - _, _ = buffer.WriteString(",") - } - } - _, _ = buffer.WriteString("\n") - } - _, _ = buffer.WriteString(req.URL.Path) - if req.URL.RawQuery != "" { - _, _ = buffer.WriteString("?") - _, _ = buffer.WriteString(req.URL.RawQuery) - } - if req.URL.Fragment != "" { - _, _ = buffer.WriteString("#") - _, _ = buffer.WriteString(req.URL.Fragment) - } - _, _ = buffer.WriteString("\n") - return buffer.String() -} - -func (auth *hmacAuth) SignRequest(req *http.Request) { - req.Header.Set(auth.header, auth.RequestSignature(req)) -} - -func (auth *hmacAuth) RequestSignature(req *http.Request) string { - return requestSignature(auth, req, auth.hash) -} - -func requestSignature(auth *hmacAuth, req *http.Request, - hashAlgorithm crypto.Hash) string { - h := hmac.New(hashAlgorithm.New, auth.key) - _, _ = h.Write([]byte(auth.StringToSign(req))) - - if req.Body != nil { - reqBody, _ := ioutil.ReadAll(req.Body) - req.Body = ioutil.NopCloser(bytes.NewBuffer(reqBody)) - _, _ = h.Write(reqBody) - } - - var sig []byte - sig = h.Sum(sig) - return algorithmName[hashAlgorithm] + " " + - base64.StdEncoding.EncodeToString(sig) -} - -func (auth *hmacAuth) SignatureFromHeader(req *http.Request) string { - return req.Header.Get(auth.header) -} - -// AuthenticationResult is a code used to identify the outcome of -// HmacAuth.AuthenticateRequest(). -type AuthenticationResult int - -const ( - // ResultNoSignature - the incoming result did not have a signature - // header. - ResultNoSignature AuthenticationResult = iota - - // ResultInvalidFormat - the signature header was not parseable. - ResultInvalidFormat - - // ResultUnsupportedAlgorithm - the signature header specified an - // unsupported algorithm. - ResultUnsupportedAlgorithm - - // ResultMatch - the signature from the request header matched the - // locally-computed signature. - ResultMatch - - // ResultMismatch - the signature from the request header did not match - // the locally-computed signature. - ResultMismatch -) - -var validationResultStrings = []string{ - "", - "ResultNoSignature", - "ResultInvalidFormat", - "ResultUnsupportedAlgorithm", - "ResultMatch", - "ResultMismatch", -} - -func (result AuthenticationResult) String() string { - return validationResultStrings[result] -} - -func (auth *hmacAuth) AuthenticateRequest(request *http.Request) ( - result AuthenticationResult, headerSignature, - computedSignature string) { - headerSignature = auth.SignatureFromHeader(request) - if headerSignature == "" { - result = ResultNoSignature - return - } - - components := strings.Split(headerSignature, " ") - if len(components) != 2 { - result = ResultInvalidFormat - return - } - - algorithm, err := DigestNameToCryptoHash(components[0]) - if err != nil { - result = ResultUnsupportedAlgorithm - return - } - - computedSignature = requestSignature(auth, request, algorithm) - if hmac.Equal([]byte(headerSignature), []byte(computedSignature)) { - result = ResultMatch - } else { - result = ResultMismatch - } - return -} diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/.gitignore b/Godeps/_workspace/src/github.com/BurntSushi/toml/.gitignore deleted file mode 100644 index 0cd380037..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -TAGS -tags -.*.swp -tomlcheck/tomlcheck -toml.test diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/.travis.yml b/Godeps/_workspace/src/github.com/BurntSushi/toml/.travis.yml deleted file mode 100644 index 43caf6d02..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/.travis.yml +++ /dev/null @@ -1,12 +0,0 @@ -language: go -go: - - 1.1 - - 1.2 - - tip -install: - - go install ./... - - go get github.com/BurntSushi/toml-test -script: - - export PATH="$PATH:$HOME/gopath/bin" - - make test - diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/COMPATIBLE b/Godeps/_workspace/src/github.com/BurntSushi/toml/COMPATIBLE deleted file mode 100644 index 21e0938ca..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/COMPATIBLE +++ /dev/null @@ -1,3 +0,0 @@ -Compatible with TOML version -[v0.2.0](https://github.com/mojombo/toml/blob/master/versions/toml-v0.2.0.md) - diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/COPYING b/Godeps/_workspace/src/github.com/BurntSushi/toml/COPYING deleted file mode 100644 index 5a8e33254..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/COPYING +++ /dev/null @@ -1,14 +0,0 @@ - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - Version 2, December 2004 - - Copyright (C) 2004 Sam Hocevar - - Everyone is permitted to copy and distribute verbatim or modified - copies of this license document, and changing it is allowed as long - as the name is changed. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. You just DO WHAT THE FUCK YOU WANT TO. - diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/Makefile b/Godeps/_workspace/src/github.com/BurntSushi/toml/Makefile deleted file mode 100644 index 3600848d3..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/Makefile +++ /dev/null @@ -1,19 +0,0 @@ -install: - go install ./... - -test: install - go test -v - toml-test toml-test-decoder - toml-test -encoder toml-test-encoder - -fmt: - gofmt -w *.go */*.go - colcheck *.go */*.go - -tags: - find ./ -name '*.go' -print0 | xargs -0 gotags > TAGS - -push: - git push origin master - git push github master - diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/README.md b/Godeps/_workspace/src/github.com/BurntSushi/toml/README.md deleted file mode 100644 index 5a5df6370..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/README.md +++ /dev/null @@ -1,220 +0,0 @@ -## TOML parser and encoder for Go with reflection - -TOML stands for Tom's Obvious, Minimal Language. This Go package provides a -reflection interface similar to Go's standard library `json` and `xml` -packages. This package also supports the `encoding.TextUnmarshaler` and -`encoding.TextMarshaler` interfaces so that you can define custom data -representations. (There is an example of this below.) - -Spec: https://github.com/mojombo/toml - -Compatible with TOML version -[v0.2.0](https://github.com/toml-lang/toml/blob/master/versions/en/toml-v0.2.0.md) - -Documentation: http://godoc.org/github.com/BurntSushi/toml - -Installation: - -```bash -go get github.com/BurntSushi/toml -``` - -Try the toml validator: - -```bash -go get github.com/BurntSushi/toml/cmd/tomlv -tomlv some-toml-file.toml -``` - -[![Build status](https://api.travis-ci.org/BurntSushi/toml.png)](https://travis-ci.org/BurntSushi/toml) - - -### Testing - -This package passes all tests in -[toml-test](https://github.com/BurntSushi/toml-test) for both the decoder -and the encoder. - -### Examples - -This package works similarly to how the Go standard library handles `XML` -and `JSON`. Namely, data is loaded into Go values via reflection. - -For the simplest example, consider some TOML file as just a list of keys -and values: - -```toml -Age = 25 -Cats = [ "Cauchy", "Plato" ] -Pi = 3.14 -Perfection = [ 6, 28, 496, 8128 ] -DOB = 1987-07-05T05:45:00Z -``` - -Which could be defined in Go as: - -```go -type Config struct { - Age int - Cats []string - Pi float64 - Perfection []int - DOB time.Time // requires `import time` -} -``` - -And then decoded with: - -```go -var conf Config -if _, err := toml.Decode(tomlData, &conf); err != nil { - // handle error -} -``` - -You can also use struct tags if your struct field name doesn't map to a TOML -key value directly: - -```toml -some_key_NAME = "wat" -``` - -```go -type TOML struct { - ObscureKey string `toml:"some_key_NAME"` -} -``` - -### Using the `encoding.TextUnmarshaler` interface - -Here's an example that automatically parses duration strings into -`time.Duration` values: - -```toml -[[song]] -name = "Thunder Road" -duration = "4m49s" - -[[song]] -name = "Stairway to Heaven" -duration = "8m03s" -``` - -Which can be decoded with: - -```go -type song struct { - Name string - Duration duration -} -type songs struct { - Song []song -} -var favorites songs -if _, err := toml.Decode(blob, &favorites); err != nil { - log.Fatal(err) -} - -for _, s := range favorites.Song { - fmt.Printf("%s (%s)\n", s.Name, s.Duration) -} -``` - -And you'll also need a `duration` type that satisfies the -`encoding.TextUnmarshaler` interface: - -```go -type duration struct { - time.Duration -} - -func (d *duration) UnmarshalText(text []byte) error { - var err error - d.Duration, err = time.ParseDuration(string(text)) - return err -} -``` - -### More complex usage - -Here's an example of how to load the example from the official spec page: - -```toml -# This is a TOML document. Boom. - -title = "TOML Example" - -[owner] -name = "Tom Preston-Werner" -organization = "GitHub" -bio = "GitHub Cofounder & CEO\nLikes tater tots and beer." -dob = 1979-05-27T07:32:00Z # First class dates? Why not? - -[database] -server = "192.168.1.1" -ports = [ 8001, 8001, 8002 ] -connection_max = 5000 -enabled = true - -[servers] - - # You can indent as you please. Tabs or spaces. TOML don't care. - [servers.alpha] - ip = "10.0.0.1" - dc = "eqdc10" - - [servers.beta] - ip = "10.0.0.2" - dc = "eqdc10" - -[clients] -data = [ ["gamma", "delta"], [1, 2] ] # just an update to make sure parsers support it - -# Line breaks are OK when inside arrays -hosts = [ - "alpha", - "omega" -] -``` - -And the corresponding Go types are: - -```go -type tomlConfig struct { - Title string - Owner ownerInfo - DB database `toml:"database"` - Servers map[string]server - Clients clients -} - -type ownerInfo struct { - Name string - Org string `toml:"organization"` - Bio string - DOB time.Time -} - -type database struct { - Server string - Ports []int - ConnMax int `toml:"connection_max"` - Enabled bool -} - -type server struct { - IP string - DC string -} - -type clients struct { - Data [][]interface{} - Hosts []string -} -``` - -Note that a case insensitive match will be tried if an exact match can't be -found. - -A working example of the above can be found in `_examples/example.{go,toml}`. - diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/decode.go b/Godeps/_workspace/src/github.com/BurntSushi/toml/decode.go deleted file mode 100644 index 6c7d398b8..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/decode.go +++ /dev/null @@ -1,492 +0,0 @@ -package toml - -import ( - "fmt" - "io" - "io/ioutil" - "math" - "reflect" - "strings" - "time" -) - -var e = fmt.Errorf - -// Unmarshaler is the interface implemented by objects that can unmarshal a -// TOML description of themselves. -type Unmarshaler interface { - UnmarshalTOML(interface{}) error -} - -// Unmarshal decodes the contents of `p` in TOML format into a pointer `v`. -func Unmarshal(p []byte, v interface{}) error { - _, err := Decode(string(p), v) - return err -} - -// Primitive is a TOML value that hasn't been decoded into a Go value. -// When using the various `Decode*` functions, the type `Primitive` may -// be given to any value, and its decoding will be delayed. -// -// A `Primitive` value can be decoded using the `PrimitiveDecode` function. -// -// The underlying representation of a `Primitive` value is subject to change. -// Do not rely on it. -// -// N.B. Primitive values are still parsed, so using them will only avoid -// the overhead of reflection. They can be useful when you don't know the -// exact type of TOML data until run time. -type Primitive struct { - undecoded interface{} - context Key -} - -// DEPRECATED! -// -// Use MetaData.PrimitiveDecode instead. -func PrimitiveDecode(primValue Primitive, v interface{}) error { - md := MetaData{decoded: make(map[string]bool)} - return md.unify(primValue.undecoded, rvalue(v)) -} - -// PrimitiveDecode is just like the other `Decode*` functions, except it -// decodes a TOML value that has already been parsed. Valid primitive values -// can *only* be obtained from values filled by the decoder functions, -// including this method. (i.e., `v` may contain more `Primitive` -// values.) -// -// Meta data for primitive values is included in the meta data returned by -// the `Decode*` functions with one exception: keys returned by the Undecoded -// method will only reflect keys that were decoded. Namely, any keys hidden -// behind a Primitive will be considered undecoded. Executing this method will -// update the undecoded keys in the meta data. (See the example.) -func (md *MetaData) PrimitiveDecode(primValue Primitive, v interface{}) error { - md.context = primValue.context - defer func() { md.context = nil }() - return md.unify(primValue.undecoded, rvalue(v)) -} - -// Decode will decode the contents of `data` in TOML format into a pointer -// `v`. -// -// TOML hashes correspond to Go structs or maps. (Dealer's choice. They can be -// used interchangeably.) -// -// TOML arrays of tables correspond to either a slice of structs or a slice -// of maps. -// -// TOML datetimes correspond to Go `time.Time` values. -// -// All other TOML types (float, string, int, bool and array) correspond -// to the obvious Go types. -// -// An exception to the above rules is if a type implements the -// encoding.TextUnmarshaler interface. In this case, any primitive TOML value -// (floats, strings, integers, booleans and datetimes) will be converted to -// a byte string and given to the value's UnmarshalText method. See the -// Unmarshaler example for a demonstration with time duration strings. -// -// Key mapping -// -// TOML keys can map to either keys in a Go map or field names in a Go -// struct. The special `toml` struct tag may be used to map TOML keys to -// struct fields that don't match the key name exactly. (See the example.) -// A case insensitive match to struct names will be tried if an exact match -// can't be found. -// -// The mapping between TOML values and Go values is loose. That is, there -// may exist TOML values that cannot be placed into your representation, and -// there may be parts of your representation that do not correspond to -// TOML values. This loose mapping can be made stricter by using the IsDefined -// and/or Undecoded methods on the MetaData returned. -// -// This decoder will not handle cyclic types. If a cyclic type is passed, -// `Decode` will not terminate. -func Decode(data string, v interface{}) (MetaData, error) { - p, err := parse(data) - if err != nil { - return MetaData{}, err - } - md := MetaData{ - p.mapping, p.types, p.ordered, - make(map[string]bool, len(p.ordered)), nil, - } - return md, md.unify(p.mapping, rvalue(v)) -} - -// DecodeFile is just like Decode, except it will automatically read the -// contents of the file at `fpath` and decode it for you. -func DecodeFile(fpath string, v interface{}) (MetaData, error) { - bs, err := ioutil.ReadFile(fpath) - if err != nil { - return MetaData{}, err - } - return Decode(string(bs), v) -} - -// DecodeReader is just like Decode, except it will consume all bytes -// from the reader and decode it for you. -func DecodeReader(r io.Reader, v interface{}) (MetaData, error) { - bs, err := ioutil.ReadAll(r) - if err != nil { - return MetaData{}, err - } - return Decode(string(bs), v) -} - -// unify performs a sort of type unification based on the structure of `rv`, -// which is the client representation. -// -// Any type mismatch produces an error. Finding a type that we don't know -// how to handle produces an unsupported type error. -func (md *MetaData) unify(data interface{}, rv reflect.Value) error { - - // Special case. Look for a `Primitive` value. - if rv.Type() == reflect.TypeOf((*Primitive)(nil)).Elem() { - // Save the undecoded data and the key context into the primitive - // value. - context := make(Key, len(md.context)) - copy(context, md.context) - rv.Set(reflect.ValueOf(Primitive{ - undecoded: data, - context: context, - })) - return nil - } - - // Special case. Unmarshaler Interface support. - if rv.CanAddr() { - if v, ok := rv.Addr().Interface().(Unmarshaler); ok { - return v.UnmarshalTOML(data) - } - } - - // Special case. Handle time.Time values specifically. - // TODO: Remove this code when we decide to drop support for Go 1.1. - // This isn't necessary in Go 1.2 because time.Time satisfies the encoding - // interfaces. - if rv.Type().AssignableTo(rvalue(time.Time{}).Type()) { - return md.unifyDatetime(data, rv) - } - - // Special case. Look for a value satisfying the TextUnmarshaler interface. - if v, ok := rv.Interface().(TextUnmarshaler); ok { - return md.unifyText(data, v) - } - // BUG(burntsushi) - // The behavior here is incorrect whenever a Go type satisfies the - // encoding.TextUnmarshaler interface but also corresponds to a TOML - // hash or array. In particular, the unmarshaler should only be applied - // to primitive TOML values. But at this point, it will be applied to - // all kinds of values and produce an incorrect error whenever those values - // are hashes or arrays (including arrays of tables). - - k := rv.Kind() - - // laziness - if k >= reflect.Int && k <= reflect.Uint64 { - return md.unifyInt(data, rv) - } - switch k { - case reflect.Ptr: - elem := reflect.New(rv.Type().Elem()) - err := md.unify(data, reflect.Indirect(elem)) - if err != nil { - return err - } - rv.Set(elem) - return nil - case reflect.Struct: - return md.unifyStruct(data, rv) - case reflect.Map: - return md.unifyMap(data, rv) - case reflect.Array: - return md.unifyArray(data, rv) - case reflect.Slice: - return md.unifySlice(data, rv) - case reflect.String: - return md.unifyString(data, rv) - case reflect.Bool: - return md.unifyBool(data, rv) - case reflect.Interface: - // we only support empty interfaces. - if rv.NumMethod() > 0 { - return e("Unsupported type '%s'.", rv.Kind()) - } - return md.unifyAnything(data, rv) - case reflect.Float32: - fallthrough - case reflect.Float64: - return md.unifyFloat64(data, rv) - } - return e("Unsupported type '%s'.", rv.Kind()) -} - -func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { - tmap, ok := mapping.(map[string]interface{}) - if !ok { - return mismatch(rv, "map", mapping) - } - - for key, datum := range tmap { - var f *field - fields := cachedTypeFields(rv.Type()) - for i := range fields { - ff := &fields[i] - if ff.name == key { - f = ff - break - } - if f == nil && strings.EqualFold(ff.name, key) { - f = ff - } - } - if f != nil { - subv := rv - for _, i := range f.index { - subv = indirect(subv.Field(i)) - } - if isUnifiable(subv) { - md.decoded[md.context.add(key).String()] = true - md.context = append(md.context, key) - if err := md.unify(datum, subv); err != nil { - return e("Type mismatch for '%s.%s': %s", - rv.Type().String(), f.name, err) - } - md.context = md.context[0 : len(md.context)-1] - } else if f.name != "" { - // Bad user! No soup for you! - return e("Field '%s.%s' is unexported, and therefore cannot "+ - "be loaded with reflection.", rv.Type().String(), f.name) - } - } - } - return nil -} - -func (md *MetaData) unifyMap(mapping interface{}, rv reflect.Value) error { - tmap, ok := mapping.(map[string]interface{}) - if !ok { - return badtype("map", mapping) - } - if rv.IsNil() { - rv.Set(reflect.MakeMap(rv.Type())) - } - for k, v := range tmap { - md.decoded[md.context.add(k).String()] = true - md.context = append(md.context, k) - - rvkey := indirect(reflect.New(rv.Type().Key())) - rvval := reflect.Indirect(reflect.New(rv.Type().Elem())) - if err := md.unify(v, rvval); err != nil { - return err - } - md.context = md.context[0 : len(md.context)-1] - - rvkey.SetString(k) - rv.SetMapIndex(rvkey, rvval) - } - return nil -} - -func (md *MetaData) unifyArray(data interface{}, rv reflect.Value) error { - datav := reflect.ValueOf(data) - if datav.Kind() != reflect.Slice { - return badtype("slice", data) - } - sliceLen := datav.Len() - if sliceLen != rv.Len() { - return e("expected array length %d; got TOML array of length %d", - rv.Len(), sliceLen) - } - return md.unifySliceArray(datav, rv) -} - -func (md *MetaData) unifySlice(data interface{}, rv reflect.Value) error { - datav := reflect.ValueOf(data) - if datav.Kind() != reflect.Slice { - return badtype("slice", data) - } - sliceLen := datav.Len() - if rv.IsNil() { - rv.Set(reflect.MakeSlice(rv.Type(), sliceLen, sliceLen)) - } - return md.unifySliceArray(datav, rv) -} - -func (md *MetaData) unifySliceArray(data, rv reflect.Value) error { - sliceLen := data.Len() - for i := 0; i < sliceLen; i++ { - v := data.Index(i).Interface() - sliceval := indirect(rv.Index(i)) - if err := md.unify(v, sliceval); err != nil { - return err - } - } - return nil -} - -func (md *MetaData) unifyDatetime(data interface{}, rv reflect.Value) error { - if _, ok := data.(time.Time); ok { - rv.Set(reflect.ValueOf(data)) - return nil - } - return badtype("time.Time", data) -} - -func (md *MetaData) unifyString(data interface{}, rv reflect.Value) error { - if s, ok := data.(string); ok { - rv.SetString(s) - return nil - } - return badtype("string", data) -} - -func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error { - if num, ok := data.(float64); ok { - switch rv.Kind() { - case reflect.Float32: - fallthrough - case reflect.Float64: - rv.SetFloat(num) - default: - panic("bug") - } - return nil - } - return badtype("float", data) -} - -func (md *MetaData) unifyInt(data interface{}, rv reflect.Value) error { - if num, ok := data.(int64); ok { - if rv.Kind() >= reflect.Int && rv.Kind() <= reflect.Int64 { - switch rv.Kind() { - case reflect.Int, reflect.Int64: - // No bounds checking necessary. - case reflect.Int8: - if num < math.MinInt8 || num > math.MaxInt8 { - return e("Value '%d' is out of range for int8.", num) - } - case reflect.Int16: - if num < math.MinInt16 || num > math.MaxInt16 { - return e("Value '%d' is out of range for int16.", num) - } - case reflect.Int32: - if num < math.MinInt32 || num > math.MaxInt32 { - return e("Value '%d' is out of range for int32.", num) - } - } - rv.SetInt(num) - } else if rv.Kind() >= reflect.Uint && rv.Kind() <= reflect.Uint64 { - unum := uint64(num) - switch rv.Kind() { - case reflect.Uint, reflect.Uint64: - // No bounds checking necessary. - case reflect.Uint8: - if num < 0 || unum > math.MaxUint8 { - return e("Value '%d' is out of range for uint8.", num) - } - case reflect.Uint16: - if num < 0 || unum > math.MaxUint16 { - return e("Value '%d' is out of range for uint16.", num) - } - case reflect.Uint32: - if num < 0 || unum > math.MaxUint32 { - return e("Value '%d' is out of range for uint32.", num) - } - } - rv.SetUint(unum) - } else { - panic("unreachable") - } - return nil - } - return badtype("integer", data) -} - -func (md *MetaData) unifyBool(data interface{}, rv reflect.Value) error { - if b, ok := data.(bool); ok { - rv.SetBool(b) - return nil - } - return badtype("boolean", data) -} - -func (md *MetaData) unifyAnything(data interface{}, rv reflect.Value) error { - rv.Set(reflect.ValueOf(data)) - return nil -} - -func (md *MetaData) unifyText(data interface{}, v TextUnmarshaler) error { - var s string - switch sdata := data.(type) { - case TextMarshaler: - text, err := sdata.MarshalText() - if err != nil { - return err - } - s = string(text) - case fmt.Stringer: - s = sdata.String() - case string: - s = sdata - case bool: - s = fmt.Sprintf("%v", sdata) - case int64: - s = fmt.Sprintf("%d", sdata) - case float64: - s = fmt.Sprintf("%f", sdata) - default: - return badtype("primitive (string-like)", data) - } - if err := v.UnmarshalText([]byte(s)); err != nil { - return err - } - return nil -} - -// rvalue returns a reflect.Value of `v`. All pointers are resolved. -func rvalue(v interface{}) reflect.Value { - return indirect(reflect.ValueOf(v)) -} - -// indirect returns the value pointed to by a pointer. -// Pointers are followed until the value is not a pointer. -// New values are allocated for each nil pointer. -// -// An exception to this rule is if the value satisfies an interface of -// interest to us (like encoding.TextUnmarshaler). -func indirect(v reflect.Value) reflect.Value { - if v.Kind() != reflect.Ptr { - if v.CanAddr() { - pv := v.Addr() - if _, ok := pv.Interface().(TextUnmarshaler); ok { - return pv - } - } - return v - } - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - return indirect(reflect.Indirect(v)) -} - -func isUnifiable(rv reflect.Value) bool { - if rv.CanSet() { - return true - } - if _, ok := rv.Interface().(TextUnmarshaler); ok { - return true - } - return false -} - -func badtype(expected string, data interface{}) error { - return e("Expected %s but found '%T'.", expected, data) -} - -func mismatch(user reflect.Value, expected string, data interface{}) error { - return e("Type mismatch for %s. Expected %s but found '%T'.", - user.Type().String(), expected, data) -} diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/decode_meta.go b/Godeps/_workspace/src/github.com/BurntSushi/toml/decode_meta.go deleted file mode 100644 index ef6f545fa..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/decode_meta.go +++ /dev/null @@ -1,122 +0,0 @@ -package toml - -import "strings" - -// MetaData allows access to meta information about TOML data that may not -// be inferrable via reflection. In particular, whether a key has been defined -// and the TOML type of a key. -type MetaData struct { - mapping map[string]interface{} - types map[string]tomlType - keys []Key - decoded map[string]bool - context Key // Used only during decoding. -} - -// IsDefined returns true if the key given exists in the TOML data. The key -// should be specified hierarchially. e.g., -// -// // access the TOML key 'a.b.c' -// IsDefined("a", "b", "c") -// -// IsDefined will return false if an empty key given. Keys are case sensitive. -func (md *MetaData) IsDefined(key ...string) bool { - if len(key) == 0 { - return false - } - - var hash map[string]interface{} - var ok bool - var hashOrVal interface{} = md.mapping - for _, k := range key { - if hash, ok = hashOrVal.(map[string]interface{}); !ok { - return false - } - if hashOrVal, ok = hash[k]; !ok { - return false - } - } - return true -} - -// Type returns a string representation of the type of the key specified. -// -// Type will return the empty string if given an empty key or a key that -// does not exist. Keys are case sensitive. -func (md *MetaData) Type(key ...string) string { - fullkey := strings.Join(key, ".") - if typ, ok := md.types[fullkey]; ok { - return typ.typeString() - } - return "" -} - -// Key is the type of any TOML key, including key groups. Use (MetaData).Keys -// to get values of this type. -type Key []string - -func (k Key) String() string { - return strings.Join(k, ".") -} - -func (k Key) maybeQuotedAll() string { - var ss []string - for i := range k { - ss = append(ss, k.maybeQuoted(i)) - } - return strings.Join(ss, ".") -} - -func (k Key) maybeQuoted(i int) string { - quote := false - for _, c := range k[i] { - if !isBareKeyChar(c) { - quote = true - break - } - } - if quote { - return "\"" + strings.Replace(k[i], "\"", "\\\"", -1) + "\"" - } else { - return k[i] - } -} - -func (k Key) add(piece string) Key { - newKey := make(Key, len(k)+1) - copy(newKey, k) - newKey[len(k)] = piece - return newKey -} - -// Keys returns a slice of every key in the TOML data, including key groups. -// Each key is itself a slice, where the first element is the top of the -// hierarchy and the last is the most specific. -// -// The list will have the same order as the keys appeared in the TOML data. -// -// All keys returned are non-empty. -func (md *MetaData) Keys() []Key { - return md.keys -} - -// Undecoded returns all keys that have not been decoded in the order in which -// they appear in the original TOML document. -// -// This includes keys that haven't been decoded because of a Primitive value. -// Once the Primitive value is decoded, the keys will be considered decoded. -// -// Also note that decoding into an empty interface will result in no decoding, -// and so no keys will be considered decoded. -// -// In this sense, the Undecoded keys correspond to keys in the TOML document -// that do not have a concrete type in your representation. -func (md *MetaData) Undecoded() []Key { - undecoded := make([]Key, 0, len(md.keys)) - for _, key := range md.keys { - if !md.decoded[key.String()] { - undecoded = append(undecoded, key) - } - } - return undecoded -} diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/doc.go b/Godeps/_workspace/src/github.com/BurntSushi/toml/doc.go deleted file mode 100644 index fe2680004..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/doc.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Package toml provides facilities for decoding and encoding TOML configuration -files via reflection. There is also support for delaying decoding with -the Primitive type, and querying the set of keys in a TOML document with the -MetaData type. - -The specification implemented: https://github.com/mojombo/toml - -The sub-command github.com/BurntSushi/toml/cmd/tomlv can be used to verify -whether a file is a valid TOML document. It can also be used to print the -type of each key in a TOML document. - -Testing - -There are two important types of tests used for this package. The first is -contained inside '*_test.go' files and uses the standard Go unit testing -framework. These tests are primarily devoted to holistically testing the -decoder and encoder. - -The second type of testing is used to verify the implementation's adherence -to the TOML specification. These tests have been factored into their own -project: https://github.com/BurntSushi/toml-test - -The reason the tests are in a separate project is so that they can be used by -any implementation of TOML. Namely, it is language agnostic. -*/ -package toml diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/encode.go b/Godeps/_workspace/src/github.com/BurntSushi/toml/encode.go deleted file mode 100644 index c7e227c7f..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/encode.go +++ /dev/null @@ -1,551 +0,0 @@ -package toml - -import ( - "bufio" - "errors" - "fmt" - "io" - "reflect" - "sort" - "strconv" - "strings" - "time" -) - -type tomlEncodeError struct{ error } - -var ( - errArrayMixedElementTypes = errors.New( - "can't encode array with mixed element types") - errArrayNilElement = errors.New( - "can't encode array with nil element") - errNonString = errors.New( - "can't encode a map with non-string key type") - errAnonNonStruct = errors.New( - "can't encode an anonymous field that is not a struct") - errArrayNoTable = errors.New( - "TOML array element can't contain a table") - errNoKey = errors.New( - "top-level values must be a Go map or struct") - errAnything = errors.New("") // used in testing -) - -var quotedReplacer = strings.NewReplacer( - "\t", "\\t", - "\n", "\\n", - "\r", "\\r", - "\"", "\\\"", - "\\", "\\\\", -) - -// Encoder controls the encoding of Go values to a TOML document to some -// io.Writer. -// -// The indentation level can be controlled with the Indent field. -type Encoder struct { - // A single indentation level. By default it is two spaces. - Indent string - - // hasWritten is whether we have written any output to w yet. - hasWritten bool - w *bufio.Writer -} - -// NewEncoder returns a TOML encoder that encodes Go values to the io.Writer -// given. By default, a single indentation level is 2 spaces. -func NewEncoder(w io.Writer) *Encoder { - return &Encoder{ - w: bufio.NewWriter(w), - Indent: " ", - } -} - -// Encode writes a TOML representation of the Go value to the underlying -// io.Writer. If the value given cannot be encoded to a valid TOML document, -// then an error is returned. -// -// The mapping between Go values and TOML values should be precisely the same -// as for the Decode* functions. Similarly, the TextMarshaler interface is -// supported by encoding the resulting bytes as strings. (If you want to write -// arbitrary binary data then you will need to use something like base64 since -// TOML does not have any binary types.) -// -// When encoding TOML hashes (i.e., Go maps or structs), keys without any -// sub-hashes are encoded first. -// -// If a Go map is encoded, then its keys are sorted alphabetically for -// deterministic output. More control over this behavior may be provided if -// there is demand for it. -// -// Encoding Go values without a corresponding TOML representation---like map -// types with non-string keys---will cause an error to be returned. Similarly -// for mixed arrays/slices, arrays/slices with nil elements, embedded -// non-struct types and nested slices containing maps or structs. -// (e.g., [][]map[string]string is not allowed but []map[string]string is OK -// and so is []map[string][]string.) -func (enc *Encoder) Encode(v interface{}) error { - rv := eindirect(reflect.ValueOf(v)) - if err := enc.safeEncode(Key([]string{}), rv); err != nil { - return err - } - return enc.w.Flush() -} - -func (enc *Encoder) safeEncode(key Key, rv reflect.Value) (err error) { - defer func() { - if r := recover(); r != nil { - if terr, ok := r.(tomlEncodeError); ok { - err = terr.error - return - } - panic(r) - } - }() - enc.encode(key, rv) - return nil -} - -func (enc *Encoder) encode(key Key, rv reflect.Value) { - // Special case. Time needs to be in ISO8601 format. - // Special case. If we can marshal the type to text, then we used that. - // Basically, this prevents the encoder for handling these types as - // generic structs (or whatever the underlying type of a TextMarshaler is). - switch rv.Interface().(type) { - case time.Time, TextMarshaler: - enc.keyEqElement(key, rv) - return - } - - k := rv.Kind() - switch k { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, - reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, - reflect.Uint64, - reflect.Float32, reflect.Float64, reflect.String, reflect.Bool: - enc.keyEqElement(key, rv) - case reflect.Array, reflect.Slice: - if typeEqual(tomlArrayHash, tomlTypeOfGo(rv)) { - enc.eArrayOfTables(key, rv) - } else { - enc.keyEqElement(key, rv) - } - case reflect.Interface: - if rv.IsNil() { - return - } - enc.encode(key, rv.Elem()) - case reflect.Map: - if rv.IsNil() { - return - } - enc.eTable(key, rv) - case reflect.Ptr: - if rv.IsNil() { - return - } - enc.encode(key, rv.Elem()) - case reflect.Struct: - enc.eTable(key, rv) - default: - panic(e("Unsupported type for key '%s': %s", key, k)) - } -} - -// eElement encodes any value that can be an array element (primitives and -// arrays). -func (enc *Encoder) eElement(rv reflect.Value) { - switch v := rv.Interface().(type) { - case time.Time: - // Special case time.Time as a primitive. Has to come before - // TextMarshaler below because time.Time implements - // encoding.TextMarshaler, but we need to always use UTC. - enc.wf(v.In(time.FixedZone("UTC", 0)).Format("2006-01-02T15:04:05Z")) - return - case TextMarshaler: - // Special case. Use text marshaler if it's available for this value. - if s, err := v.MarshalText(); err != nil { - encPanic(err) - } else { - enc.writeQuoted(string(s)) - } - return - } - switch rv.Kind() { - case reflect.Bool: - enc.wf(strconv.FormatBool(rv.Bool())) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, - reflect.Int64: - enc.wf(strconv.FormatInt(rv.Int(), 10)) - case reflect.Uint, reflect.Uint8, reflect.Uint16, - reflect.Uint32, reflect.Uint64: - enc.wf(strconv.FormatUint(rv.Uint(), 10)) - case reflect.Float32: - enc.wf(floatAddDecimal(strconv.FormatFloat(rv.Float(), 'f', -1, 32))) - case reflect.Float64: - enc.wf(floatAddDecimal(strconv.FormatFloat(rv.Float(), 'f', -1, 64))) - case reflect.Array, reflect.Slice: - enc.eArrayOrSliceElement(rv) - case reflect.Interface: - enc.eElement(rv.Elem()) - case reflect.String: - enc.writeQuoted(rv.String()) - default: - panic(e("Unexpected primitive type: %s", rv.Kind())) - } -} - -// By the TOML spec, all floats must have a decimal with at least one -// number on either side. -func floatAddDecimal(fstr string) string { - if !strings.Contains(fstr, ".") { - return fstr + ".0" - } - return fstr -} - -func (enc *Encoder) writeQuoted(s string) { - enc.wf("\"%s\"", quotedReplacer.Replace(s)) -} - -func (enc *Encoder) eArrayOrSliceElement(rv reflect.Value) { - length := rv.Len() - enc.wf("[") - for i := 0; i < length; i++ { - elem := rv.Index(i) - enc.eElement(elem) - if i != length-1 { - enc.wf(", ") - } - } - enc.wf("]") -} - -func (enc *Encoder) eArrayOfTables(key Key, rv reflect.Value) { - if len(key) == 0 { - encPanic(errNoKey) - } - for i := 0; i < rv.Len(); i++ { - trv := rv.Index(i) - if isNil(trv) { - continue - } - panicIfInvalidKey(key) - enc.newline() - enc.wf("%s[[%s]]", enc.indentStr(key), key.maybeQuotedAll()) - enc.newline() - enc.eMapOrStruct(key, trv) - } -} - -func (enc *Encoder) eTable(key Key, rv reflect.Value) { - panicIfInvalidKey(key) - if len(key) == 1 { - // Output an extra new line between top-level tables. - // (The newline isn't written if nothing else has been written though.) - enc.newline() - } - if len(key) > 0 { - enc.wf("%s[%s]", enc.indentStr(key), key.maybeQuotedAll()) - enc.newline() - } - enc.eMapOrStruct(key, rv) -} - -func (enc *Encoder) eMapOrStruct(key Key, rv reflect.Value) { - switch rv := eindirect(rv); rv.Kind() { - case reflect.Map: - enc.eMap(key, rv) - case reflect.Struct: - enc.eStruct(key, rv) - default: - panic("eTable: unhandled reflect.Value Kind: " + rv.Kind().String()) - } -} - -func (enc *Encoder) eMap(key Key, rv reflect.Value) { - rt := rv.Type() - if rt.Key().Kind() != reflect.String { - encPanic(errNonString) - } - - // Sort keys so that we have deterministic output. And write keys directly - // underneath this key first, before writing sub-structs or sub-maps. - var mapKeysDirect, mapKeysSub []string - for _, mapKey := range rv.MapKeys() { - k := mapKey.String() - if typeIsHash(tomlTypeOfGo(rv.MapIndex(mapKey))) { - mapKeysSub = append(mapKeysSub, k) - } else { - mapKeysDirect = append(mapKeysDirect, k) - } - } - - var writeMapKeys = func(mapKeys []string) { - sort.Strings(mapKeys) - for _, mapKey := range mapKeys { - mrv := rv.MapIndex(reflect.ValueOf(mapKey)) - if isNil(mrv) { - // Don't write anything for nil fields. - continue - } - enc.encode(key.add(mapKey), mrv) - } - } - writeMapKeys(mapKeysDirect) - writeMapKeys(mapKeysSub) -} - -func (enc *Encoder) eStruct(key Key, rv reflect.Value) { - // Write keys for fields directly under this key first, because if we write - // a field that creates a new table, then all keys under it will be in that - // table (not the one we're writing here). - rt := rv.Type() - var fieldsDirect, fieldsSub [][]int - var addFields func(rt reflect.Type, rv reflect.Value, start []int) - addFields = func(rt reflect.Type, rv reflect.Value, start []int) { - for i := 0; i < rt.NumField(); i++ { - f := rt.Field(i) - // skip unexporded fields - if f.PkgPath != "" { - continue - } - frv := rv.Field(i) - if f.Anonymous { - frv := eindirect(frv) - t := frv.Type() - if t.Kind() != reflect.Struct { - encPanic(errAnonNonStruct) - } - addFields(t, frv, f.Index) - } else if typeIsHash(tomlTypeOfGo(frv)) { - fieldsSub = append(fieldsSub, append(start, f.Index...)) - } else { - fieldsDirect = append(fieldsDirect, append(start, f.Index...)) - } - } - } - addFields(rt, rv, nil) - - var writeFields = func(fields [][]int) { - for _, fieldIndex := range fields { - sft := rt.FieldByIndex(fieldIndex) - sf := rv.FieldByIndex(fieldIndex) - if isNil(sf) { - // Don't write anything for nil fields. - continue - } - - keyName := sft.Tag.Get("toml") - if keyName == "-" { - continue - } - if keyName == "" { - keyName = sft.Name - } - - keyName, opts := getOptions(keyName) - if _, ok := opts["omitempty"]; ok && isEmpty(sf) { - continue - } else if _, ok := opts["omitzero"]; ok && isZero(sf) { - continue - } - - enc.encode(key.add(keyName), sf) - } - } - writeFields(fieldsDirect) - writeFields(fieldsSub) -} - -// tomlTypeName returns the TOML type name of the Go value's type. It is -// used to determine whether the types of array elements are mixed (which is -// forbidden). If the Go value is nil, then it is illegal for it to be an array -// element, and valueIsNil is returned as true. - -// Returns the TOML type of a Go value. The type may be `nil`, which means -// no concrete TOML type could be found. -func tomlTypeOfGo(rv reflect.Value) tomlType { - if isNil(rv) || !rv.IsValid() { - return nil - } - switch rv.Kind() { - case reflect.Bool: - return tomlBool - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, - reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, - reflect.Uint64: - return tomlInteger - case reflect.Float32, reflect.Float64: - return tomlFloat - case reflect.Array, reflect.Slice: - if typeEqual(tomlHash, tomlArrayType(rv)) { - return tomlArrayHash - } else { - return tomlArray - } - case reflect.Ptr, reflect.Interface: - return tomlTypeOfGo(rv.Elem()) - case reflect.String: - return tomlString - case reflect.Map: - return tomlHash - case reflect.Struct: - switch rv.Interface().(type) { - case time.Time: - return tomlDatetime - case TextMarshaler: - return tomlString - default: - return tomlHash - } - default: - panic("unexpected reflect.Kind: " + rv.Kind().String()) - } -} - -// tomlArrayType returns the element type of a TOML array. The type returned -// may be nil if it cannot be determined (e.g., a nil slice or a zero length -// slize). This function may also panic if it finds a type that cannot be -// expressed in TOML (such as nil elements, heterogeneous arrays or directly -// nested arrays of tables). -func tomlArrayType(rv reflect.Value) tomlType { - if isNil(rv) || !rv.IsValid() || rv.Len() == 0 { - return nil - } - firstType := tomlTypeOfGo(rv.Index(0)) - if firstType == nil { - encPanic(errArrayNilElement) - } - - rvlen := rv.Len() - for i := 1; i < rvlen; i++ { - elem := rv.Index(i) - switch elemType := tomlTypeOfGo(elem); { - case elemType == nil: - encPanic(errArrayNilElement) - case !typeEqual(firstType, elemType): - encPanic(errArrayMixedElementTypes) - } - } - // If we have a nested array, then we must make sure that the nested - // array contains ONLY primitives. - // This checks arbitrarily nested arrays. - if typeEqual(firstType, tomlArray) || typeEqual(firstType, tomlArrayHash) { - nest := tomlArrayType(eindirect(rv.Index(0))) - if typeEqual(nest, tomlHash) || typeEqual(nest, tomlArrayHash) { - encPanic(errArrayNoTable) - } - } - return firstType -} - -func getOptions(keyName string) (string, map[string]struct{}) { - opts := make(map[string]struct{}) - ss := strings.Split(keyName, ",") - name := ss[0] - if len(ss) > 1 { - for _, opt := range ss { - opts[opt] = struct{}{} - } - } - - return name, opts -} - -func isZero(rv reflect.Value) bool { - switch rv.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - if rv.Int() == 0 { - return true - } - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - if rv.Uint() == 0 { - return true - } - case reflect.Float32, reflect.Float64: - if rv.Float() == 0.0 { - return true - } - } - - return false -} - -func isEmpty(rv reflect.Value) bool { - switch rv.Kind() { - case reflect.String: - if len(strings.TrimSpace(rv.String())) == 0 { - return true - } - case reflect.Array, reflect.Slice, reflect.Map: - if rv.Len() == 0 { - return true - } - } - - return false -} - -func (enc *Encoder) newline() { - if enc.hasWritten { - enc.wf("\n") - } -} - -func (enc *Encoder) keyEqElement(key Key, val reflect.Value) { - if len(key) == 0 { - encPanic(errNoKey) - } - panicIfInvalidKey(key) - enc.wf("%s%s = ", enc.indentStr(key), key.maybeQuoted(len(key)-1)) - enc.eElement(val) - enc.newline() -} - -func (enc *Encoder) wf(format string, v ...interface{}) { - if _, err := fmt.Fprintf(enc.w, format, v...); err != nil { - encPanic(err) - } - enc.hasWritten = true -} - -func (enc *Encoder) indentStr(key Key) string { - return strings.Repeat(enc.Indent, len(key)-1) -} - -func encPanic(err error) { - panic(tomlEncodeError{err}) -} - -func eindirect(v reflect.Value) reflect.Value { - switch v.Kind() { - case reflect.Ptr, reflect.Interface: - return eindirect(v.Elem()) - default: - return v - } -} - -func isNil(rv reflect.Value) bool { - switch rv.Kind() { - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return rv.IsNil() - default: - return false - } -} - -func panicIfInvalidKey(key Key) { - for _, k := range key { - if len(k) == 0 { - encPanic(e("Key '%s' is not a valid table name. Key names "+ - "cannot be empty.", key.maybeQuotedAll())) - } - } -} - -func isValidKeyName(s string) bool { - return len(s) != 0 -} diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/encoding_types.go b/Godeps/_workspace/src/github.com/BurntSushi/toml/encoding_types.go deleted file mode 100644 index d36e1dd60..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/encoding_types.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build go1.2 - -package toml - -// In order to support Go 1.1, we define our own TextMarshaler and -// TextUnmarshaler types. For Go 1.2+, we just alias them with the -// standard library interfaces. - -import ( - "encoding" -) - -// TextMarshaler is a synonym for encoding.TextMarshaler. It is defined here -// so that Go 1.1 can be supported. -type TextMarshaler encoding.TextMarshaler - -// TextUnmarshaler is a synonym for encoding.TextUnmarshaler. It is defined -// here so that Go 1.1 can be supported. -type TextUnmarshaler encoding.TextUnmarshaler diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/encoding_types_1.1.go b/Godeps/_workspace/src/github.com/BurntSushi/toml/encoding_types_1.1.go deleted file mode 100644 index e8d503d04..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/encoding_types_1.1.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build !go1.2 - -package toml - -// These interfaces were introduced in Go 1.2, so we add them manually when -// compiling for Go 1.1. - -// TextMarshaler is a synonym for encoding.TextMarshaler. It is defined here -// so that Go 1.1 can be supported. -type TextMarshaler interface { - MarshalText() (text []byte, err error) -} - -// TextUnmarshaler is a synonym for encoding.TextUnmarshaler. It is defined -// here so that Go 1.1 can be supported. -type TextUnmarshaler interface { - UnmarshalText(text []byte) error -} diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/lex.go b/Godeps/_workspace/src/github.com/BurntSushi/toml/lex.go deleted file mode 100644 index 08dce77ba..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/lex.go +++ /dev/null @@ -1,872 +0,0 @@ -package toml - -import ( - "fmt" - "strings" - "unicode/utf8" -) - -type itemType int - -const ( - itemError itemType = iota - itemNIL // used in the parser to indicate no type - itemEOF - itemText - itemString - itemRawString - itemMultilineString - itemRawMultilineString - itemBool - itemInteger - itemFloat - itemDatetime - itemArray // the start of an array - itemArrayEnd - itemTableStart - itemTableEnd - itemArrayTableStart - itemArrayTableEnd - itemKeyStart - itemCommentStart -) - -const ( - eof = 0 - tableStart = '[' - tableEnd = ']' - arrayTableStart = '[' - arrayTableEnd = ']' - tableSep = '.' - keySep = '=' - arrayStart = '[' - arrayEnd = ']' - arrayValTerm = ',' - commentStart = '#' - stringStart = '"' - stringEnd = '"' - rawStringStart = '\'' - rawStringEnd = '\'' -) - -type stateFn func(lx *lexer) stateFn - -type lexer struct { - input string - start int - pos int - width int - line int - state stateFn - items chan item - - // A stack of state functions used to maintain context. - // The idea is to reuse parts of the state machine in various places. - // For example, values can appear at the top level or within arbitrarily - // nested arrays. The last state on the stack is used after a value has - // been lexed. Similarly for comments. - stack []stateFn -} - -type item struct { - typ itemType - val string - line int -} - -func (lx *lexer) nextItem() item { - for { - select { - case item := <-lx.items: - return item - default: - lx.state = lx.state(lx) - } - } -} - -func lex(input string) *lexer { - lx := &lexer{ - input: input + "\n", - state: lexTop, - line: 1, - items: make(chan item, 10), - stack: make([]stateFn, 0, 10), - } - return lx -} - -func (lx *lexer) push(state stateFn) { - lx.stack = append(lx.stack, state) -} - -func (lx *lexer) pop() stateFn { - if len(lx.stack) == 0 { - return lx.errorf("BUG in lexer: no states to pop.") - } - last := lx.stack[len(lx.stack)-1] - lx.stack = lx.stack[0 : len(lx.stack)-1] - return last -} - -func (lx *lexer) current() string { - return lx.input[lx.start:lx.pos] -} - -func (lx *lexer) emit(typ itemType) { - lx.items <- item{typ, lx.current(), lx.line} - lx.start = lx.pos -} - -func (lx *lexer) emitTrim(typ itemType) { - lx.items <- item{typ, strings.TrimSpace(lx.current()), lx.line} - lx.start = lx.pos -} - -func (lx *lexer) next() (r rune) { - if lx.pos >= len(lx.input) { - lx.width = 0 - return eof - } - - if lx.input[lx.pos] == '\n' { - lx.line++ - } - r, lx.width = utf8.DecodeRuneInString(lx.input[lx.pos:]) - lx.pos += lx.width - return r -} - -// ignore skips over the pending input before this point. -func (lx *lexer) ignore() { - lx.start = lx.pos -} - -// backup steps back one rune. Can be called only once per call of next. -func (lx *lexer) backup() { - lx.pos -= lx.width - if lx.pos < len(lx.input) && lx.input[lx.pos] == '\n' { - lx.line-- - } -} - -// accept consumes the next rune if it's equal to `valid`. -func (lx *lexer) accept(valid rune) bool { - if lx.next() == valid { - return true - } - lx.backup() - return false -} - -// peek returns but does not consume the next rune in the input. -func (lx *lexer) peek() rune { - r := lx.next() - lx.backup() - return r -} - -// errorf stops all lexing by emitting an error and returning `nil`. -// Note that any value that is a character is escaped if it's a special -// character (new lines, tabs, etc.). -func (lx *lexer) errorf(format string, values ...interface{}) stateFn { - lx.items <- item{ - itemError, - fmt.Sprintf(format, values...), - lx.line, - } - return nil -} - -// lexTop consumes elements at the top level of TOML data. -func lexTop(lx *lexer) stateFn { - r := lx.next() - if isWhitespace(r) || isNL(r) { - return lexSkip(lx, lexTop) - } - - switch r { - case commentStart: - lx.push(lexTop) - return lexCommentStart - case tableStart: - return lexTableStart - case eof: - if lx.pos > lx.start { - return lx.errorf("Unexpected EOF.") - } - lx.emit(itemEOF) - return nil - } - - // At this point, the only valid item can be a key, so we back up - // and let the key lexer do the rest. - lx.backup() - lx.push(lexTopEnd) - return lexKeyStart -} - -// lexTopEnd is entered whenever a top-level item has been consumed. (A value -// or a table.) It must see only whitespace, and will turn back to lexTop -// upon a new line. If it sees EOF, it will quit the lexer successfully. -func lexTopEnd(lx *lexer) stateFn { - r := lx.next() - switch { - case r == commentStart: - // a comment will read to a new line for us. - lx.push(lexTop) - return lexCommentStart - case isWhitespace(r): - return lexTopEnd - case isNL(r): - lx.ignore() - return lexTop - case r == eof: - lx.ignore() - return lexTop - } - return lx.errorf("Expected a top-level item to end with a new line, "+ - "comment or EOF, but got %q instead.", r) -} - -// lexTable lexes the beginning of a table. Namely, it makes sure that -// it starts with a character other than '.' and ']'. -// It assumes that '[' has already been consumed. -// It also handles the case that this is an item in an array of tables. -// e.g., '[[name]]'. -func lexTableStart(lx *lexer) stateFn { - if lx.peek() == arrayTableStart { - lx.next() - lx.emit(itemArrayTableStart) - lx.push(lexArrayTableEnd) - } else { - lx.emit(itemTableStart) - lx.push(lexTableEnd) - } - return lexTableNameStart -} - -func lexTableEnd(lx *lexer) stateFn { - lx.emit(itemTableEnd) - return lexTopEnd -} - -func lexArrayTableEnd(lx *lexer) stateFn { - if r := lx.next(); r != arrayTableEnd { - return lx.errorf("Expected end of table array name delimiter %q, "+ - "but got %q instead.", arrayTableEnd, r) - } - lx.emit(itemArrayTableEnd) - return lexTopEnd -} - -func lexTableNameStart(lx *lexer) stateFn { - switch r := lx.peek(); { - case r == tableEnd || r == eof: - return lx.errorf("Unexpected end of table name. (Table names cannot " + - "be empty.)") - case r == tableSep: - return lx.errorf("Unexpected table separator. (Table names cannot " + - "be empty.)") - case r == stringStart || r == rawStringStart: - lx.ignore() - lx.push(lexTableNameEnd) - return lexValue // reuse string lexing - default: - return lexBareTableName - } -} - -// lexTableName lexes the name of a table. It assumes that at least one -// valid character for the table has already been read. -func lexBareTableName(lx *lexer) stateFn { - switch r := lx.next(); { - case isBareKeyChar(r): - return lexBareTableName - case r == tableSep || r == tableEnd: - lx.backup() - lx.emitTrim(itemText) - return lexTableNameEnd - default: - return lx.errorf("Bare keys cannot contain %q.", r) - } -} - -// lexTableNameEnd reads the end of a piece of a table name, optionally -// consuming whitespace. -func lexTableNameEnd(lx *lexer) stateFn { - switch r := lx.next(); { - case isWhitespace(r): - return lexTableNameEnd - case r == tableSep: - lx.ignore() - return lexTableNameStart - case r == tableEnd: - return lx.pop() - default: - return lx.errorf("Expected '.' or ']' to end table name, but got %q "+ - "instead.", r) - } -} - -// lexKeyStart consumes a key name up until the first non-whitespace character. -// lexKeyStart will ignore whitespace. -func lexKeyStart(lx *lexer) stateFn { - r := lx.peek() - switch { - case r == keySep: - return lx.errorf("Unexpected key separator %q.", keySep) - case isWhitespace(r) || isNL(r): - lx.next() - return lexSkip(lx, lexKeyStart) - case r == stringStart || r == rawStringStart: - lx.ignore() - lx.emit(itemKeyStart) - lx.push(lexKeyEnd) - return lexValue // reuse string lexing - default: - lx.ignore() - lx.emit(itemKeyStart) - return lexBareKey - } -} - -// lexBareKey consumes the text of a bare key. Assumes that the first character -// (which is not whitespace) has not yet been consumed. -func lexBareKey(lx *lexer) stateFn { - switch r := lx.next(); { - case isBareKeyChar(r): - return lexBareKey - case isWhitespace(r): - lx.emitTrim(itemText) - return lexKeyEnd - case r == keySep: - lx.backup() - lx.emitTrim(itemText) - return lexKeyEnd - default: - return lx.errorf("Bare keys cannot contain %q.", r) - } -} - -// lexKeyEnd consumes the end of a key and trims whitespace (up to the key -// separator). -func lexKeyEnd(lx *lexer) stateFn { - switch r := lx.next(); { - case r == keySep: - return lexSkip(lx, lexValue) - case isWhitespace(r): - return lexSkip(lx, lexKeyEnd) - default: - return lx.errorf("Expected key separator %q, but got %q instead.", - keySep, r) - } -} - -// lexValue starts the consumption of a value anywhere a value is expected. -// lexValue will ignore whitespace. -// After a value is lexed, the last state on the next is popped and returned. -func lexValue(lx *lexer) stateFn { - // We allow whitespace to precede a value, but NOT new lines. - // In array syntax, the array states are responsible for ignoring new - // lines. - r := lx.next() - if isWhitespace(r) { - return lexSkip(lx, lexValue) - } - - switch { - case r == arrayStart: - lx.ignore() - lx.emit(itemArray) - return lexArrayValue - case r == stringStart: - if lx.accept(stringStart) { - if lx.accept(stringStart) { - lx.ignore() // Ignore """ - return lexMultilineString - } - lx.backup() - } - lx.ignore() // ignore the '"' - return lexString - case r == rawStringStart: - if lx.accept(rawStringStart) { - if lx.accept(rawStringStart) { - lx.ignore() // Ignore """ - return lexMultilineRawString - } - lx.backup() - } - lx.ignore() // ignore the "'" - return lexRawString - case r == 't': - return lexTrue - case r == 'f': - return lexFalse - case r == '-': - return lexNumberStart - case isDigit(r): - lx.backup() // avoid an extra state and use the same as above - return lexNumberOrDateStart - case r == '.': // special error case, be kind to users - return lx.errorf("Floats must start with a digit, not '.'.") - } - return lx.errorf("Expected value but found %q instead.", r) -} - -// lexArrayValue consumes one value in an array. It assumes that '[' or ',' -// have already been consumed. All whitespace and new lines are ignored. -func lexArrayValue(lx *lexer) stateFn { - r := lx.next() - switch { - case isWhitespace(r) || isNL(r): - return lexSkip(lx, lexArrayValue) - case r == commentStart: - lx.push(lexArrayValue) - return lexCommentStart - case r == arrayValTerm: - return lx.errorf("Unexpected array value terminator %q.", - arrayValTerm) - case r == arrayEnd: - return lexArrayEnd - } - - lx.backup() - lx.push(lexArrayValueEnd) - return lexValue -} - -// lexArrayValueEnd consumes the cruft between values of an array. Namely, -// it ignores whitespace and expects either a ',' or a ']'. -func lexArrayValueEnd(lx *lexer) stateFn { - r := lx.next() - switch { - case isWhitespace(r) || isNL(r): - return lexSkip(lx, lexArrayValueEnd) - case r == commentStart: - lx.push(lexArrayValueEnd) - return lexCommentStart - case r == arrayValTerm: - lx.ignore() - return lexArrayValue // move on to the next value - case r == arrayEnd: - return lexArrayEnd - } - return lx.errorf("Expected an array value terminator %q or an array "+ - "terminator %q, but got %q instead.", arrayValTerm, arrayEnd, r) -} - -// lexArrayEnd finishes the lexing of an array. It assumes that a ']' has -// just been consumed. -func lexArrayEnd(lx *lexer) stateFn { - lx.ignore() - lx.emit(itemArrayEnd) - return lx.pop() -} - -// lexString consumes the inner contents of a string. It assumes that the -// beginning '"' has already been consumed and ignored. -func lexString(lx *lexer) stateFn { - r := lx.next() - switch { - case isNL(r): - return lx.errorf("Strings cannot contain new lines.") - case r == '\\': - lx.push(lexString) - return lexStringEscape - case r == stringEnd: - lx.backup() - lx.emit(itemString) - lx.next() - lx.ignore() - return lx.pop() - } - return lexString -} - -// lexMultilineString consumes the inner contents of a string. It assumes that -// the beginning '"""' has already been consumed and ignored. -func lexMultilineString(lx *lexer) stateFn { - r := lx.next() - switch { - case r == '\\': - return lexMultilineStringEscape - case r == stringEnd: - if lx.accept(stringEnd) { - if lx.accept(stringEnd) { - lx.backup() - lx.backup() - lx.backup() - lx.emit(itemMultilineString) - lx.next() - lx.next() - lx.next() - lx.ignore() - return lx.pop() - } - lx.backup() - } - } - return lexMultilineString -} - -// lexRawString consumes a raw string. Nothing can be escaped in such a string. -// It assumes that the beginning "'" has already been consumed and ignored. -func lexRawString(lx *lexer) stateFn { - r := lx.next() - switch { - case isNL(r): - return lx.errorf("Strings cannot contain new lines.") - case r == rawStringEnd: - lx.backup() - lx.emit(itemRawString) - lx.next() - lx.ignore() - return lx.pop() - } - return lexRawString -} - -// lexMultilineRawString consumes a raw string. Nothing can be escaped in such -// a string. It assumes that the beginning "'" has already been consumed and -// ignored. -func lexMultilineRawString(lx *lexer) stateFn { - r := lx.next() - switch { - case r == rawStringEnd: - if lx.accept(rawStringEnd) { - if lx.accept(rawStringEnd) { - lx.backup() - lx.backup() - lx.backup() - lx.emit(itemRawMultilineString) - lx.next() - lx.next() - lx.next() - lx.ignore() - return lx.pop() - } - lx.backup() - } - } - return lexMultilineRawString -} - -// lexMultilineStringEscape consumes an escaped character. It assumes that the -// preceding '\\' has already been consumed. -func lexMultilineStringEscape(lx *lexer) stateFn { - // Handle the special case first: - if isNL(lx.next()) { - lx.next() - return lexMultilineString - } else { - lx.backup() - lx.push(lexMultilineString) - return lexStringEscape(lx) - } -} - -func lexStringEscape(lx *lexer) stateFn { - r := lx.next() - switch r { - case 'b': - fallthrough - case 't': - fallthrough - case 'n': - fallthrough - case 'f': - fallthrough - case 'r': - fallthrough - case '"': - fallthrough - case '\\': - return lx.pop() - case 'u': - return lexShortUnicodeEscape - case 'U': - return lexLongUnicodeEscape - } - return lx.errorf("Invalid escape character %q. Only the following "+ - "escape characters are allowed: "+ - "\\b, \\t, \\n, \\f, \\r, \\\", \\/, \\\\, "+ - "\\uXXXX and \\UXXXXXXXX.", r) -} - -func lexShortUnicodeEscape(lx *lexer) stateFn { - var r rune - for i := 0; i < 4; i++ { - r = lx.next() - if !isHexadecimal(r) { - return lx.errorf("Expected four hexadecimal digits after '\\u', "+ - "but got '%s' instead.", lx.current()) - } - } - return lx.pop() -} - -func lexLongUnicodeEscape(lx *lexer) stateFn { - var r rune - for i := 0; i < 8; i++ { - r = lx.next() - if !isHexadecimal(r) { - return lx.errorf("Expected eight hexadecimal digits after '\\U', "+ - "but got '%s' instead.", lx.current()) - } - } - return lx.pop() -} - -// lexNumberOrDateStart consumes either a (positive) integer, float or -// datetime. It assumes that NO negative sign has been consumed. -func lexNumberOrDateStart(lx *lexer) stateFn { - r := lx.next() - if !isDigit(r) { - if r == '.' { - return lx.errorf("Floats must start with a digit, not '.'.") - } else { - return lx.errorf("Expected a digit but got %q.", r) - } - } - return lexNumberOrDate -} - -// lexNumberOrDate consumes either a (positive) integer, float or datetime. -func lexNumberOrDate(lx *lexer) stateFn { - r := lx.next() - switch { - case r == '-': - if lx.pos-lx.start != 5 { - return lx.errorf("All ISO8601 dates must be in full Zulu form.") - } - return lexDateAfterYear - case isDigit(r): - return lexNumberOrDate - case r == '.': - return lexFloatStart - } - - lx.backup() - lx.emit(itemInteger) - return lx.pop() -} - -// lexDateAfterYear consumes a full Zulu Datetime in ISO8601 format. -// It assumes that "YYYY-" has already been consumed. -func lexDateAfterYear(lx *lexer) stateFn { - formats := []rune{ - // digits are '0'. - // everything else is direct equality. - '0', '0', '-', '0', '0', - 'T', - '0', '0', ':', '0', '0', ':', '0', '0', - 'Z', - } - for _, f := range formats { - r := lx.next() - if f == '0' { - if !isDigit(r) { - return lx.errorf("Expected digit in ISO8601 datetime, "+ - "but found %q instead.", r) - } - } else if f != r { - return lx.errorf("Expected %q in ISO8601 datetime, "+ - "but found %q instead.", f, r) - } - } - lx.emit(itemDatetime) - return lx.pop() -} - -// lexNumberStart consumes either an integer or a float. It assumes that -// a negative sign has already been read, but that *no* digits have been -// consumed. lexNumberStart will move to the appropriate integer or float -// states. -func lexNumberStart(lx *lexer) stateFn { - // we MUST see a digit. Even floats have to start with a digit. - r := lx.next() - if !isDigit(r) { - if r == '.' { - return lx.errorf("Floats must start with a digit, not '.'.") - } else { - return lx.errorf("Expected a digit but got %q.", r) - } - } - return lexNumber -} - -// lexNumber consumes an integer or a float after seeing the first digit. -func lexNumber(lx *lexer) stateFn { - r := lx.next() - switch { - case isDigit(r): - return lexNumber - case r == '.': - return lexFloatStart - } - - lx.backup() - lx.emit(itemInteger) - return lx.pop() -} - -// lexFloatStart starts the consumption of digits of a float after a '.'. -// Namely, at least one digit is required. -func lexFloatStart(lx *lexer) stateFn { - r := lx.next() - if !isDigit(r) { - return lx.errorf("Floats must have a digit after the '.', but got "+ - "%q instead.", r) - } - return lexFloat -} - -// lexFloat consumes the digits of a float after a '.'. -// Assumes that one digit has been consumed after a '.' already. -func lexFloat(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexFloat - } - - lx.backup() - lx.emit(itemFloat) - return lx.pop() -} - -// lexConst consumes the s[1:] in s. It assumes that s[0] has already been -// consumed. -func lexConst(lx *lexer, s string) stateFn { - for i := range s[1:] { - if r := lx.next(); r != rune(s[i+1]) { - return lx.errorf("Expected %q, but found %q instead.", s[:i+1], - s[:i]+string(r)) - } - } - return nil -} - -// lexTrue consumes the "rue" in "true". It assumes that 't' has already -// been consumed. -func lexTrue(lx *lexer) stateFn { - if fn := lexConst(lx, "true"); fn != nil { - return fn - } - lx.emit(itemBool) - return lx.pop() -} - -// lexFalse consumes the "alse" in "false". It assumes that 'f' has already -// been consumed. -func lexFalse(lx *lexer) stateFn { - if fn := lexConst(lx, "false"); fn != nil { - return fn - } - lx.emit(itemBool) - return lx.pop() -} - -// lexCommentStart begins the lexing of a comment. It will emit -// itemCommentStart and consume no characters, passing control to lexComment. -func lexCommentStart(lx *lexer) stateFn { - lx.ignore() - lx.emit(itemCommentStart) - return lexComment -} - -// lexComment lexes an entire comment. It assumes that '#' has been consumed. -// It will consume *up to* the first new line character, and pass control -// back to the last state on the stack. -func lexComment(lx *lexer) stateFn { - r := lx.peek() - if isNL(r) || r == eof { - lx.emit(itemText) - return lx.pop() - } - lx.next() - return lexComment -} - -// lexSkip ignores all slurped input and moves on to the next state. -func lexSkip(lx *lexer, nextState stateFn) stateFn { - return func(lx *lexer) stateFn { - lx.ignore() - return nextState - } -} - -// isWhitespace returns true if `r` is a whitespace character according -// to the spec. -func isWhitespace(r rune) bool { - return r == '\t' || r == ' ' -} - -func isNL(r rune) bool { - return r == '\n' || r == '\r' -} - -func isDigit(r rune) bool { - return r >= '0' && r <= '9' -} - -func isHexadecimal(r rune) bool { - return (r >= '0' && r <= '9') || - (r >= 'a' && r <= 'f') || - (r >= 'A' && r <= 'F') -} - -func isBareKeyChar(r rune) bool { - return (r >= 'A' && r <= 'Z') || - (r >= 'a' && r <= 'z') || - (r >= '0' && r <= '9') || - r == '_' || - r == '-' -} - -func (itype itemType) String() string { - switch itype { - case itemError: - return "Error" - case itemNIL: - return "NIL" - case itemEOF: - return "EOF" - case itemText: - return "Text" - case itemString: - return "String" - case itemRawString: - return "String" - case itemMultilineString: - return "String" - case itemRawMultilineString: - return "String" - case itemBool: - return "Bool" - case itemInteger: - return "Integer" - case itemFloat: - return "Float" - case itemDatetime: - return "DateTime" - case itemTableStart: - return "TableStart" - case itemTableEnd: - return "TableEnd" - case itemKeyStart: - return "KeyStart" - case itemArray: - return "Array" - case itemArrayEnd: - return "ArrayEnd" - case itemCommentStart: - return "CommentStart" - } - panic(fmt.Sprintf("BUG: Unknown type '%d'.", int(itype))) -} - -func (item item) String() string { - return fmt.Sprintf("(%s, %s)", item.typ.String(), item.val) -} diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/parse.go b/Godeps/_workspace/src/github.com/BurntSushi/toml/parse.go deleted file mode 100644 index c6069be1f..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/parse.go +++ /dev/null @@ -1,498 +0,0 @@ -package toml - -import ( - "fmt" - "log" - "strconv" - "strings" - "time" - "unicode" - "unicode/utf8" -) - -type parser struct { - mapping map[string]interface{} - types map[string]tomlType - lx *lexer - - // A list of keys in the order that they appear in the TOML data. - ordered []Key - - // the full key for the current hash in scope - context Key - - // the base key name for everything except hashes - currentKey string - - // rough approximation of line number - approxLine int - - // A map of 'key.group.names' to whether they were created implicitly. - implicits map[string]bool -} - -type parseError string - -func (pe parseError) Error() string { - return string(pe) -} - -func parse(data string) (p *parser, err error) { - defer func() { - if r := recover(); r != nil { - var ok bool - if err, ok = r.(parseError); ok { - return - } - panic(r) - } - }() - - p = &parser{ - mapping: make(map[string]interface{}), - types: make(map[string]tomlType), - lx: lex(data), - ordered: make([]Key, 0), - implicits: make(map[string]bool), - } - for { - item := p.next() - if item.typ == itemEOF { - break - } - p.topLevel(item) - } - - return p, nil -} - -func (p *parser) panicf(format string, v ...interface{}) { - msg := fmt.Sprintf("Near line %d (last key parsed '%s'): %s", - p.approxLine, p.current(), fmt.Sprintf(format, v...)) - panic(parseError(msg)) -} - -func (p *parser) next() item { - it := p.lx.nextItem() - if it.typ == itemError { - p.panicf("%s", it.val) - } - return it -} - -func (p *parser) bug(format string, v ...interface{}) { - log.Fatalf("BUG: %s\n\n", fmt.Sprintf(format, v...)) -} - -func (p *parser) expect(typ itemType) item { - it := p.next() - p.assertEqual(typ, it.typ) - return it -} - -func (p *parser) assertEqual(expected, got itemType) { - if expected != got { - p.bug("Expected '%s' but got '%s'.", expected, got) - } -} - -func (p *parser) topLevel(item item) { - switch item.typ { - case itemCommentStart: - p.approxLine = item.line - p.expect(itemText) - case itemTableStart: - kg := p.next() - p.approxLine = kg.line - - var key Key - for ; kg.typ != itemTableEnd && kg.typ != itemEOF; kg = p.next() { - key = append(key, p.keyString(kg)) - } - p.assertEqual(itemTableEnd, kg.typ) - - p.establishContext(key, false) - p.setType("", tomlHash) - p.ordered = append(p.ordered, key) - case itemArrayTableStart: - kg := p.next() - p.approxLine = kg.line - - var key Key - for ; kg.typ != itemArrayTableEnd && kg.typ != itemEOF; kg = p.next() { - key = append(key, p.keyString(kg)) - } - p.assertEqual(itemArrayTableEnd, kg.typ) - - p.establishContext(key, true) - p.setType("", tomlArrayHash) - p.ordered = append(p.ordered, key) - case itemKeyStart: - kname := p.next() - p.approxLine = kname.line - p.currentKey = p.keyString(kname) - - val, typ := p.value(p.next()) - p.setValue(p.currentKey, val) - p.setType(p.currentKey, typ) - p.ordered = append(p.ordered, p.context.add(p.currentKey)) - p.currentKey = "" - default: - p.bug("Unexpected type at top level: %s", item.typ) - } -} - -// Gets a string for a key (or part of a key in a table name). -func (p *parser) keyString(it item) string { - switch it.typ { - case itemText: - return it.val - case itemString, itemMultilineString, - itemRawString, itemRawMultilineString: - s, _ := p.value(it) - return s.(string) - default: - p.bug("Unexpected key type: %s", it.typ) - panic("unreachable") - } -} - -// value translates an expected value from the lexer into a Go value wrapped -// as an empty interface. -func (p *parser) value(it item) (interface{}, tomlType) { - switch it.typ { - case itemString: - return p.replaceEscapes(it.val), p.typeOfPrimitive(it) - case itemMultilineString: - trimmed := stripFirstNewline(stripEscapedWhitespace(it.val)) - return p.replaceEscapes(trimmed), p.typeOfPrimitive(it) - case itemRawString: - return it.val, p.typeOfPrimitive(it) - case itemRawMultilineString: - return stripFirstNewline(it.val), p.typeOfPrimitive(it) - case itemBool: - switch it.val { - case "true": - return true, p.typeOfPrimitive(it) - case "false": - return false, p.typeOfPrimitive(it) - } - p.bug("Expected boolean value, but got '%s'.", it.val) - case itemInteger: - num, err := strconv.ParseInt(it.val, 10, 64) - if err != nil { - // See comment below for floats describing why we make a - // distinction between a bug and a user error. - if e, ok := err.(*strconv.NumError); ok && - e.Err == strconv.ErrRange { - - p.panicf("Integer '%s' is out of the range of 64-bit "+ - "signed integers.", it.val) - } else { - p.bug("Expected integer value, but got '%s'.", it.val) - } - } - return num, p.typeOfPrimitive(it) - case itemFloat: - num, err := strconv.ParseFloat(it.val, 64) - if err != nil { - // Distinguish float values. Normally, it'd be a bug if the lexer - // provides an invalid float, but it's possible that the float is - // out of range of valid values (which the lexer cannot determine). - // So mark the former as a bug but the latter as a legitimate user - // error. - // - // This is also true for integers. - if e, ok := err.(*strconv.NumError); ok && - e.Err == strconv.ErrRange { - - p.panicf("Float '%s' is out of the range of 64-bit "+ - "IEEE-754 floating-point numbers.", it.val) - } else { - p.bug("Expected float value, but got '%s'.", it.val) - } - } - return num, p.typeOfPrimitive(it) - case itemDatetime: - t, err := time.Parse("2006-01-02T15:04:05Z", it.val) - if err != nil { - p.bug("Expected Zulu formatted DateTime, but got '%s'.", it.val) - } - return t, p.typeOfPrimitive(it) - case itemArray: - array := make([]interface{}, 0) - types := make([]tomlType, 0) - - for it = p.next(); it.typ != itemArrayEnd; it = p.next() { - if it.typ == itemCommentStart { - p.expect(itemText) - continue - } - - val, typ := p.value(it) - array = append(array, val) - types = append(types, typ) - } - return array, p.typeOfArray(types) - } - p.bug("Unexpected value type: %s", it.typ) - panic("unreachable") -} - -// establishContext sets the current context of the parser, -// where the context is either a hash or an array of hashes. Which one is -// set depends on the value of the `array` parameter. -// -// Establishing the context also makes sure that the key isn't a duplicate, and -// will create implicit hashes automatically. -func (p *parser) establishContext(key Key, array bool) { - var ok bool - - // Always start at the top level and drill down for our context. - hashContext := p.mapping - keyContext := make(Key, 0) - - // We only need implicit hashes for key[0:-1] - for _, k := range key[0 : len(key)-1] { - _, ok = hashContext[k] - keyContext = append(keyContext, k) - - // No key? Make an implicit hash and move on. - if !ok { - p.addImplicit(keyContext) - hashContext[k] = make(map[string]interface{}) - } - - // If the hash context is actually an array of tables, then set - // the hash context to the last element in that array. - // - // Otherwise, it better be a table, since this MUST be a key group (by - // virtue of it not being the last element in a key). - switch t := hashContext[k].(type) { - case []map[string]interface{}: - hashContext = t[len(t)-1] - case map[string]interface{}: - hashContext = t - default: - p.panicf("Key '%s' was already created as a hash.", keyContext) - } - } - - p.context = keyContext - if array { - // If this is the first element for this array, then allocate a new - // list of tables for it. - k := key[len(key)-1] - if _, ok := hashContext[k]; !ok { - hashContext[k] = make([]map[string]interface{}, 0, 5) - } - - // Add a new table. But make sure the key hasn't already been used - // for something else. - if hash, ok := hashContext[k].([]map[string]interface{}); ok { - hashContext[k] = append(hash, make(map[string]interface{})) - } else { - p.panicf("Key '%s' was already created and cannot be used as "+ - "an array.", keyContext) - } - } else { - p.setValue(key[len(key)-1], make(map[string]interface{})) - } - p.context = append(p.context, key[len(key)-1]) -} - -// setValue sets the given key to the given value in the current context. -// It will make sure that the key hasn't already been defined, account for -// implicit key groups. -func (p *parser) setValue(key string, value interface{}) { - var tmpHash interface{} - var ok bool - - hash := p.mapping - keyContext := make(Key, 0) - for _, k := range p.context { - keyContext = append(keyContext, k) - if tmpHash, ok = hash[k]; !ok { - p.bug("Context for key '%s' has not been established.", keyContext) - } - switch t := tmpHash.(type) { - case []map[string]interface{}: - // The context is a table of hashes. Pick the most recent table - // defined as the current hash. - hash = t[len(t)-1] - case map[string]interface{}: - hash = t - default: - p.bug("Expected hash to have type 'map[string]interface{}', but "+ - "it has '%T' instead.", tmpHash) - } - } - keyContext = append(keyContext, key) - - if _, ok := hash[key]; ok { - // Typically, if the given key has already been set, then we have - // to raise an error since duplicate keys are disallowed. However, - // it's possible that a key was previously defined implicitly. In this - // case, it is allowed to be redefined concretely. (See the - // `tests/valid/implicit-and-explicit-after.toml` test in `toml-test`.) - // - // But we have to make sure to stop marking it as an implicit. (So that - // another redefinition provokes an error.) - // - // Note that since it has already been defined (as a hash), we don't - // want to overwrite it. So our business is done. - if p.isImplicit(keyContext) { - p.removeImplicit(keyContext) - return - } - - // Otherwise, we have a concrete key trying to override a previous - // key, which is *always* wrong. - p.panicf("Key '%s' has already been defined.", keyContext) - } - hash[key] = value -} - -// setType sets the type of a particular value at a given key. -// It should be called immediately AFTER setValue. -// -// Note that if `key` is empty, then the type given will be applied to the -// current context (which is either a table or an array of tables). -func (p *parser) setType(key string, typ tomlType) { - keyContext := make(Key, 0, len(p.context)+1) - for _, k := range p.context { - keyContext = append(keyContext, k) - } - if len(key) > 0 { // allow type setting for hashes - keyContext = append(keyContext, key) - } - p.types[keyContext.String()] = typ -} - -// addImplicit sets the given Key as having been created implicitly. -func (p *parser) addImplicit(key Key) { - p.implicits[key.String()] = true -} - -// removeImplicit stops tagging the given key as having been implicitly -// created. -func (p *parser) removeImplicit(key Key) { - p.implicits[key.String()] = false -} - -// isImplicit returns true if the key group pointed to by the key was created -// implicitly. -func (p *parser) isImplicit(key Key) bool { - return p.implicits[key.String()] -} - -// current returns the full key name of the current context. -func (p *parser) current() string { - if len(p.currentKey) == 0 { - return p.context.String() - } - if len(p.context) == 0 { - return p.currentKey - } - return fmt.Sprintf("%s.%s", p.context, p.currentKey) -} - -func stripFirstNewline(s string) string { - if len(s) == 0 || s[0] != '\n' { - return s - } - return s[1:len(s)] -} - -func stripEscapedWhitespace(s string) string { - esc := strings.Split(s, "\\\n") - if len(esc) > 1 { - for i := 1; i < len(esc); i++ { - esc[i] = strings.TrimLeftFunc(esc[i], unicode.IsSpace) - } - } - return strings.Join(esc, "") -} - -func (p *parser) replaceEscapes(str string) string { - var replaced []rune - s := []byte(str) - r := 0 - for r < len(s) { - if s[r] != '\\' { - c, size := utf8.DecodeRune(s[r:]) - r += size - replaced = append(replaced, c) - continue - } - r += 1 - if r >= len(s) { - p.bug("Escape sequence at end of string.") - return "" - } - switch s[r] { - default: - p.bug("Expected valid escape code after \\, but got %q.", s[r]) - return "" - case 'b': - replaced = append(replaced, rune(0x0008)) - r += 1 - case 't': - replaced = append(replaced, rune(0x0009)) - r += 1 - case 'n': - replaced = append(replaced, rune(0x000A)) - r += 1 - case 'f': - replaced = append(replaced, rune(0x000C)) - r += 1 - case 'r': - replaced = append(replaced, rune(0x000D)) - r += 1 - case '"': - replaced = append(replaced, rune(0x0022)) - r += 1 - case '\\': - replaced = append(replaced, rune(0x005C)) - r += 1 - case 'u': - // At this point, we know we have a Unicode escape of the form - // `uXXXX` at [r, r+5). (Because the lexer guarantees this - // for us.) - escaped := p.asciiEscapeToUnicode(s[r+1 : r+5]) - replaced = append(replaced, escaped) - r += 5 - case 'U': - // At this point, we know we have a Unicode escape of the form - // `uXXXX` at [r, r+9). (Because the lexer guarantees this - // for us.) - escaped := p.asciiEscapeToUnicode(s[r+1 : r+9]) - replaced = append(replaced, escaped) - r += 9 - } - } - return string(replaced) -} - -func (p *parser) asciiEscapeToUnicode(bs []byte) rune { - s := string(bs) - hex, err := strconv.ParseUint(strings.ToLower(s), 16, 32) - if err != nil { - p.bug("Could not parse '%s' as a hexadecimal number, but the "+ - "lexer claims it's OK: %s", s, err) - } - - // BUG(burntsushi) - // I honestly don't understand how this works. I can't seem - // to find a way to make this fail. I figured this would fail on invalid - // UTF-8 characters like U+DCFF, but it doesn't. - if !utf8.ValidString(string(rune(hex))) { - p.panicf("Escaped character '\\u%s' is not valid UTF-8.", s) - } - return rune(hex) -} - -func isStringType(ty itemType) bool { - return ty == itemString || ty == itemMultilineString || - ty == itemRawString || ty == itemRawMultilineString -} diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/session.vim b/Godeps/_workspace/src/github.com/BurntSushi/toml/session.vim deleted file mode 100644 index 562164be0..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/session.vim +++ /dev/null @@ -1 +0,0 @@ -au BufWritePost *.go silent!make tags > /dev/null 2>&1 diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/type_check.go b/Godeps/_workspace/src/github.com/BurntSushi/toml/type_check.go deleted file mode 100644 index c73f8afc1..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/type_check.go +++ /dev/null @@ -1,91 +0,0 @@ -package toml - -// tomlType represents any Go type that corresponds to a TOML type. -// While the first draft of the TOML spec has a simplistic type system that -// probably doesn't need this level of sophistication, we seem to be militating -// toward adding real composite types. -type tomlType interface { - typeString() string -} - -// typeEqual accepts any two types and returns true if they are equal. -func typeEqual(t1, t2 tomlType) bool { - if t1 == nil || t2 == nil { - return false - } - return t1.typeString() == t2.typeString() -} - -func typeIsHash(t tomlType) bool { - return typeEqual(t, tomlHash) || typeEqual(t, tomlArrayHash) -} - -type tomlBaseType string - -func (btype tomlBaseType) typeString() string { - return string(btype) -} - -func (btype tomlBaseType) String() string { - return btype.typeString() -} - -var ( - tomlInteger tomlBaseType = "Integer" - tomlFloat tomlBaseType = "Float" - tomlDatetime tomlBaseType = "Datetime" - tomlString tomlBaseType = "String" - tomlBool tomlBaseType = "Bool" - tomlArray tomlBaseType = "Array" - tomlHash tomlBaseType = "Hash" - tomlArrayHash tomlBaseType = "ArrayHash" -) - -// typeOfPrimitive returns a tomlType of any primitive value in TOML. -// Primitive values are: Integer, Float, Datetime, String and Bool. -// -// Passing a lexer item other than the following will cause a BUG message -// to occur: itemString, itemBool, itemInteger, itemFloat, itemDatetime. -func (p *parser) typeOfPrimitive(lexItem item) tomlType { - switch lexItem.typ { - case itemInteger: - return tomlInteger - case itemFloat: - return tomlFloat - case itemDatetime: - return tomlDatetime - case itemString: - return tomlString - case itemMultilineString: - return tomlString - case itemRawString: - return tomlString - case itemRawMultilineString: - return tomlString - case itemBool: - return tomlBool - } - p.bug("Cannot infer primitive type of lex item '%s'.", lexItem) - panic("unreachable") -} - -// typeOfArray returns a tomlType for an array given a list of types of its -// values. -// -// In the current spec, if an array is homogeneous, then its type is always -// "Array". If the array is not homogeneous, an error is generated. -func (p *parser) typeOfArray(types []tomlType) tomlType { - // Empty arrays are cool. - if len(types) == 0 { - return tomlArray - } - - theType := types[0] - for _, t := range types[1:] { - if !typeEqual(theType, t) { - p.panicf("Array contains values of type '%s' and '%s', but "+ - "arrays must be homogeneous.", theType, t) - } - } - return tomlArray -} diff --git a/Godeps/_workspace/src/github.com/BurntSushi/toml/type_fields.go b/Godeps/_workspace/src/github.com/BurntSushi/toml/type_fields.go deleted file mode 100644 index 7592f87a4..000000000 --- a/Godeps/_workspace/src/github.com/BurntSushi/toml/type_fields.go +++ /dev/null @@ -1,241 +0,0 @@ -package toml - -// Struct field handling is adapted from code in encoding/json: -// -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the Go distribution. - -import ( - "reflect" - "sort" - "sync" -) - -// A field represents a single field found in a struct. -type field struct { - name string // the name of the field (`toml` tag included) - tag bool // whether field has a `toml` tag - index []int // represents the depth of an anonymous field - typ reflect.Type // the type of the field -} - -// byName sorts field by name, breaking ties with depth, -// then breaking ties with "name came from toml tag", then -// breaking ties with index sequence. -type byName []field - -func (x byName) Len() int { return len(x) } - -func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byName) Less(i, j int) bool { - if x[i].name != x[j].name { - return x[i].name < x[j].name - } - if len(x[i].index) != len(x[j].index) { - return len(x[i].index) < len(x[j].index) - } - if x[i].tag != x[j].tag { - return x[i].tag - } - return byIndex(x).Less(i, j) -} - -// byIndex sorts field by index sequence. -type byIndex []field - -func (x byIndex) Len() int { return len(x) } - -func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byIndex) Less(i, j int) bool { - for k, xik := range x[i].index { - if k >= len(x[j].index) { - return false - } - if xik != x[j].index[k] { - return xik < x[j].index[k] - } - } - return len(x[i].index) < len(x[j].index) -} - -// typeFields returns a list of fields that TOML should recognize for the given -// type. The algorithm is breadth-first search over the set of structs to -// include - the top struct and then any reachable anonymous structs. -func typeFields(t reflect.Type) []field { - // Anonymous fields to explore at the current level and the next. - current := []field{} - next := []field{{typ: t}} - - // Count of queued names for current level and the next. - count := map[reflect.Type]int{} - nextCount := map[reflect.Type]int{} - - // Types already visited at an earlier level. - visited := map[reflect.Type]bool{} - - // Fields found. - var fields []field - - for len(next) > 0 { - current, next = next, current[:0] - count, nextCount = nextCount, map[reflect.Type]int{} - - for _, f := range current { - if visited[f.typ] { - continue - } - visited[f.typ] = true - - // Scan f.typ for fields to include. - for i := 0; i < f.typ.NumField(); i++ { - sf := f.typ.Field(i) - if sf.PkgPath != "" { // unexported - continue - } - name := sf.Tag.Get("toml") - if name == "-" { - continue - } - index := make([]int, len(f.index)+1) - copy(index, f.index) - index[len(f.index)] = i - - ft := sf.Type - if ft.Name() == "" && ft.Kind() == reflect.Ptr { - // Follow pointer. - ft = ft.Elem() - } - - // Record found field and index sequence. - if name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { - tagged := name != "" - if name == "" { - name = sf.Name - } - fields = append(fields, field{name, tagged, index, ft}) - if count[f.typ] > 1 { - // If there were multiple instances, add a second, - // so that the annihilation code will see a duplicate. - // It only cares about the distinction between 1 or 2, - // so don't bother generating any more copies. - fields = append(fields, fields[len(fields)-1]) - } - continue - } - - // Record new anonymous struct to explore in next round. - nextCount[ft]++ - if nextCount[ft] == 1 { - f := field{name: ft.Name(), index: index, typ: ft} - next = append(next, f) - } - } - } - } - - sort.Sort(byName(fields)) - - // Delete all fields that are hidden by the Go rules for embedded fields, - // except that fields with TOML tags are promoted. - - // The fields are sorted in primary order of name, secondary order - // of field index length. Loop over names; for each name, delete - // hidden fields by choosing the one dominant field that survives. - out := fields[:0] - for advance, i := 0, 0; i < len(fields); i += advance { - // One iteration per name. - // Find the sequence of fields with the name of this first field. - fi := fields[i] - name := fi.name - for advance = 1; i+advance < len(fields); advance++ { - fj := fields[i+advance] - if fj.name != name { - break - } - } - if advance == 1 { // Only one field with this name - out = append(out, fi) - continue - } - dominant, ok := dominantField(fields[i : i+advance]) - if ok { - out = append(out, dominant) - } - } - - fields = out - sort.Sort(byIndex(fields)) - - return fields -} - -// dominantField looks through the fields, all of which are known to -// have the same name, to find the single field that dominates the -// others using Go's embedding rules, modified by the presence of -// TOML tags. If there are multiple top-level fields, the boolean -// will be false: This condition is an error in Go and we skip all -// the fields. -func dominantField(fields []field) (field, bool) { - // The fields are sorted in increasing index-length order. The winner - // must therefore be one with the shortest index length. Drop all - // longer entries, which is easy: just truncate the slice. - length := len(fields[0].index) - tagged := -1 // Index of first tagged field. - for i, f := range fields { - if len(f.index) > length { - fields = fields[:i] - break - } - if f.tag { - if tagged >= 0 { - // Multiple tagged fields at the same level: conflict. - // Return no field. - return field{}, false - } - tagged = i - } - } - if tagged >= 0 { - return fields[tagged], true - } - // All remaining fields have the same length. If there's more than one, - // we have a conflict (two fields named "X" at the same level) and we - // return no field. - if len(fields) > 1 { - return field{}, false - } - return fields[0], true -} - -var fieldCache struct { - sync.RWMutex - m map[reflect.Type][]field -} - -// cachedTypeFields is like typeFields but uses a cache to avoid repeated work. -func cachedTypeFields(t reflect.Type) []field { - fieldCache.RLock() - f := fieldCache.m[t] - fieldCache.RUnlock() - if f != nil { - return f - } - - // Compute fields without lock. - // Might duplicate effort but won't hold other computations back. - f = typeFields(t) - if f == nil { - f = []field{} - } - - fieldCache.Lock() - if fieldCache.m == nil { - fieldCache.m = map[reflect.Type][]field{} - } - fieldCache.m[t] = f - fieldCache.Unlock() - return f -} diff --git a/Godeps/_workspace/src/github.com/bitly/go-simplejson/.travis.yml b/Godeps/_workspace/src/github.com/bitly/go-simplejson/.travis.yml deleted file mode 100644 index 55accb9bf..000000000 --- a/Godeps/_workspace/src/github.com/bitly/go-simplejson/.travis.yml +++ /dev/null @@ -1,10 +0,0 @@ -language: go -go: - - 1.0.3 - - 1.1.2 - - 1.2 - - tip -install: - - go get github.com/bmizerany/assert -notifications: - email: false diff --git a/Godeps/_workspace/src/github.com/bitly/go-simplejson/LICENSE b/Godeps/_workspace/src/github.com/bitly/go-simplejson/LICENSE deleted file mode 100644 index 89de35479..000000000 --- a/Godeps/_workspace/src/github.com/bitly/go-simplejson/LICENSE +++ /dev/null @@ -1,17 +0,0 @@ -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/Godeps/_workspace/src/github.com/bitly/go-simplejson/README.md b/Godeps/_workspace/src/github.com/bitly/go-simplejson/README.md deleted file mode 100644 index 8c6c101a8..000000000 --- a/Godeps/_workspace/src/github.com/bitly/go-simplejson/README.md +++ /dev/null @@ -1,13 +0,0 @@ -### go-simplejson - -a Go package to interact with arbitrary JSON - -[![Build Status](https://secure.travis-ci.org/bitly/go-simplejson.png)](http://travis-ci.org/bitly/go-simplejson) - -### Importing - - import github.com/bitly/go-simplejson - -### Documentation - -Visit the docs on [gopkgdoc](http://godoc.org/github.com/bitly/go-simplejson) diff --git a/Godeps/_workspace/src/github.com/bitly/go-simplejson/simplejson.go b/Godeps/_workspace/src/github.com/bitly/go-simplejson/simplejson.go deleted file mode 100644 index 27ce98616..000000000 --- a/Godeps/_workspace/src/github.com/bitly/go-simplejson/simplejson.go +++ /dev/null @@ -1,446 +0,0 @@ -package simplejson - -import ( - "encoding/json" - "errors" - "log" -) - -// returns the current implementation version -func Version() string { - return "0.5.0" -} - -type Json struct { - data interface{} -} - -// NewJson returns a pointer to a new `Json` object -// after unmarshaling `body` bytes -func NewJson(body []byte) (*Json, error) { - j := new(Json) - err := j.UnmarshalJSON(body) - if err != nil { - return nil, err - } - return j, nil -} - -// New returns a pointer to a new, empty `Json` object -func New() *Json { - return &Json{ - data: make(map[string]interface{}), - } -} - -// Interface returns the underlying data -func (j *Json) Interface() interface{} { - return j.data -} - -// Encode returns its marshaled data as `[]byte` -func (j *Json) Encode() ([]byte, error) { - return j.MarshalJSON() -} - -// EncodePretty returns its marshaled data as `[]byte` with indentation -func (j *Json) EncodePretty() ([]byte, error) { - return json.MarshalIndent(&j.data, "", " ") -} - -// Implements the json.Marshaler interface. -func (j *Json) MarshalJSON() ([]byte, error) { - return json.Marshal(&j.data) -} - -// Set modifies `Json` map by `key` and `value` -// Useful for changing single key/value in a `Json` object easily. -func (j *Json) Set(key string, val interface{}) { - m, err := j.Map() - if err != nil { - return - } - m[key] = val -} - -// SetPath modifies `Json`, recursively checking/creating map keys for the supplied path, -// and then finally writing in the value -func (j *Json) SetPath(branch []string, val interface{}) { - if len(branch) == 0 { - j.data = val - return - } - - // in order to insert our branch, we need map[string]interface{} - if _, ok := (j.data).(map[string]interface{}); !ok { - // have to replace with something suitable - j.data = make(map[string]interface{}) - } - curr := j.data.(map[string]interface{}) - - for i := 0; i < len(branch)-1; i++ { - b := branch[i] - // key exists? - if _, ok := curr[b]; !ok { - n := make(map[string]interface{}) - curr[b] = n - curr = n - continue - } - - // make sure the value is the right sort of thing - if _, ok := curr[b].(map[string]interface{}); !ok { - // have to replace with something suitable - n := make(map[string]interface{}) - curr[b] = n - } - - curr = curr[b].(map[string]interface{}) - } - - // add remaining k/v - curr[branch[len(branch)-1]] = val -} - -// Del modifies `Json` map by deleting `key` if it is present. -func (j *Json) Del(key string) { - m, err := j.Map() - if err != nil { - return - } - delete(m, key) -} - -// Get returns a pointer to a new `Json` object -// for `key` in its `map` representation -// -// useful for chaining operations (to traverse a nested JSON): -// js.Get("top_level").Get("dict").Get("value").Int() -func (j *Json) Get(key string) *Json { - m, err := j.Map() - if err == nil { - if val, ok := m[key]; ok { - return &Json{val} - } - } - return &Json{nil} -} - -// GetPath searches for the item as specified by the branch -// without the need to deep dive using Get()'s. -// -// js.GetPath("top_level", "dict") -func (j *Json) GetPath(branch ...string) *Json { - jin := j - for _, p := range branch { - jin = jin.Get(p) - } - return jin -} - -// GetIndex returns a pointer to a new `Json` object -// for `index` in its `array` representation -// -// this is the analog to Get when accessing elements of -// a json array instead of a json object: -// js.Get("top_level").Get("array").GetIndex(1).Get("key").Int() -func (j *Json) GetIndex(index int) *Json { - a, err := j.Array() - if err == nil { - if len(a) > index { - return &Json{a[index]} - } - } - return &Json{nil} -} - -// CheckGet returns a pointer to a new `Json` object and -// a `bool` identifying success or failure -// -// useful for chained operations when success is important: -// if data, ok := js.Get("top_level").CheckGet("inner"); ok { -// log.Println(data) -// } -func (j *Json) CheckGet(key string) (*Json, bool) { - m, err := j.Map() - if err == nil { - if val, ok := m[key]; ok { - return &Json{val}, true - } - } - return nil, false -} - -// Map type asserts to `map` -func (j *Json) Map() (map[string]interface{}, error) { - if m, ok := (j.data).(map[string]interface{}); ok { - return m, nil - } - return nil, errors.New("type assertion to map[string]interface{} failed") -} - -// Array type asserts to an `array` -func (j *Json) Array() ([]interface{}, error) { - if a, ok := (j.data).([]interface{}); ok { - return a, nil - } - return nil, errors.New("type assertion to []interface{} failed") -} - -// Bool type asserts to `bool` -func (j *Json) Bool() (bool, error) { - if s, ok := (j.data).(bool); ok { - return s, nil - } - return false, errors.New("type assertion to bool failed") -} - -// String type asserts to `string` -func (j *Json) String() (string, error) { - if s, ok := (j.data).(string); ok { - return s, nil - } - return "", errors.New("type assertion to string failed") -} - -// Bytes type asserts to `[]byte` -func (j *Json) Bytes() ([]byte, error) { - if s, ok := (j.data).(string); ok { - return []byte(s), nil - } - return nil, errors.New("type assertion to []byte failed") -} - -// StringArray type asserts to an `array` of `string` -func (j *Json) StringArray() ([]string, error) { - arr, err := j.Array() - if err != nil { - return nil, err - } - retArr := make([]string, 0, len(arr)) - for _, a := range arr { - if a == nil { - retArr = append(retArr, "") - continue - } - s, ok := a.(string) - if !ok { - return nil, err - } - retArr = append(retArr, s) - } - return retArr, nil -} - -// MustArray guarantees the return of a `[]interface{}` (with optional default) -// -// useful when you want to interate over array values in a succinct manner: -// for i, v := range js.Get("results").MustArray() { -// fmt.Println(i, v) -// } -func (j *Json) MustArray(args ...[]interface{}) []interface{} { - var def []interface{} - - switch len(args) { - case 0: - case 1: - def = args[0] - default: - log.Panicf("MustArray() received too many arguments %d", len(args)) - } - - a, err := j.Array() - if err == nil { - return a - } - - return def -} - -// MustMap guarantees the return of a `map[string]interface{}` (with optional default) -// -// useful when you want to interate over map values in a succinct manner: -// for k, v := range js.Get("dictionary").MustMap() { -// fmt.Println(k, v) -// } -func (j *Json) MustMap(args ...map[string]interface{}) map[string]interface{} { - var def map[string]interface{} - - switch len(args) { - case 0: - case 1: - def = args[0] - default: - log.Panicf("MustMap() received too many arguments %d", len(args)) - } - - a, err := j.Map() - if err == nil { - return a - } - - return def -} - -// MustString guarantees the return of a `string` (with optional default) -// -// useful when you explicitly want a `string` in a single value return context: -// myFunc(js.Get("param1").MustString(), js.Get("optional_param").MustString("my_default")) -func (j *Json) MustString(args ...string) string { - var def string - - switch len(args) { - case 0: - case 1: - def = args[0] - default: - log.Panicf("MustString() received too many arguments %d", len(args)) - } - - s, err := j.String() - if err == nil { - return s - } - - return def -} - -// MustStringArray guarantees the return of a `[]string` (with optional default) -// -// useful when you want to interate over array values in a succinct manner: -// for i, s := range js.Get("results").MustStringArray() { -// fmt.Println(i, s) -// } -func (j *Json) MustStringArray(args ...[]string) []string { - var def []string - - switch len(args) { - case 0: - case 1: - def = args[0] - default: - log.Panicf("MustStringArray() received too many arguments %d", len(args)) - } - - a, err := j.StringArray() - if err == nil { - return a - } - - return def -} - -// MustInt guarantees the return of an `int` (with optional default) -// -// useful when you explicitly want an `int` in a single value return context: -// myFunc(js.Get("param1").MustInt(), js.Get("optional_param").MustInt(5150)) -func (j *Json) MustInt(args ...int) int { - var def int - - switch len(args) { - case 0: - case 1: - def = args[0] - default: - log.Panicf("MustInt() received too many arguments %d", len(args)) - } - - i, err := j.Int() - if err == nil { - return i - } - - return def -} - -// MustFloat64 guarantees the return of a `float64` (with optional default) -// -// useful when you explicitly want a `float64` in a single value return context: -// myFunc(js.Get("param1").MustFloat64(), js.Get("optional_param").MustFloat64(5.150)) -func (j *Json) MustFloat64(args ...float64) float64 { - var def float64 - - switch len(args) { - case 0: - case 1: - def = args[0] - default: - log.Panicf("MustFloat64() received too many arguments %d", len(args)) - } - - f, err := j.Float64() - if err == nil { - return f - } - - return def -} - -// MustBool guarantees the return of a `bool` (with optional default) -// -// useful when you explicitly want a `bool` in a single value return context: -// myFunc(js.Get("param1").MustBool(), js.Get("optional_param").MustBool(true)) -func (j *Json) MustBool(args ...bool) bool { - var def bool - - switch len(args) { - case 0: - case 1: - def = args[0] - default: - log.Panicf("MustBool() received too many arguments %d", len(args)) - } - - b, err := j.Bool() - if err == nil { - return b - } - - return def -} - -// MustInt64 guarantees the return of an `int64` (with optional default) -// -// useful when you explicitly want an `int64` in a single value return context: -// myFunc(js.Get("param1").MustInt64(), js.Get("optional_param").MustInt64(5150)) -func (j *Json) MustInt64(args ...int64) int64 { - var def int64 - - switch len(args) { - case 0: - case 1: - def = args[0] - default: - log.Panicf("MustInt64() received too many arguments %d", len(args)) - } - - i, err := j.Int64() - if err == nil { - return i - } - - return def -} - -// MustUInt64 guarantees the return of an `uint64` (with optional default) -// -// useful when you explicitly want an `uint64` in a single value return context: -// myFunc(js.Get("param1").MustUint64(), js.Get("optional_param").MustUint64(5150)) -func (j *Json) MustUint64(args ...uint64) uint64 { - var def uint64 - - switch len(args) { - case 0: - case 1: - def = args[0] - default: - log.Panicf("MustUint64() received too many arguments %d", len(args)) - } - - i, err := j.Uint64() - if err == nil { - return i - } - - return def -} diff --git a/Godeps/_workspace/src/github.com/bitly/go-simplejson/simplejson_go10.go b/Godeps/_workspace/src/github.com/bitly/go-simplejson/simplejson_go10.go deleted file mode 100644 index c9151e9be..000000000 --- a/Godeps/_workspace/src/github.com/bitly/go-simplejson/simplejson_go10.go +++ /dev/null @@ -1,75 +0,0 @@ -// +build !go1.1 - -package simplejson - -import ( - "encoding/json" - "errors" - "io" - "reflect" -) - -// NewFromReader returns a *Json by decoding from an io.Reader -func NewFromReader(r io.Reader) (*Json, error) { - j := new(Json) - dec := json.NewDecoder(r) - err := dec.Decode(&j.data) - return j, err -} - -// Implements the json.Unmarshaler interface. -func (j *Json) UnmarshalJSON(p []byte) error { - return json.Unmarshal(p, &j.data) -} - -// Float64 coerces into a float64 -func (j *Json) Float64() (float64, error) { - switch j.data.(type) { - case float32, float64: - return reflect.ValueOf(j.data).Float(), nil - case int, int8, int16, int32, int64: - return float64(reflect.ValueOf(j.data).Int()), nil - case uint, uint8, uint16, uint32, uint64: - return float64(reflect.ValueOf(j.data).Uint()), nil - } - return 0, errors.New("invalid value type") -} - -// Int coerces into an int -func (j *Json) Int() (int, error) { - switch j.data.(type) { - case float32, float64: - return int(reflect.ValueOf(j.data).Float()), nil - case int, int8, int16, int32, int64: - return int(reflect.ValueOf(j.data).Int()), nil - case uint, uint8, uint16, uint32, uint64: - return int(reflect.ValueOf(j.data).Uint()), nil - } - return 0, errors.New("invalid value type") -} - -// Int64 coerces into an int64 -func (j *Json) Int64() (int64, error) { - switch j.data.(type) { - case float32, float64: - return int64(reflect.ValueOf(j.data).Float()), nil - case int, int8, int16, int32, int64: - return reflect.ValueOf(j.data).Int(), nil - case uint, uint8, uint16, uint32, uint64: - return int64(reflect.ValueOf(j.data).Uint()), nil - } - return 0, errors.New("invalid value type") -} - -// Uint64 coerces into an uint64 -func (j *Json) Uint64() (uint64, error) { - switch j.data.(type) { - case float32, float64: - return uint64(reflect.ValueOf(j.data).Float()), nil - case int, int8, int16, int32, int64: - return uint64(reflect.ValueOf(j.data).Int()), nil - case uint, uint8, uint16, uint32, uint64: - return reflect.ValueOf(j.data).Uint(), nil - } - return 0, errors.New("invalid value type") -} diff --git a/Godeps/_workspace/src/github.com/bitly/go-simplejson/simplejson_go11.go b/Godeps/_workspace/src/github.com/bitly/go-simplejson/simplejson_go11.go deleted file mode 100644 index 1c479532c..000000000 --- a/Godeps/_workspace/src/github.com/bitly/go-simplejson/simplejson_go11.go +++ /dev/null @@ -1,89 +0,0 @@ -// +build go1.1 - -package simplejson - -import ( - "bytes" - "encoding/json" - "errors" - "io" - "reflect" - "strconv" -) - -// Implements the json.Unmarshaler interface. -func (j *Json) UnmarshalJSON(p []byte) error { - dec := json.NewDecoder(bytes.NewBuffer(p)) - dec.UseNumber() - return dec.Decode(&j.data) -} - -// NewFromReader returns a *Json by decoding from an io.Reader -func NewFromReader(r io.Reader) (*Json, error) { - j := new(Json) - dec := json.NewDecoder(r) - dec.UseNumber() - err := dec.Decode(&j.data) - return j, err -} - -// Float64 coerces into a float64 -func (j *Json) Float64() (float64, error) { - switch j.data.(type) { - case json.Number: - return j.data.(json.Number).Float64() - case float32, float64: - return reflect.ValueOf(j.data).Float(), nil - case int, int8, int16, int32, int64: - return float64(reflect.ValueOf(j.data).Int()), nil - case uint, uint8, uint16, uint32, uint64: - return float64(reflect.ValueOf(j.data).Uint()), nil - } - return 0, errors.New("invalid value type") -} - -// Int coerces into an int -func (j *Json) Int() (int, error) { - switch j.data.(type) { - case json.Number: - i, err := j.data.(json.Number).Int64() - return int(i), err - case float32, float64: - return int(reflect.ValueOf(j.data).Float()), nil - case int, int8, int16, int32, int64: - return int(reflect.ValueOf(j.data).Int()), nil - case uint, uint8, uint16, uint32, uint64: - return int(reflect.ValueOf(j.data).Uint()), nil - } - return 0, errors.New("invalid value type") -} - -// Int64 coerces into an int64 -func (j *Json) Int64() (int64, error) { - switch j.data.(type) { - case json.Number: - return j.data.(json.Number).Int64() - case float32, float64: - return int64(reflect.ValueOf(j.data).Float()), nil - case int, int8, int16, int32, int64: - return reflect.ValueOf(j.data).Int(), nil - case uint, uint8, uint16, uint32, uint64: - return int64(reflect.ValueOf(j.data).Uint()), nil - } - return 0, errors.New("invalid value type") -} - -// Uint64 coerces into an uint64 -func (j *Json) Uint64() (uint64, error) { - switch j.data.(type) { - case json.Number: - return strconv.ParseUint(j.data.(json.Number).String(), 10, 64) - case float32, float64: - return uint64(reflect.ValueOf(j.data).Float()), nil - case int, int8, int16, int32, int64: - return uint64(reflect.ValueOf(j.data).Int()), nil - case uint, uint8, uint16, uint32, uint64: - return reflect.ValueOf(j.data).Uint(), nil - } - return 0, errors.New("invalid value type") -} diff --git a/Godeps/_workspace/src/github.com/bmizerany/assert/.gitignore b/Godeps/_workspace/src/github.com/bmizerany/assert/.gitignore deleted file mode 100644 index b6fadf4eb..000000000 --- a/Godeps/_workspace/src/github.com/bmizerany/assert/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -_go_.* -_gotest_.* -_obj -_test -_testmain.go -*.out -*.[568] diff --git a/Godeps/_workspace/src/github.com/bmizerany/assert/README.md b/Godeps/_workspace/src/github.com/bmizerany/assert/README.md deleted file mode 100644 index 8b6b6fc4f..000000000 --- a/Godeps/_workspace/src/github.com/bmizerany/assert/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# Assert (c) Blake Mizerany and Keith Rarick -- MIT LICENCE - -## Assertions for Go tests - -## Install - - $ go get github.com/bmizerany/assert - -## Use - -**point.go** - - package point - - type Point struct { - x, y int - } - -**point_test.go** - - - package point - - import ( - "testing" - "github.com/bmizerany/assert" - ) - - func TestAsserts(t *testing.T) { - p1 := Point{1, 1} - p2 := Point{2, 1} - - assert.Equal(t, p1, p2) - } - -**output** - $ go test - --- FAIL: TestAsserts (0.00 seconds) - assert.go:15: /Users/flavio.barbosa/dev/stewie/src/point_test.go:12 - assert.go:24: ! X: 1 != 2 - FAIL - -## Docs - - http://github.com/bmizerany/assert diff --git a/Godeps/_workspace/src/github.com/bmizerany/assert/assert.go b/Godeps/_workspace/src/github.com/bmizerany/assert/assert.go deleted file mode 100644 index 7409f985e..000000000 --- a/Godeps/_workspace/src/github.com/bmizerany/assert/assert.go +++ /dev/null @@ -1,76 +0,0 @@ -package assert -// Testing helpers for doozer. - -import ( - "github.com/kr/pretty" - "reflect" - "testing" - "runtime" - "fmt" -) - -func assert(t *testing.T, result bool, f func(), cd int) { - if !result { - _, file, line, _ := runtime.Caller(cd + 1) - t.Errorf("%s:%d", file, line) - f() - t.FailNow() - } -} - -func equal(t *testing.T, exp, got interface{}, cd int, args ...interface{}) { - fn := func() { - for _, desc := range pretty.Diff(exp, got) { - t.Error("!", desc) - } - if len(args) > 0 { - t.Error("!", " -", fmt.Sprint(args...)) - } - } - result := reflect.DeepEqual(exp, got) - assert(t, result, fn, cd+1) -} - -func tt(t *testing.T, result bool, cd int, args ...interface{}) { - fn := func() { - t.Errorf("! Failure") - if len(args) > 0 { - t.Error("!", " -", fmt.Sprint(args...)) - } - } - assert(t, result, fn, cd+1) -} - -func T(t *testing.T, result bool, args ...interface{}) { - tt(t, result, 1, args...) -} - -func Tf(t *testing.T, result bool, format string, args ...interface{}) { - tt(t, result, 1, fmt.Sprintf(format, args...)) -} - -func Equal(t *testing.T, exp, got interface{}, args ...interface{}) { - equal(t, exp, got, 1, args...) -} - -func Equalf(t *testing.T, exp, got interface{}, format string, args ...interface{}) { - equal(t, exp, got, 1, fmt.Sprintf(format, args...)) -} - -func NotEqual(t *testing.T, exp, got interface{}, args ...interface{}) { - fn := func() { - t.Errorf("! Unexpected: <%#v>", exp) - if len(args) > 0 { - t.Error("!", " -", fmt.Sprint(args...)) - } - } - result := !reflect.DeepEqual(exp, got) - assert(t, result, fn, 1) -} - -func Panic(t *testing.T, err interface{}, fn func()) { - defer func() { - equal(t, err, recover(), 3) - }() - fn() -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/LICENSE b/Godeps/_workspace/src/github.com/golang/protobuf/LICENSE deleted file mode 100644 index 1b1b1921e..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/LICENSE +++ /dev/null @@ -1,31 +0,0 @@ -Go support for Protocol Buffers - Google's data interchange format - -Copyright 2010 The Go Authors. All rights reserved. -https://github.com/golang/protobuf - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile b/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile deleted file mode 100644 index e2e0651a9..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile +++ /dev/null @@ -1,43 +0,0 @@ -# Go support for Protocol Buffers - Google's data interchange format -# -# Copyright 2010 The Go Authors. All rights reserved. -# https://github.com/golang/protobuf -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# * Redistributions in binary form must reproduce the above -# copyright notice, this list of conditions and the following disclaimer -# in the documentation and/or other materials provided with the -# distribution. -# * Neither the name of Google Inc. nor the names of its -# contributors may be used to endorse or promote products derived from -# this software without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -install: - go install - -test: install generate-test-pbs - go test - - -generate-test-pbs: - make install - make -C testdata - 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/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go deleted file mode 100644 index e98ddec98..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go +++ /dev/null @@ -1,223 +0,0 @@ -// 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. - -// Protocol buffer deep copy and merge. -// TODO: RawMessage. - -package proto - -import ( - "log" - "reflect" - "strings" -) - -// Clone returns a deep copy of a protocol buffer. -func Clone(pb Message) Message { - in := reflect.ValueOf(pb) - if in.IsNil() { - return pb - } - - out := reflect.New(in.Type().Elem()) - // out is empty so a merge is a deep copy. - mergeStruct(out.Elem(), in.Elem()) - return out.Interface().(Message) -} - -// Merge merges src into dst. -// Required and optional fields that are set in src will be set to that value in dst. -// Elements of repeated fields will be appended. -// Merge panics if src and dst are not the same type, or if dst is nil. -func Merge(dst, src Message) { - in := reflect.ValueOf(src) - out := reflect.ValueOf(dst) - if out.IsNil() { - panic("proto: nil destination") - } - if in.Type() != out.Type() { - // Explicit test prior to mergeStruct so that mistyped nils will fail - panic("proto: type mismatch") - } - if in.IsNil() { - // Merging nil into non-nil is a quiet no-op - return - } - mergeStruct(out.Elem(), in.Elem()) -} - -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), false, sprop.Prop[i]) - } - - if emIn, ok := in.Addr().Interface().(extendableProto); ok { - emOut := out.Addr().Interface().(extendableProto) - mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap()) - } - - uf := in.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return - } - uin := uf.Bytes() - if len(uin) > 0 { - out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...)) - } -} - -// 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() { - out.Set(reflect.ValueOf(Clone(in.Interface().(Message)))) - } else { - Merge(out.Interface().(Message), in.Interface().(Message)) - } - } - return - } - 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 - } - if out.IsNil() { - out.Set(reflect.MakeMap(in.Type())) - } - // For maps with value types of *T or []byte we need to deep copy each value. - elemKind := in.Type().Elem().Kind() - for _, key := range in.MapKeys() { - var val reflect.Value - switch elemKind { - case reflect.Ptr: - val = reflect.New(in.Type().Elem().Elem()) - mergeAny(val, in.MapIndex(key), false, nil) - case reflect.Slice: - val = in.MapIndex(key) - val = reflect.ValueOf(append([]byte{}, val.Bytes()...)) - default: - val = in.MapIndex(key) - } - out.SetMapIndex(key, val) - } - case reflect.Ptr: - if in.IsNil() { - return - } - if out.IsNil() { - out.Set(reflect.New(in.Elem().Type())) - } - 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. - out.SetBytes(append([]byte{}, in.Bytes()...)) - return - } - n := in.Len() - if out.IsNil() { - out.Set(reflect.MakeSlice(in.Type(), 0, n)) - } - switch in.Type().Elem().Kind() { - case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64, - reflect.String, reflect.Uint32, reflect.Uint64: - out.Set(reflect.AppendSlice(out, in)) - default: - for i := 0; i < n; i++ { - x := reflect.Indirect(reflect.New(in.Type().Elem())) - mergeAny(x, in.Index(i), false, nil) - out.Set(reflect.Append(out, x)) - } - } - case reflect.Struct: - mergeStruct(out, in) - default: - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to copy %v", in) - } -} - -func mergeExtension(out, in map[int32]Extension) { - for extNum, eIn := range in { - eOut := Extension{desc: eIn.desc} - if eIn.value != nil { - v := reflect.New(reflect.TypeOf(eIn.value)).Elem() - mergeAny(v, reflect.ValueOf(eIn.value), false, nil) - eOut.value = v.Interface() - } - if eIn.enc != nil { - eOut.enc = make([]byte, len(eIn.enc)) - copy(eOut.enc, eIn.enc) - } - - out[extNum] = eOut - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go deleted file mode 100644 index f94b9f416..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go +++ /dev/null @@ -1,868 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for decoding protocol buffer data to construct in-memory representations. - */ - -import ( - "errors" - "fmt" - "io" - "os" - "reflect" -) - -// 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. - -// DecodeVarint reads a varint-encoded integer from the slice. -// It returns the integer and the number of bytes consumed, or -// zero if there is not enough. -// This is the format for the -// 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 - } - b := uint64(buf[n]) - n++ - x |= (b & 0x7F) << shift - if (b & 0x80) == 0 { - return x, n - } - } - - // The number is too large to represent in a 64-bit value. - 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 - - i := p.index - l := len(p.buf) - - for shift := uint(0); shift < 64; shift += 7 { - if i >= l { - err = io.ErrUnexpectedEOF - return - } - b := p.buf[i] - i++ - x |= (uint64(b) & 0x7F) << shift - if b < 0x80 { - p.index = i - return - } - } - - // The number is too large to represent in a 64-bit value. - err = errOverflow - return -} - -// DecodeFixed64 reads a 64-bit integer from the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) DecodeFixed64() (x uint64, err error) { - // x, err already 0 - i := p.index + 8 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-8]) - x |= uint64(p.buf[i-7]) << 8 - x |= uint64(p.buf[i-6]) << 16 - x |= uint64(p.buf[i-5]) << 24 - x |= uint64(p.buf[i-4]) << 32 - x |= uint64(p.buf[i-3]) << 40 - x |= uint64(p.buf[i-2]) << 48 - x |= uint64(p.buf[i-1]) << 56 - return -} - -// DecodeFixed32 reads a 32-bit integer from the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) DecodeFixed32() (x uint64, err error) { - // x, err already 0 - i := p.index + 4 - if i < 0 || i > len(p.buf) { - err = io.ErrUnexpectedEOF - return - } - p.index = i - - x = uint64(p.buf[i-4]) - x |= uint64(p.buf[i-3]) << 8 - x |= uint64(p.buf[i-2]) << 16 - x |= uint64(p.buf[i-1]) << 24 - return -} - -// DecodeZigzag64 reads a zigzag-encoded 64-bit integer -// from the Buffer. -// This is the format used for the sint64 protocol buffer type. -func (p *Buffer) DecodeZigzag64() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63) - return -} - -// DecodeZigzag32 reads a zigzag-encoded 32-bit integer -// from the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) DecodeZigzag32() (x uint64, err error) { - x, err = p.DecodeVarint() - if err != nil { - return - } - x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31)) - return -} - -// These are not ValueDecoders: they produce an array of bytes or a string. -// bytes, embedded messages - -// DecodeRawBytes reads a count-delimited byte buffer from the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) { - n, err := p.DecodeVarint() - if err != nil { - return nil, err - } - - nb := int(n) - if nb < 0 { - return nil, fmt.Errorf("proto: bad byte length %d", nb) - } - end := p.index + nb - if end < p.index || end > len(p.buf) { - return nil, io.ErrUnexpectedEOF - } - - if !alloc { - // todo: check if can get more uses of alloc=false - buf = p.buf[p.index:end] - p.index += nb - return - } - - buf = make([]byte, nb) - copy(buf, p.buf[p.index:]) - p.index += nb - return -} - -// DecodeStringBytes reads an encoded string from the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) DecodeStringBytes() (s string, err error) { - buf, err := p.DecodeRawBytes(false) - if err != nil { - return - } - return string(buf), nil -} - -// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. -// If the protocol buffer has extensions, and the field matches, add it as an extension. -// Otherwise, if the XXX_unrecognized field exists, append the skipped data there. -func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error { - oi := o.index - - err := o.skip(t, tag, wire) - if err != nil { - return err - } - - if !unrecField.IsValid() { - return nil - } - - ptr := structPointer_Bytes(base, unrecField) - - // Add the skipped field to struct field - obuf := o.buf - - o.buf = *ptr - o.EncodeVarint(uint64(tag<<3 | wire)) - *ptr = append(o.buf, obuf[oi:o.index]...) - - o.buf = obuf - - return nil -} - -// Skip the next item in the buffer. Its wire type is decoded and presented as an argument. -func (o *Buffer) skip(t reflect.Type, tag, wire int) error { - - var u uint64 - var err error - - switch wire { - case WireVarint: - _, err = o.DecodeVarint() - case WireFixed64: - _, err = o.DecodeFixed64() - case WireBytes: - _, err = o.DecodeRawBytes(false) - case WireFixed32: - _, err = o.DecodeFixed32() - case WireStartGroup: - for { - u, err = o.DecodeVarint() - if err != nil { - break - } - fwire := int(u & 0x7) - if fwire == WireEndGroup { - break - } - ftag := int(u >> 3) - err = o.skip(t, ftag, fwire) - if err != nil { - break - } - } - default: - err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t) - } - return err -} - -// Unmarshaler is the interface representing objects that can -// unmarshal themselves. The method should reset the receiver before -// decoding starts. The argument points to data that may be -// overwritten, so implementations should not keep references to the -// buffer. -type Unmarshaler interface { - Unmarshal([]byte) error -} - -// Unmarshal parses the protocol buffer representation in buf and places the -// decoded result in pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// Unmarshal resets pb before starting to unmarshal, so any -// existing data in pb is always removed. Use UnmarshalMerge -// to preserve and append to existing data. -func Unmarshal(buf []byte, pb Message) error { - pb.Reset() - return UnmarshalMerge(buf, pb) -} - -// UnmarshalMerge parses the protocol buffer representation in buf and -// writes the decoded result to pb. If the struct underlying pb does not match -// the data in buf, the results can be unpredictable. -// -// UnmarshalMerge merges into existing data in pb. -// Most code should use Unmarshal instead. -func UnmarshalMerge(buf []byte, pb Message) error { - // If the object can unmarshal itself, let it. - if u, ok := pb.(Unmarshaler); ok { - return u.Unmarshal(buf) - } - 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. -func (p *Buffer) Unmarshal(pb Message) error { - // If the object can unmarshal itself, let it. - if u, ok := pb.(Unmarshaler); ok { - err := u.Unmarshal(p.buf[p.index:]) - p.index = len(p.buf) - return err - } - - typ, base, err := getbase(pb) - if err != nil { - return err - } - - err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base) - - if collectStats { - stats.Decode++ - } - - return err -} - -// unmarshalType does the work of unmarshaling a structure. -func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error { - var state errorState - required, reqFields := prop.reqCount, uint64(0) - - var err error - for err == nil && o.index < len(o.buf) { - oi := o.index - var u uint64 - u, err = o.DecodeVarint() - if err != nil { - break - } - wire := int(u & 0x7) - if wire == WireEndGroup { - if is_group { - return nil // input is satisfied - } - return fmt.Errorf("proto: %s: wiretype end group for non-group", st) - } - tag := int(u >> 3) - if tag <= 0 { - return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire) - } - fieldnum, ok := prop.decoderTags.get(tag) - if !ok { - // Maybe it's an extension? - if prop.extendable { - if e := structPointer_Interface(base, st).(extendableProto); isExtensionField(e, int32(tag)) { - if err = o.skip(st, tag, wire); err == nil { - ext := e.ExtensionMap()[int32(tag)] // may be missing - ext.enc = append(ext.enc, o.buf[oi:o.index]...) - e.ExtensionMap()[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 - } - p := prop.Prop[fieldnum] - - if p.dec == nil { - fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name) - continue - } - dec := p.dec - if wire != WireStartGroup && wire != p.WireType { - if wire == WireBytes && p.packedDec != nil { - // a packable field - dec = p.packedDec - } else { - err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType) - continue - } - } - decErr := dec(o, p, base) - if decErr != nil && !state.shouldContinue(decErr, p) { - err = decErr - } - if err == nil && p.Required { - // Successfully decoded a required field. - if tag <= 64 { - // use bitmap for fields 1-64 to catch field reuse. - var mask uint64 = 1 << uint64(tag-1) - if reqFields&mask == 0 { - // new required field - reqFields |= mask - required-- - } - } else { - // This is imprecise. It can be fooled by a required field - // with a tag > 64 that is encoded twice; that's very rare. - // A fully correct implementation would require allocating - // a data structure, which we would like to avoid. - required-- - } - } - } - if err == nil { - if is_group { - return io.ErrUnexpectedEOF - } - if state.err != nil { - return state.err - } - if required > 0 { - // Not enough information to determine the exact field. If we use extra - // CPU, we could determine the field only if the missing required field - // has a tag <= 64 and we check reqFields. - return &RequiredNotSetError{"{Unknown}"} - } - } - return err -} - -// Individual type decoders -// For each, -// u is the decoded value, -// v is a pointer to the field (pointer) in the struct - -// Sizes of the pools to allocate inside the Buffer. -// The goal is modest amortization and allocation -// on at least 16-byte boundaries. -const ( - boolPoolSize = 16 - uint32PoolSize = 8 - uint64PoolSize = 4 -) - -// Decode a bool. -func (o *Buffer) dec_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - if len(o.bools) == 0 { - o.bools = make([]bool, boolPoolSize) - } - o.bools[0] = u != 0 - *structPointer_Bool(base, p.field) = &o.bools[0] - o.bools = o.bools[1:] - return nil -} - -func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - *structPointer_BoolVal(base, p.field) = u != 0 - return nil -} - -// Decode an int32. -func (o *Buffer) dec_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word32_Set(structPointer_Word32(base, p.field), o, uint32(u)) - return nil -} - -func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u)) - return nil -} - -// Decode an int64. -func (o *Buffer) dec_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word64_Set(structPointer_Word64(base, p.field), o, u) - return nil -} - -func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - word64Val_Set(structPointer_Word64Val(base, p.field), o, u) - return nil -} - -// Decode a string. -func (o *Buffer) dec_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - *structPointer_String(base, p.field) = &s - return nil -} - -func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - *structPointer_StringVal(base, p.field) = s - return nil -} - -// Decode a slice of bytes ([]byte). -func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error { - b, err := o.DecodeRawBytes(true) - if err != nil { - return err - } - *structPointer_Bytes(base, p.field) = b - return nil -} - -// Decode a slice of bools ([]bool). -func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - v := structPointer_BoolSlice(base, p.field) - *v = append(*v, u != 0) - return nil -} - -// Decode a slice of bools ([]bool) in packed format. -func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error { - v := structPointer_BoolSlice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded bools - fin := o.index + nb - if fin < o.index { - return errOverflow - } - - y := *v - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - y = append(y, u != 0) - } - - *v = y - return nil -} - -// Decode a slice of int32s ([]int32). -func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - structPointer_Word32Slice(base, p.field).Append(uint32(u)) - return nil -} - -// Decode a slice of int32s ([]int32) in packed format. -func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error { - v := structPointer_Word32Slice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded int32s - - fin := o.index + nb - if fin < o.index { - return errOverflow - } - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - v.Append(uint32(u)) - } - return nil -} - -// Decode a slice of int64s ([]int64). -func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error { - u, err := p.valDec(o) - if err != nil { - return err - } - - structPointer_Word64Slice(base, p.field).Append(u) - return nil -} - -// Decode a slice of int64s ([]int64) in packed format. -func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error { - v := structPointer_Word64Slice(base, p.field) - - nn, err := o.DecodeVarint() - if err != nil { - return err - } - nb := int(nn) // number of bytes of encoded int64s - - fin := o.index + nb - if fin < o.index { - return errOverflow - } - for o.index < fin { - u, err := p.valDec(o) - if err != nil { - return err - } - v.Append(u) - } - return nil -} - -// Decode a slice of strings ([]string). -func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error { - s, err := o.DecodeStringBytes() - if err != nil { - return err - } - v := structPointer_StringSlice(base, p.field) - *v = append(*v, s) - return nil -} - -// Decode a slice of slice of bytes ([][]byte). -func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error { - b, err := o.DecodeRawBytes(true) - if err != nil { - return err - } - v := structPointer_BytesSlice(base, p.field) - *v = append(*v, b) - return nil -} - -// Decode a map field. -func (o *Buffer) dec_new_map(p *Properties, base structPointer) error { - raw, err := o.DecodeRawBytes(false) - if err != nil { - return err - } - 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_NewAt(base, p.field, p.mtype) // *map[K]V - if mptr.Elem().IsNil() { - mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem())) - } - v := mptr.Elem() // map[K]V - - // Prepare addressable doubly-indirect placeholders for the key and value types. - // See enc_new_map for why. - keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K - keybase := toStructPointer(keyptr.Addr()) // **K - - var valbase structPointer - var valptr reflect.Value - switch p.mtype.Elem().Kind() { - case reflect.Slice: - // []byte - var dummy []byte - valptr = reflect.ValueOf(&dummy) // *[]byte - valbase = toStructPointer(valptr) // *[]byte - case reflect.Ptr: - // message; valptr is **Msg; need to allocate the intermediate pointer - valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V - valptr.Set(reflect.New(valptr.Type().Elem())) - valbase = toStructPointer(valptr) - default: - // everything else - valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V - valbase = toStructPointer(valptr.Addr()) // **V - } - - // Decode. - // This parses a restricted wire format, namely the encoding of a message - // with two fields. See enc_new_map for the format. - for o.index < oi { - // tagcode for key and value properties are always a single byte - // because they have tags 1 and 2. - tagcode := o.buf[o.index] - o.index++ - switch tagcode { - case p.mkeyprop.tagcode[0]: - if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil { - return err - } - case p.mvalprop.tagcode[0]: - if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil { - return err - } - default: - // TODO: Should we silently skip this instead? - return fmt.Errorf("proto: bad map data tag %d", raw[0]) - } - } - keyelem, valelem := keyptr.Elem(), valptr.Elem() - if !keyelem.IsValid() { - keyelem = reflect.Zero(p.mtype.Key()) - } - if !valelem.IsValid() { - valelem = reflect.Zero(p.mtype.Elem()) - } - - v.SetMapIndex(keyelem, valelem) - return nil -} - -// Decode a group. -func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error { - bas := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(bas) { - // allocate new nested message - bas = toStructPointer(reflect.New(p.stype)) - structPointer_SetStructPointer(base, p.field, bas) - } - return o.unmarshalType(p.stype, p.sprop, true, bas) -} - -// Decode an embedded message. -func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) { - raw, e := o.DecodeRawBytes(false) - if e != nil { - return e - } - - bas := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(bas) { - // allocate new nested message - bas = toStructPointer(reflect.New(p.stype)) - structPointer_SetStructPointer(base, p.field, bas) - } - - // If the object can unmarshal itself, let it. - if p.isUnmarshaler { - iv := structPointer_Interface(bas, p.stype) - return iv.(Unmarshaler).Unmarshal(raw) - } - - obuf := o.buf - oi := o.index - o.buf = raw - o.index = 0 - - err = o.unmarshalType(p.stype, p.sprop, false, bas) - o.buf = obuf - o.index = oi - - return err -} - -// Decode a slice of embedded messages. -func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error { - return o.dec_slice_struct(p, false, base) -} - -// Decode a slice of embedded groups. -func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error { - return o.dec_slice_struct(p, true, base) -} - -// Decode a slice of structs ([]*struct). -func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error { - v := reflect.New(p.stype) - bas := toStructPointer(v) - structPointer_StructPointerSlice(base, p.field).Append(bas) - - if is_group { - err := o.unmarshalType(p.stype, p.sprop, is_group, bas) - return err - } - - raw, err := o.DecodeRawBytes(false) - if err != nil { - return err - } - - // If the object can unmarshal itself, let it. - if p.isUnmarshaler { - iv := v.Interface() - return iv.(Unmarshaler).Unmarshal(raw) - } - - obuf := o.buf - oi := o.index - o.buf = raw - o.index = 0 - - err = o.unmarshalType(p.stype, p.sprop, is_group, bas) - - o.buf = obuf - o.index = oi - - return err -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go deleted file mode 100644 index eb7e0474e..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go +++ /dev/null @@ -1,1331 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "errors" - "fmt" - "reflect" - "sort" -) - -// RequiredNotSetError is the error returned if Marshal is called with -// a protocol buffer struct whose required fields have not -// all been initialized. It is also the error returned if Unmarshal is -// called with an encoded protocol buffer that does not include all the -// required fields. -// -// When printed, RequiredNotSetError reports the first unset required field in a -// message. If the field cannot be precisely determined, it is reported as -// "{Unknown}". -type RequiredNotSetError struct { - field string -} - -func (e *RequiredNotSetError) Error() string { - return fmt.Sprintf("proto: required field %q not set", e.field) -} - -var ( - // errRepeatedHasNil is the error returned if Marshal is called with - // a struct with a repeated field containing a nil element. - errRepeatedHasNil = errors.New("proto: repeated field has nil element") - - // errOneofHasNil is the error returned if Marshal is called with - // a struct with a oneof field containing a nil element. - errOneofHasNil = errors.New("proto: oneof field has nil value") - - // ErrNil is the error returned if Marshal is called with nil. - ErrNil = errors.New("proto: Marshal called with nil") -) - -// The fundamental encoders that put bytes on the wire. -// Those that take integer types all accept uint64 and are -// therefore of type valueEncoder. - -const maxVarintBytes = 10 // maximum length of a varint - -// EncodeVarint returns the varint encoding of x. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -// Not used by the package itself, but helpful to clients -// wishing to use the same encoding. -func EncodeVarint(x uint64) []byte { - var buf [maxVarintBytes]byte - var n int - for n = 0; x > 127; n++ { - buf[n] = 0x80 | uint8(x&0x7F) - x >>= 7 - } - buf[n] = uint8(x) - n++ - return buf[0:n] -} - -// EncodeVarint writes a varint-encoded integer to the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) EncodeVarint(x uint64) error { - for x >= 1<<7 { - p.buf = append(p.buf, uint8(x&0x7f|0x80)) - x >>= 7 - } - p.buf = append(p.buf, uint8(x)) - 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++ - x >>= 7 - if x == 0 { - break - } - } - return n -} - -// EncodeFixed64 writes a 64-bit integer to the Buffer. -// This is the format for the -// fixed64, sfixed64, and double protocol buffer types. -func (p *Buffer) EncodeFixed64(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24), - uint8(x>>32), - uint8(x>>40), - uint8(x>>48), - uint8(x>>56)) - return nil -} - -func sizeFixed64(x uint64) int { - return 8 -} - -// EncodeFixed32 writes a 32-bit integer to the Buffer. -// This is the format for the -// fixed32, sfixed32, and float protocol buffer types. -func (p *Buffer) EncodeFixed32(x uint64) error { - p.buf = append(p.buf, - uint8(x), - uint8(x>>8), - uint8(x>>16), - uint8(x>>24)) - return nil -} - -func sizeFixed32(x uint64) int { - return 4 -} - -// EncodeZigzag64 writes a zigzag-encoded 64-bit integer -// to the Buffer. -// 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)))) -} - -func sizeZigzag64(x uint64) int { - return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} - -// EncodeZigzag32 writes a zigzag-encoded 32-bit integer -// to the Buffer. -// This is the format used for the sint32 protocol buffer type. -func (p *Buffer) EncodeZigzag32(x uint64) error { - // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) -} - -func sizeZigzag32(x uint64) int { - return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31)))) -} - -// EncodeRawBytes writes a count-delimited byte buffer to the Buffer. -// This is the format used for the bytes protocol buffer -// type and for embedded messages. -func (p *Buffer) EncodeRawBytes(b []byte) error { - p.EncodeVarint(uint64(len(b))) - p.buf = append(p.buf, b...) - return nil -} - -func sizeRawBytes(b []byte) int { - return sizeVarint(uint64(len(b))) + - len(b) -} - -// EncodeStringBytes writes an encoded string to the Buffer. -// This is the format used for the proto2 string type. -func (p *Buffer) EncodeStringBytes(s string) error { - p.EncodeVarint(uint64(len(s))) - p.buf = append(p.buf, s...) - return nil -} - -func sizeStringBytes(s string) int { - return sizeVarint(uint64(len(s))) + - len(s) -} - -// Marshaler is the interface representing objects that can marshal themselves. -type Marshaler interface { - Marshal() ([]byte, error) -} - -// Marshal takes the protocol buffer -// and encodes it into the wire format, returning the data. -func Marshal(pb Message) ([]byte, error) { - // Can the object marshal itself? - if m, ok := pb.(Marshaler); ok { - return m.Marshal() - } - 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 - } - 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. -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 - } - - t, base, err := getbase(pb) - if structPointer_IsNil(base) { - return ErrNil - } - if err == nil { - err = p.enc_struct(GetProperties(t.Elem()), base) - } - - if collectStats { - stats.Encode++ - } - - return err -} - -// Size returns the encoded size of a protocol buffer. -func Size(pb Message) (n int) { - // Can the object marshal itself? If so, Size is slow. - // TODO: add Size to Marshaler, or add a Sizer interface. - if m, ok := pb.(Marshaler); ok { - b, _ := m.Marshal() - return len(b) - } - - t, base, err := getbase(pb) - if structPointer_IsNil(base) { - return 0 - } - if err == nil { - n = size_struct(GetProperties(t.Elem()), base) - } - - if collectStats { - stats.Size++ - } - - return -} - -// Individual type encoders. - -// Encode a bool. -func (o *Buffer) enc_bool(p *Properties, base structPointer) error { - v := *structPointer_Bool(base, p.field) - if v == nil { - return ErrNil - } - x := 0 - if *v { - x = 1 - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error { - v := *structPointer_BoolVal(base, p.field) - if !v { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, 1) - return nil -} - -func size_bool(p *Properties, base structPointer) int { - v := *structPointer_Bool(base, p.field) - if v == nil { - return 0 - } - return len(p.tagcode) + 1 // each bool takes exactly one byte -} - -func size_proto3_bool(p *Properties, base structPointer) int { - v := *structPointer_BoolVal(base, p.field) - if !v && !p.oneof { - return 0 - } - return len(p.tagcode) + 1 // each bool takes exactly one byte -} - -// Encode an int32. -func (o *Buffer) enc_int32(p *Properties, base structPointer) error { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return ErrNil - } - x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error { - v := structPointer_Word32Val(base, p.field) - x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func size_int32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return 0 - } - x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -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 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -// Encode a uint32. -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_uint32(p *Properties, base structPointer) error { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return ErrNil - } - x := word32_Get(v) - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error { - v := structPointer_Word32Val(base, p.field) - x := word32Val_Get(v) - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, uint64(x)) - return nil -} - -func size_uint32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32(base, p.field) - if word32_IsNil(v) { - return 0 - } - x := word32_Get(v) - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -func size_proto3_uint32(p *Properties, base structPointer) (n int) { - v := structPointer_Word32Val(base, p.field) - x := word32Val_Get(v) - if x == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += p.valSize(uint64(x)) - return -} - -// Encode an int64. -func (o *Buffer) enc_int64(p *Properties, base structPointer) error { - v := structPointer_Word64(base, p.field) - if word64_IsNil(v) { - return ErrNil - } - x := word64_Get(v) - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, x) - return nil -} - -func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error { - v := structPointer_Word64Val(base, p.field) - x := word64Val_Get(v) - if x == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, x) - return nil -} - -func size_int64(p *Properties, base structPointer) (n int) { - v := structPointer_Word64(base, p.field) - if word64_IsNil(v) { - return 0 - } - x := word64_Get(v) - n += len(p.tagcode) - n += p.valSize(x) - return -} - -func size_proto3_int64(p *Properties, base structPointer) (n int) { - v := structPointer_Word64Val(base, p.field) - x := word64Val_Get(v) - if x == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += p.valSize(x) - return -} - -// Encode a string. -func (o *Buffer) enc_string(p *Properties, base structPointer) error { - v := *structPointer_String(base, p.field) - if v == nil { - return ErrNil - } - x := *v - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(x) - return nil -} - -func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error { - v := *structPointer_StringVal(base, p.field) - if v == "" { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(v) - return nil -} - -func size_string(p *Properties, base structPointer) (n int) { - v := *structPointer_String(base, p.field) - if v == nil { - return 0 - } - x := *v - n += len(p.tagcode) - n += sizeStringBytes(x) - return -} - -func size_proto3_string(p *Properties, base structPointer) (n int) { - v := *structPointer_StringVal(base, p.field) - if v == "" && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += sizeStringBytes(v) - return -} - -// All protocol buffer fields are nillable, but be careful. -func isNil(v reflect.Value) bool { - switch v.Kind() { - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - } - return false -} - -// Encode a message struct. -func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error { - var state errorState - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return ErrNil - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, err := m.Marshal() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - return state.err - } - - o.buf = append(o.buf, p.tagcode...) - return o.enc_len_struct(p.sprop, structp, &state) -} - -func size_struct_message(p *Properties, base structPointer) int { - structp := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(structp) { - return 0 - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, _ := m.Marshal() - n0 := len(p.tagcode) - n1 := sizeRawBytes(data) - return n0 + n1 - } - - n0 := len(p.tagcode) - n1 := size_struct(p.sprop, structp) - n2 := sizeVarint(uint64(n1)) // size of encoded length - return n0 + n1 + n2 -} - -// Encode a group struct. -func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error { - var state errorState - b := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(b) { - return ErrNil - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) - err := o.enc_struct(p.sprop, b) - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) - return state.err -} - -func size_struct_group(p *Properties, base structPointer) (n int) { - b := structPointer_GetStructPointer(base, p.field) - if structPointer_IsNil(b) { - return 0 - } - - n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup)) - n += size_struct(p.sprop, b) - n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup)) - return -} - -// Encode a slice of bools ([]bool). -func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return ErrNil - } - for _, x := range s { - o.buf = append(o.buf, p.tagcode...) - v := uint64(0) - if x { - v = 1 - } - p.valEnc(o, v) - } - return nil -} - -func size_slice_bool(p *Properties, base structPointer) int { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return 0 - } - return l * (len(p.tagcode) + 1) // each bool takes exactly one byte -} - -// Encode a slice of bools ([]bool) in packed format. -func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(l)) // each bool takes exactly one byte - for _, x := range s { - v := uint64(0) - if x { - v = 1 - } - p.valEnc(o, v) - } - return nil -} - -func size_slice_packed_bool(p *Properties, base structPointer) (n int) { - s := *structPointer_BoolSlice(base, p.field) - l := len(s) - if l == 0 { - return 0 - } - n += len(p.tagcode) - n += sizeVarint(uint64(l)) - n += l // each bool takes exactly one byte - return -} - -// Encode a slice of bytes ([]byte). -func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error { - s := *structPointer_Bytes(base, p.field) - if s == nil { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(s) - return nil -} - -func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error { - s := *structPointer_Bytes(base, p.field) - if len(s) == 0 { - return ErrNil - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(s) - return nil -} - -func size_slice_byte(p *Properties, base structPointer) (n int) { - s := *structPointer_Bytes(base, p.field) - if s == nil && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += sizeRawBytes(s) - return -} - -func size_proto3_slice_byte(p *Properties, base structPointer) (n int) { - s := *structPointer_Bytes(base, p.field) - if len(s) == 0 && !p.oneof { - return 0 - } - n += len(p.tagcode) - n += sizeRawBytes(s) - return -} - -// Encode a slice of int32s ([]int32). -func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - p.valEnc(o, uint64(x)) - } - return nil -} - -func size_slice_int32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - n += p.valSize(uint64(x)) - } - return -} - -// Encode a slice of int32s ([]int32) in packed format. -func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - p.valEnc(buf, uint64(x)) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_int32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - x := int32(s.Index(i)) // permit sign extension to use full 64-bit range - bufSize += p.valSize(uint64(x)) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of uint32s ([]uint32). -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - x := s.Index(i) - p.valEnc(o, uint64(x)) - } - return nil -} - -func size_slice_uint32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - x := s.Index(i) - n += p.valSize(uint64(x)) - } - return -} - -// Encode a slice of uint32s ([]uint32) in packed format. -// Exactly the same as int32, except for no sign extension. -func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - p.valEnc(buf, uint64(s.Index(i))) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_uint32(p *Properties, base structPointer) (n int) { - s := structPointer_Word32Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - bufSize += p.valSize(uint64(s.Index(i))) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of int64s ([]int64). -func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - p.valEnc(o, s.Index(i)) - } - return nil -} - -func size_slice_int64(p *Properties, base structPointer) (n int) { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - for i := 0; i < l; i++ { - n += len(p.tagcode) - n += p.valSize(s.Index(i)) - } - return -} - -// Encode a slice of int64s ([]int64) in packed format. -func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return ErrNil - } - // TODO: Reuse a Buffer. - buf := NewBuffer(nil) - for i := 0; i < l; i++ { - p.valEnc(buf, s.Index(i)) - } - - o.buf = append(o.buf, p.tagcode...) - o.EncodeVarint(uint64(len(buf.buf))) - o.buf = append(o.buf, buf.buf...) - return nil -} - -func size_slice_packed_int64(p *Properties, base structPointer) (n int) { - s := structPointer_Word64Slice(base, p.field) - l := s.Len() - if l == 0 { - return 0 - } - var bufSize int - for i := 0; i < l; i++ { - bufSize += p.valSize(s.Index(i)) - } - - n += len(p.tagcode) - n += sizeVarint(uint64(bufSize)) - n += bufSize - return -} - -// Encode a slice of slice of bytes ([][]byte). -func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error { - ss := *structPointer_BytesSlice(base, p.field) - l := len(ss) - if l == 0 { - return ErrNil - } - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(ss[i]) - } - return nil -} - -func size_slice_slice_byte(p *Properties, base structPointer) (n int) { - ss := *structPointer_BytesSlice(base, p.field) - l := len(ss) - if l == 0 { - return 0 - } - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - n += sizeRawBytes(ss[i]) - } - return -} - -// Encode a slice of strings ([]string). -func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error { - ss := *structPointer_StringSlice(base, p.field) - l := len(ss) - for i := 0; i < l; i++ { - o.buf = append(o.buf, p.tagcode...) - o.EncodeStringBytes(ss[i]) - } - return nil -} - -func size_slice_string(p *Properties, base structPointer) (n int) { - ss := *structPointer_StringSlice(base, p.field) - l := len(ss) - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - n += sizeStringBytes(ss[i]) - } - return -} - -// Encode a slice of message structs ([]*struct). -func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error { - var state errorState - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - for i := 0; i < l; i++ { - structp := s.Index(i) - if structPointer_IsNil(structp) { - return errRepeatedHasNil - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, err := m.Marshal() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - o.buf = append(o.buf, p.tagcode...) - o.EncodeRawBytes(data) - continue - } - - o.buf = append(o.buf, p.tagcode...) - err := o.enc_len_struct(p.sprop, structp, &state) - if err != nil && !state.shouldContinue(err, nil) { - if err == ErrNil { - return errRepeatedHasNil - } - return err - } - } - return state.err -} - -func size_slice_struct_message(p *Properties, base structPointer) (n int) { - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - n += l * len(p.tagcode) - for i := 0; i < l; i++ { - structp := s.Index(i) - if structPointer_IsNil(structp) { - return // return the size up to this point - } - - // Can the object marshal itself? - if p.isMarshaler { - m := structPointer_Interface(structp, p.stype).(Marshaler) - data, _ := m.Marshal() - n += len(p.tagcode) - n += sizeRawBytes(data) - continue - } - - n0 := size_struct(p.sprop, structp) - n1 := sizeVarint(uint64(n0)) // size of encoded length - n += n0 + n1 - } - return -} - -// Encode a slice of group structs ([]*struct). -func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error { - var state errorState - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - for i := 0; i < l; i++ { - b := s.Index(i) - if structPointer_IsNil(b) { - return errRepeatedHasNil - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup)) - - err := o.enc_struct(p.sprop, b) - - if err != nil && !state.shouldContinue(err, nil) { - if err == ErrNil { - return errRepeatedHasNil - } - return err - } - - o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup)) - } - return state.err -} - -func size_slice_struct_group(p *Properties, base structPointer) (n int) { - s := structPointer_StructPointerSlice(base, p.field) - l := s.Len() - - n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup)) - n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup)) - for i := 0; i < l; i++ { - b := s.Index(i) - if structPointer_IsNil(b) { - return // return size up to this point - } - - n += size_struct(p.sprop, b) - } - return -} - -// 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 { - return err - } - // Fast-path for common cases: zero or one extensions. - if len(v) <= 1 { - for _, e := range v { - o.buf = append(o.buf, e.enc...) - } - return nil - } - - // Sort keys to provide a deterministic encoding. - keys := make([]int, 0, len(v)) - for k := range v { - keys = append(keys, int(k)) - } - sort.Ints(keys) - - for _, k := range keys { - o.buf = append(o.buf, v[int32(k)].enc...) - } - return nil -} - -func size_map(p *Properties, base structPointer) int { - v := *structPointer_ExtMap(base, p.field) - return sizeExtensionMap(v) -} - -// Encode a map field. -func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { - var state errorState // XXX: or do we need to plumb this through? - - /* - A map defined as - map map_field = N; - is encoded in the same way as - message MapFieldEntry { - key_type key = 1; - value_type value = 2; - } - repeated MapFieldEntry map_field = N; - */ - - v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V - if v.Len() == 0 { - return nil - } - - keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) - - enc := func() 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 { - return err - } - return nil - } - - // 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) - - o.buf = append(o.buf, p.tagcode...) - if err := o.enc_len_thing(enc, &state); err != nil { - return err - } - } - return nil -} - -func size_new_map(p *Properties, base structPointer) int { - v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V - - keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype) - - n := 0 - for _, key := range v.MapKeys() { - val := v.MapIndex(key) - keycopy.Set(key) - valcopy.Set(val) - - // Tag codes for key and val are the responsibility of the sub-sizer. - keysize := p.mkeyprop.size(p.mkeyprop, keybase) - valsize := p.mvalprop.size(p.mvalprop, valbase) - entry := keysize + valsize - // Add on tag code and length of map entry itself. - n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry - } - return n -} - -// mapEncodeScratch returns a new reflect.Value matching the map's value type, -// and a structPointer suitable for passing to an encoder or sizer. -func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) { - // Prepare addressable doubly-indirect placeholders for the key and value types. - // This is needed because the element-type encoders expect **T, but the map iteration produces T. - - keycopy = reflect.New(mapType.Key()).Elem() // addressable K - keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K - keyptr.Set(keycopy.Addr()) // - keybase = toStructPointer(keyptr.Addr()) // **K - - // Value types are more varied and require special handling. - switch mapType.Elem().Kind() { - case reflect.Slice: - // []byte - var dummy []byte - valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte - valbase = toStructPointer(valcopy.Addr()) - case reflect.Ptr: - // message; the generated field type is map[K]*Msg (so V is *Msg), - // so we only need one level of indirection. - valcopy = reflect.New(mapType.Elem()).Elem() // addressable V - valbase = toStructPointer(valcopy.Addr()) - default: - // everything else - valcopy = reflect.New(mapType.Elem()).Elem() // addressable V - valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V - valptr.Set(valcopy.Addr()) // - valbase = toStructPointer(valptr.Addr()) // **V - } - return -} - -// Encode a struct. -func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { - var state errorState - // Encode fields in tag order so that decoders may use optimizations - // that depend on the ordering. - // https://developers.google.com/protocol-buffers/docs/encoding#order - for _, i := range prop.order { - p := prop.Prop[i] - if p.enc != nil { - err := p.enc(o, p, base) - if err != nil { - if err == ErrNil { - if p.Required && state.err == nil { - state.err = &RequiredNotSetError{p.Name} - } - } else if err == errRepeatedHasNil { - // Give more context to nil values in repeated fields. - return errors.New("repeated field " + p.OrigName + " has nil element") - } else if !state.shouldContinue(err, p) { - return err - } - } - } - } - - // 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(v) > 0 { - o.buf = append(o.buf, v...) - } - } - - return state.err -} - -func size_struct(prop *StructProperties, base structPointer) (n int) { - for _, i := range prop.order { - p := prop.Prop[i] - if p.size != nil { - n += p.size(p, base) - } - } - - // Add unrecognized fields at the end. - if prop.unrecField.IsValid() { - v := *structPointer_Bytes(base, prop.unrecField) - n += len(v) - } - - // Factor in any oneof fields. - if prop.oneofSizer != nil { - m := structPointer_Interface(base, prop.stype).(Message) - n += prop.oneofSizer(m) - } - - return -} - -var zeroes [20]byte // longer than any conceivable sizeVarint - -// Encode a struct, preceded by its encoded length (as a varint). -func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error { - return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state) -} - -// Encode something, preceded by its encoded length (as a varint). -func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error { - iLen := len(o.buf) - o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length - iMsg := len(o.buf) - err := enc() - if err != nil && !state.shouldContinue(err, nil) { - return err - } - lMsg := len(o.buf) - iMsg - lLen := sizeVarint(uint64(lMsg)) - switch x := lLen - (iMsg - iLen); { - case x > 0: // actual length is x bytes larger than the space we reserved - // Move msg x bytes right. - o.buf = append(o.buf, zeroes[:x]...) - copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) - case x < 0: // actual length is x bytes smaller than the space we reserved - // Move msg x bytes left. - copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg]) - o.buf = o.buf[:len(o.buf)+x] // x is negative - } - // Encode the length in the reserved space. - o.buf = o.buf[:iLen] - o.EncodeVarint(uint64(lMsg)) - o.buf = o.buf[:len(o.buf)+lMsg] - return state.err -} - -// errorState maintains the first error that occurs and updates that error -// with additional context. -type errorState struct { - err error -} - -// shouldContinue reports whether encoding should continue upon encountering the -// given error. If the error is RequiredNotSetError, shouldContinue returns true -// and, if this is the first appearance of that error, remembers it for future -// reporting. -// -// If prop is not nil, it may update any error with additional context about the -// field with the error. -func (s *errorState) shouldContinue(err error, prop *Properties) bool { - // Ignore unset required fields. - reqNotSet, ok := err.(*RequiredNotSetError) - if !ok { - return false - } - if s.err == nil { - if prop != nil { - err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field} - } - s.err = err - } - return true -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go deleted file mode 100644 index f5db1def3..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go +++ /dev/null @@ -1,276 +0,0 @@ -// 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. - -// Protocol buffer comparison. - -package proto - -import ( - "bytes" - "log" - "reflect" - "strings" -) - -/* -Equal returns true iff protocol buffers a and b are equal. -The arguments must both be pointers to protocol buffer structs. - -Equality is defined in this way: - - Two messages are equal iff they are the same type, - corresponding fields are equal, unknown field sets - are equal, and extensions sets are equal. - - Two set scalar fields are equal iff their values are equal. - If the fields are of a floating-point type, remember that - NaN != x for all x, including NaN. If the message is defined - in a proto3 .proto file, fields are not "set"; specifically, - zero length proto3 "bytes" fields are equal (nil == {}). - - Two repeated fields are equal iff their lengths are the same, - and their corresponding elements are equal (a "bytes" field, - although represented by []byte, is not a repeated field) - - Two unset fields are equal. - - Two unknown field sets are equal if their current - encoded state is equal. - - Two extension sets are equal iff they have corresponding - elements that are pairwise equal. - - Every other combination of things are not equal. - -The return value is undefined if a and b are not protocol buffers. -*/ -func Equal(a, b Message) bool { - if a == nil || b == nil { - return a == b - } - v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b) - if v1.Type() != v2.Type() { - return false - } - if v1.Kind() == reflect.Ptr { - if v1.IsNil() { - return v2.IsNil() - } - if v2.IsNil() { - return false - } - v1, v2 = v1.Elem(), v2.Elem() - } - if v1.Kind() != reflect.Struct { - return false - } - return equalStruct(v1, v2) -} - -// v1 and v2 are known to have the same type. -func equalStruct(v1, v2 reflect.Value) bool { - sprop := GetProperties(v1.Type()) - for i := 0; i < v1.NumField(); i++ { - f := v1.Type().Field(i) - if strings.HasPrefix(f.Name, "XXX_") { - continue - } - f1, f2 := v1.Field(i), v2.Field(i) - if f.Type.Kind() == reflect.Ptr { - if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 { - // both unset - continue - } else if n1 != n2 { - // set/unset mismatch - return false - } - b1, ok := f1.Interface().(raw) - if ok { - b2 := f2.Interface().(raw) - // RawMessage - if !bytes.Equal(b1.Bytes(), b2.Bytes()) { - return false - } - continue - } - f1, f2 = f1.Elem(), f2.Elem() - } - if !equalAny(f1, f2, sprop.Prop[i]) { - return false - } - } - - if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { - em2 := v2.FieldByName("XXX_extensions") - if !equalExtensions(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { - return false - } - } - - uf := v1.FieldByName("XXX_unrecognized") - if !uf.IsValid() { - return true - } - - u1 := uf.Bytes() - u2 := v2.FieldByName("XXX_unrecognized").Bytes() - if !bytes.Equal(u1, u2) { - return false - } - - return true -} - -// v1 and v2 are known to have the same type. -// prop may be nil. -func equalAny(v1, v2 reflect.Value, prop *Properties) bool { - if v1.Type() == protoMessageType { - m1, _ := v1.Interface().(Message) - m2, _ := v2.Interface().(Message) - return Equal(m1, m2) - } - switch v1.Kind() { - case reflect.Bool: - return v1.Bool() == v2.Bool() - case reflect.Float32, reflect.Float64: - return v1.Float() == v2.Float() - case reflect.Int32, reflect.Int64: - return v1.Int() == v2.Int() - case reflect.Interface: - // Probably a oneof field; compare the inner values. - n1, n2 := v1.IsNil(), v2.IsNil() - if n1 || n2 { - return n1 == n2 - } - e1, e2 := v1.Elem(), v2.Elem() - if e1.Type() != e2.Type() { - return false - } - return equalAny(e1, e2, nil) - case reflect.Map: - if v1.Len() != v2.Len() { - return false - } - for _, key := range v1.MapKeys() { - val2 := v2.MapIndex(key) - if !val2.IsValid() { - // This key was not found in the second map. - return false - } - if !equalAny(v1.MapIndex(key), val2, nil) { - return false - } - } - return true - case reflect.Ptr: - return equalAny(v1.Elem(), v2.Elem(), prop) - case reflect.Slice: - if v1.Type().Elem().Kind() == reflect.Uint8 { - // short circuit: []byte - - // Edge case: if this is in a proto3 message, a zero length - // bytes field is considered the zero value. - if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 { - return true - } - if v1.IsNil() != v2.IsNil() { - return false - } - return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte)) - } - - if v1.Len() != v2.Len() { - return false - } - for i := 0; i < v1.Len(); i++ { - if !equalAny(v1.Index(i), v2.Index(i), prop) { - return false - } - } - return true - case reflect.String: - return v1.Interface().(string) == v2.Interface().(string) - case reflect.Struct: - return equalStruct(v1, v2) - case reflect.Uint32, reflect.Uint64: - return v1.Uint() == v2.Uint() - } - - // unknown type, so not a protocol buffer - log.Printf("proto: don't know how to compare %v", v1) - return false -} - -// base is the struct type that the extensions are based on. -// em1 and em2 are extension maps. -func equalExtensions(base reflect.Type, em1, em2 map[int32]Extension) bool { - if len(em1) != len(em2) { - return false - } - - for extNum, e1 := range em1 { - e2, ok := em2[extNum] - if !ok { - return false - } - - m1, m2 := e1.value, e2.value - - if m1 != nil && m2 != nil { - // Both are unencoded. - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { - return false - } - continue - } - - // At least one is encoded. To do a semantically correct comparison - // we need to unmarshal them first. - var desc *ExtensionDesc - if m := extensionMaps[base]; m != nil { - desc = m[extNum] - } - if desc == nil { - log.Printf("proto: don't know how to compare extension %d of %v", extNum, base) - continue - } - var err error - if m1 == nil { - m1, err = decodeExtension(e1.enc, desc) - } - if m2 == nil && err == nil { - m2, err = decodeExtension(e2.enc, desc) - } - if err != nil { - // The encoded form is invalid. - log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err) - return false - } - if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) { - return false - } - } - - return true -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go deleted file mode 100644 index 054f4f1df..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go +++ /dev/null @@ -1,399 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Types and routines for supporting protocol buffer extensions. - */ - -import ( - "errors" - "fmt" - "reflect" - "strconv" - "sync" -) - -// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message. -var ErrMissingExtension = errors.New("proto: missing extension") - -// ExtensionRange represents a range of message extensions for a protocol buffer. -// Used in code generated by the protocol compiler. -type ExtensionRange struct { - Start, End int32 // both inclusive -} - -// extendableProto is an interface implemented by any protocol buffer that may be extended. -type extendableProto interface { - Message - ExtensionRangeArray() []ExtensionRange - ExtensionMap() map[int32]Extension -} - -var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem() - -// ExtensionDesc represents an extension specification. -// Used in generated code from the protocol compiler. -type ExtensionDesc struct { - ExtendedType Message // nil pointer to the type that is being extended - ExtensionType interface{} // nil pointer to the extension type - Field int32 // field number - Name string // fully-qualified name of extension, for text formatting - Tag string // protobuf tag style -} - -func (ed *ExtensionDesc) repeated() bool { - t := reflect.TypeOf(ed.ExtensionType) - return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 -} - -// Extension represents an extension in a message. -type Extension struct { - // When an extension is stored in a message using SetExtension - // only desc and value are set. When the message is marshaled - // enc will be set to the encoded form of the message. - // - // When a message is unmarshaled and contains extensions, each - // extension will have only enc set. When such an extension is - // accessed using GetExtension (or GetExtensions) desc and value - // will be set. - desc *ExtensionDesc - value interface{} - enc []byte -} - -// SetRawExtension is for testing only. -func SetRawExtension(base extendableProto, id int32, b []byte) { - base.ExtensionMap()[id] = Extension{enc: b} -} - -// isExtensionField returns true iff the given field number is in an extension range. -func isExtensionField(pb extendableProto, field int32) bool { - for _, er := range pb.ExtensionRangeArray() { - if er.Start <= field && field <= er.End { - return true - } - } - return false -} - -// checkExtensionTypes checks that the given extension is valid for pb. -func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { - // Check the extended type. - if a, b := reflect.TypeOf(pb), reflect.TypeOf(extension.ExtendedType); a != b { - return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String()) - } - // Check the range. - if !isExtensionField(pb, extension.Field) { - return errors.New("proto: bad extension number; not in declared ranges") - } - return nil -} - -// extPropKey is sufficient to uniquely identify an extension. -type extPropKey struct { - base reflect.Type - field int32 -} - -var extProp = struct { - sync.RWMutex - m map[extPropKey]*Properties -}{ - m: make(map[extPropKey]*Properties), -} - -func extensionProperties(ed *ExtensionDesc) *Properties { - key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field} - - extProp.RLock() - if prop, ok := extProp.m[key]; ok { - extProp.RUnlock() - return prop - } - extProp.RUnlock() - - extProp.Lock() - defer extProp.Unlock() - // Check again. - if prop, ok := extProp.m[key]; ok { - return prop - } - - prop := new(Properties) - prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil) - extProp.m[key] = prop - return prop -} - -// encodeExtensionMap encodes any unmarshaled (unencoded) extensions in m. -func encodeExtensionMap(m map[int32]Extension) error { - for k, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - et := reflect.TypeOf(e.desc.ExtensionType) - props := extensionProperties(e.desc) - - p := NewBuffer(nil) - // If e.value has type T, the encoder expects a *struct{ X T }. - // Pass a *T with a zero field and hope it all works out. - x := reflect.New(et) - x.Elem().Set(reflect.ValueOf(e.value)) - if err := props.enc(p, props, toStructPointer(x)); err != nil { - return err - } - e.enc = p.buf - m[k] = e - } - return nil -} - -func sizeExtensionMap(m map[int32]Extension) (n int) { - for _, e := range m { - if e.value == nil || e.desc == nil { - // Extension is only in its encoded form. - n += len(e.enc) - continue - } - - // We don't skip extensions that have an encoded form set, - // because the extension value may have been mutated after - // the last time this function was called. - - et := reflect.TypeOf(e.desc.ExtensionType) - props := extensionProperties(e.desc) - - // If e.value has type T, the encoder expects a *struct{ X T }. - // Pass a *T with a zero field and hope it all works out. - x := reflect.New(et) - x.Elem().Set(reflect.ValueOf(e.value)) - n += props.size(props, toStructPointer(x)) - } - return -} - -// HasExtension returns whether the given extension is present in pb. -func HasExtension(pb extendableProto, extension *ExtensionDesc) bool { - // TODO: Check types, field numbers, etc.? - _, ok := pb.ExtensionMap()[extension.Field] - return ok -} - -// ClearExtension removes the given extension from pb. -func ClearExtension(pb extendableProto, extension *ExtensionDesc) { - // TODO: Check types, field numbers, etc.? - delete(pb.ExtensionMap(), extension.Field) -} - -// GetExtension parses and returns the given extension of pb. -// If the extension is not present and has no default value it returns ErrMissingExtension. -func GetExtension(pb extendableProto, extension *ExtensionDesc) (interface{}, error) { - if err := checkExtensionTypes(pb, extension); err != nil { - return nil, err - } - - emap := pb.ExtensionMap() - e, ok := emap[extension.Field] - if !ok { - // defaultExtensionValue returns the default value or - // ErrMissingExtension if there is no default. - return defaultExtensionValue(extension) - } - - if e.value != nil { - // Already decoded. Check the descriptor, though. - if e.desc != extension { - // This shouldn't happen. If it does, it means that - // GetExtension was called twice with two different - // descriptors with the same field number. - return nil, errors.New("proto: descriptor conflict") - } - return e.value, nil - } - - v, err := decodeExtension(e.enc, extension) - if err != nil { - return nil, err - } - - // Remember the decoded version and drop the encoded version. - // That way it is safe to mutate what we return. - e.value = v - e.desc = extension - e.enc = nil - emap[extension.Field] = e - return e.value, nil -} - -// defaultExtensionValue returns the default value for extension. -// If no default for an extension is defined ErrMissingExtension is returned. -func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) { - t := reflect.TypeOf(extension.ExtensionType) - props := extensionProperties(extension) - - sf, _, err := fieldDefault(t, props) - if err != nil { - return nil, err - } - - if sf == nil || sf.value == nil { - // There is no default value. - return nil, ErrMissingExtension - } - - if t.Kind() != reflect.Ptr { - // We do not need to return a Ptr, we can directly return sf.value. - return sf.value, nil - } - - // We need to return an interface{} that is a pointer to sf.value. - value := reflect.New(t).Elem() - value.Set(reflect.New(value.Type().Elem())) - if sf.kind == reflect.Int32 { - // We may have an int32 or an enum, but the underlying data is int32. - // Since we can't set an int32 into a non int32 reflect.value directly - // set it as a int32. - value.Elem().SetInt(int64(sf.value.(int32))) - } else { - value.Elem().Set(reflect.ValueOf(sf.value)) - } - return value.Interface(), nil -} - -// decodeExtension decodes an extension encoded in b. -func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { - o := NewBuffer(b) - - t := reflect.TypeOf(extension.ExtensionType) - - props := extensionProperties(extension) - - // t is a pointer to a struct, pointer to basic type or a slice. - // Allocate a "field" to store the pointer/slice itself; the - // pointer/slice will be stored here. We pass - // the address of this field to props.dec. - // This passes a zero field and a *t and lets props.dec - // interpret it as a *struct{ x t }. - value := reflect.New(t).Elem() - - for { - // Discard wire type and field number varint. It isn't needed. - if _, err := o.DecodeVarint(); err != nil { - return nil, err - } - - if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil { - return nil, err - } - - if o.index >= len(o.buf) { - break - } - } - return value.Interface(), nil -} - -// 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) - if !ok { - err = errors.New("proto: not an extendable proto") - return - } - extensions = make([]interface{}, len(es)) - for i, e := range es { - extensions[i], err = GetExtension(epb, e) - if err == ErrMissingExtension { - err = nil - } - if err != nil { - return - } - } - return -} - -// 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 { - return err - } - typ := reflect.TypeOf(extension.ExtensionType) - if typ != reflect.TypeOf(value) { - return errors.New("proto: bad extension value type") - } - // nil extension values need to be caught early, because the - // encoder can't distinguish an ErrNil due to a nil extension - // from an ErrNil due to a missing field. Extensions are - // always optional, so the encoder would just swallow the error - // and drop all the extensions from the encoded message. - if reflect.ValueOf(value).IsNil() { - return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) - } - - pb.ExtensionMap()[extension.Field] = Extension{desc: extension, value: value} - return nil -} - -// A global registry of extensions. -// The generated code will register the generated descriptors by calling RegisterExtension. - -var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc) - -// RegisterExtension is called from the generated code. -func RegisterExtension(desc *ExtensionDesc) { - st := reflect.TypeOf(desc.ExtendedType).Elem() - m := extensionMaps[st] - if m == nil { - m = make(map[int32]*ExtensionDesc) - extensionMaps[st] = m - } - if _, ok := m[desc.Field]; ok { - panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field))) - } - m[desc.Field] = desc -} - -// RegisteredExtensions returns a map of the registered extensions of a -// protocol buffer struct, indexed by the extension number. -// The argument pb should be a nil pointer to the struct type. -func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc { - return extensionMaps[reflect.TypeOf(pb).Elem()] -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go deleted file mode 100644 index 0de8f8dff..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go +++ /dev/null @@ -1,894 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -/* -Package proto 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. - 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 by the enclosing message's name, or by the - enum's type name if it is a top-level enum. Enum types have a String - method, and a Enum method to assist in message construction. - - Nested messages, 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. - - Getters are only generated for message and oneof fields. - - Enum types do not get an Enum method. - -The simplest way to describe this is to see an example. -Given file test.proto, containing - - 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; - } - oneof union { - int32 number = 6; - string name = 7; - } - } - -The resulting file, test.pb.go, is: - - package example - - import proto "github.com/golang/protobuf/proto" - import math "math" - - type FOO int32 - const ( - FOO_X FOO = 17 - ) - var FOO_name = map[int32]string{ - 17: "X", - } - var FOO_value = map[string]int32{ - "X": 17, - } - - 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) - if err != nil { - return err - } - *x = FOO(value) - return nil - } - - 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"` - // 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() {} - - 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 { - if m != nil && m.Label != nil { - return *m.Label - } - return "" - } - - func (m *Test) GetType() int32 { - if m != nil && m.Type != nil { - return *m.Type - } - return Default_Test_Type - } - - func (m *Test) GetOptionalgroup() *Test_OptionalGroup { - if m != nil { - return m.Optionalgroup - } - return nil - } - - type Test_OptionalGroup struct { - RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"` - } - func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} } - func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) } - - func (m *Test_OptionalGroup) GetRequiredField() string { - if m != nil && m.RequiredField != nil { - return *m.RequiredField - } - 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 - - import ( - "log" - - "github.com/golang/protobuf/proto" - pb "./example.pb" - ) - - func 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 { - log.Fatal("marshaling error: ", err) - } - newTest := &pb.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()) - } - // 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. - } -*/ -package proto - -import ( - "encoding/json" - "fmt" - "log" - "reflect" - "sort" - "strconv" - "sync" -) - -// Message is implemented by generated protocol buffer messages. -type Message interface { - Reset() - String() string - ProtoMessage() -} - -// Stats records allocation details about the protocol buffer encoders -// and decoders. Useful for tuning the library itself. -type Stats struct { - Emalloc uint64 // mallocs in encode - Dmalloc uint64 // mallocs in decode - Encode uint64 // number of encodes - Decode uint64 // number of decodes - Chit uint64 // number of cache hits - Cmiss uint64 // number of cache misses - Size uint64 // number of sizes -} - -// Set to true to enable stats collection. -const collectStats = false - -var stats Stats - -// GetStats returns a copy of the global Stats structure. -func GetStats() Stats { return stats } - -// A Buffer is a buffer manager for marshaling and unmarshaling -// protocol buffers. It may be reused between invocations to -// reduce memory usage. It is not necessary to use a Buffer; -// the global functions Marshal and Unmarshal create a -// temporary Buffer and are fine for most applications. -type Buffer struct { - buf []byte // encode/decode byte stream - index int // write point - - // pools of basic types to amortize allocation. - bools []bool - uint32s []uint32 - uint64s []uint64 - - // extra pools, only used with pointer_reflect.go - int32s []int32 - int64s []int64 - float32s []float32 - float64s []float64 -} - -// NewBuffer allocates a new Buffer and initializes its internal data to -// the contents of the argument slice. -func NewBuffer(e []byte) *Buffer { - return &Buffer{buf: e} -} - -// Reset resets the Buffer, ready for marshaling a new protocol buffer. -func (p *Buffer) Reset() { - p.buf = p.buf[0:0] // for reading/writing - p.index = 0 // for reading -} - -// SetBuf replaces the internal buffer with the slice, -// ready for unmarshaling the contents of the slice. -func (p *Buffer) SetBuf(s []byte) { - p.buf = s - p.index = 0 -} - -// Bytes returns the contents of the Buffer. -func (p *Buffer) Bytes() []byte { return p.buf } - -/* - * Helper routines for simplifying the creation of optional fields of basic type. - */ - -// Bool is a helper routine that allocates a new bool value -// to store v and returns a pointer to it. -func Bool(v bool) *bool { - return &v -} - -// Int32 is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it. -func Int32(v int32) *int32 { - return &v -} - -// Int is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it, but unlike Int32 -// its argument value is an int. -func Int(v int) *int32 { - p := new(int32) - *p = int32(v) - return p -} - -// Int64 is a helper routine that allocates a new int64 value -// to store v and returns a pointer to it. -func Int64(v int64) *int64 { - return &v -} - -// Float32 is a helper routine that allocates a new float32 value -// to store v and returns a pointer to it. -func Float32(v float32) *float32 { - return &v -} - -// Float64 is a helper routine that allocates a new float64 value -// to store v and returns a pointer to it. -func Float64(v float64) *float64 { - return &v -} - -// Uint32 is a helper routine that allocates a new uint32 value -// to store v and returns a pointer to it. -func Uint32(v uint32) *uint32 { - return &v -} - -// Uint64 is a helper routine that allocates a new uint64 value -// to store v and returns a pointer to it. -func Uint64(v uint64) *uint64 { - return &v -} - -// String is a helper routine that allocates a new string value -// to store v and returns a pointer to it. -func String(v string) *string { - return &v -} - -// EnumName is a helper function to simplify printing protocol buffer enums -// by name. Given an enum map and a value, it returns a useful string. -func EnumName(m map[int32]string, v int32) string { - s, ok := m[v] - if ok { - return s - } - return strconv.Itoa(int(v)) -} - -// UnmarshalJSONEnum is a helper function to simplify recovering enum int values -// from their JSON-encoded representation. Given a map from the enum's symbolic -// names to its int values, and a byte buffer containing the JSON-encoded -// value, it returns an int32 that can be cast to the enum type by the caller. -// -// The function can deal with both JSON representations, numeric and symbolic. -func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) { - if data[0] == '"' { - // New style: enums are strings. - var repr string - if err := json.Unmarshal(data, &repr); err != nil { - return -1, err - } - val, ok := m[repr] - if !ok { - return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr) - } - return val, nil - } - // Old style: enums are ints. - var val int32 - if err := json.Unmarshal(data, &val); err != nil { - return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName) - } - return val, nil -} - -// DebugPrint dumps the encoded data in b in a debugging format with a header -// including the string s. Used in testing but made available for general debugging. -func (p *Buffer) DebugPrint(s string, b []byte) { - var u uint64 - - obuf := p.buf - index := p.index - p.buf = b - p.index = 0 - depth := 0 - - fmt.Printf("\n--- %s ---\n", s) - -out: - for { - for i := 0; i < depth; i++ { - fmt.Print(" ") - } - - index := p.index - if index == len(p.buf) { - break - } - - op, err := p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: fetching op err %v\n", index, err) - break out - } - tag := op >> 3 - wire := op & 7 - - switch wire { - default: - fmt.Printf("%3d: t=%3d unknown wire=%d\n", - index, tag, wire) - break out - - case WireBytes: - var r []byte - - r, err = p.DecodeRawBytes(false) - if err != nil { - break out - } - fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r)) - if len(r) <= 6 { - for i := 0; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } else { - for i := 0; i < 3; i++ { - fmt.Printf(" %.2x", r[i]) - } - fmt.Printf(" ..") - for i := len(r) - 3; i < len(r); i++ { - fmt.Printf(" %.2x", r[i]) - } - } - fmt.Printf("\n") - - case WireFixed32: - u, err = p.DecodeFixed32() - if err != nil { - fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u) - - case WireFixed64: - u, err = p.DecodeFixed64() - if err != nil { - fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u) - - case WireVarint: - u, err = p.DecodeVarint() - if err != nil { - fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err) - break out - } - fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u) - - case WireStartGroup: - fmt.Printf("%3d: t=%3d start\n", index, tag) - depth++ - - case WireEndGroup: - depth-- - fmt.Printf("%3d: t=%3d end\n", index, tag) - } - } - - if depth != 0 { - fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth) - } - fmt.Printf("\n") - - p.buf = obuf - p.index = index -} - -// SetDefaults sets unset protocol buffer fields to their default values. -// It only modifies fields that are both unset and have defined defaults. -// It recursively sets default values in any non-nil sub-messages. -func SetDefaults(pb Message) { - setDefaults(reflect.ValueOf(pb), true, false) -} - -// v is a pointer to a struct. -func setDefaults(v reflect.Value, recur, zeros bool) { - v = v.Elem() - - defaultMu.RLock() - dm, ok := defaults[v.Type()] - defaultMu.RUnlock() - if !ok { - dm = buildDefaultMessage(v.Type()) - defaultMu.Lock() - defaults[v.Type()] = dm - defaultMu.Unlock() - } - - for _, sf := range dm.scalars { - f := v.Field(sf.index) - if !f.IsNil() { - // field already set - continue - } - dv := sf.value - if dv == nil && !zeros { - // no explicit default, and don't want to set zeros - continue - } - fptr := f.Addr().Interface() // **T - // TODO: Consider batching the allocations we do here. - switch sf.kind { - case reflect.Bool: - b := new(bool) - if dv != nil { - *b = dv.(bool) - } - *(fptr.(**bool)) = b - case reflect.Float32: - f := new(float32) - if dv != nil { - *f = dv.(float32) - } - *(fptr.(**float32)) = f - case reflect.Float64: - f := new(float64) - if dv != nil { - *f = dv.(float64) - } - *(fptr.(**float64)) = f - case reflect.Int32: - // might be an enum - if ft := f.Type(); ft != int32PtrType { - // enum - f.Set(reflect.New(ft.Elem())) - if dv != nil { - f.Elem().SetInt(int64(dv.(int32))) - } - } else { - // int32 field - i := new(int32) - if dv != nil { - *i = dv.(int32) - } - *(fptr.(**int32)) = i - } - case reflect.Int64: - i := new(int64) - if dv != nil { - *i = dv.(int64) - } - *(fptr.(**int64)) = i - case reflect.String: - s := new(string) - if dv != nil { - *s = dv.(string) - } - *(fptr.(**string)) = s - case reflect.Uint8: - // exceptional case: []byte - var b []byte - if dv != nil { - db := dv.([]byte) - b = make([]byte, len(db)) - copy(b, db) - } else { - b = []byte{} - } - *(fptr.(*[]byte)) = b - case reflect.Uint32: - u := new(uint32) - if dv != nil { - *u = dv.(uint32) - } - *(fptr.(**uint32)) = u - case reflect.Uint64: - u := new(uint64) - if dv != nil { - *u = dv.(uint64) - } - *(fptr.(**uint64)) = u - default: - log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind) - } - } - - for _, ni := range dm.nested { - f := v.Field(ni) - // f is *T or []*T or map[T]*T - switch f.Kind() { - case reflect.Ptr: - if f.IsNil() { - continue - } - setDefaults(f, recur, zeros) - - case reflect.Slice: - for i := 0; i < f.Len(); i++ { - e := f.Index(i) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - - case reflect.Map: - for _, k := range f.MapKeys() { - e := f.MapIndex(k) - if e.IsNil() { - continue - } - setDefaults(e, recur, zeros) - } - } - } -} - -var ( - // defaults maps a protocol buffer struct type to a slice of the fields, - // with its scalar fields set to their proto-declared non-zero default values. - defaultMu sync.RWMutex - defaults = make(map[reflect.Type]defaultMessage) - - int32PtrType = reflect.TypeOf((*int32)(nil)) -) - -// defaultMessage represents information about the default values of a message. -type defaultMessage struct { - scalars []scalarField - nested []int // struct field index of nested messages -} - -type scalarField struct { - index int // struct field index - kind reflect.Kind // element type (the T in *T or []T) - value interface{} // the proto-declared default value, or nil -} - -// t is a struct type. -func buildDefaultMessage(t reflect.Type) (dm defaultMessage) { - sprop := GetProperties(t) - for _, prop := range sprop.Prop { - fi, ok := sprop.decoderTags.get(prop.Tag) - if !ok { - // XXX_unrecognized - continue - } - ft := t.Field(fi).Type - - sf, nested, err := fieldDefault(ft, prop) - switch { - case err != nil: - log.Print(err) - case nested: - dm.nested = append(dm.nested, fi) - case sf != nil: - sf.index = fi - dm.scalars = append(dm.scalars, *sf) - } - } - - return dm -} - -// fieldDefault returns the scalarField for field type ft. -// sf will be nil if the field can not have a default. -// nestedMessage will be true if this is a nested message. -// Note that sf.index is not set on return. -func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) { - var canHaveDefault bool - switch ft.Kind() { - case reflect.Ptr: - if ft.Elem().Kind() == reflect.Struct { - nestedMessage = true - } else { - canHaveDefault = true // proto2 scalar field - } - - case reflect.Slice: - switch ft.Elem().Kind() { - case reflect.Ptr: - nestedMessage = true // repeated message - case reflect.Uint8: - canHaveDefault = true // bytes field - } - - case reflect.Map: - if ft.Elem().Kind() == reflect.Ptr { - nestedMessage = true // map with message values - } - } - - if !canHaveDefault { - if nestedMessage { - return nil, true, nil - } - return nil, false, nil - } - - // We now know that ft is a pointer or slice. - sf = &scalarField{kind: ft.Elem().Kind()} - - // scalar fields without defaults - if !prop.HasDefault { - return sf, false, nil - } - - // a scalar field: either *T or []byte - switch ft.Elem().Kind() { - case reflect.Bool: - x, err := strconv.ParseBool(prop.Default) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Float32: - x, err := strconv.ParseFloat(prop.Default, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err) - } - sf.value = float32(x) - case reflect.Float64: - x, err := strconv.ParseFloat(prop.Default, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.Int32: - x, err := strconv.ParseInt(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err) - } - sf.value = int32(x) - case reflect.Int64: - x, err := strconv.ParseInt(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err) - } - sf.value = x - case reflect.String: - sf.value = prop.Default - case reflect.Uint8: - // []byte (not *uint8) - sf.value = []byte(prop.Default) - case reflect.Uint32: - x, err := strconv.ParseUint(prop.Default, 10, 32) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err) - } - sf.value = uint32(x) - case reflect.Uint64: - x, err := strconv.ParseUint(prop.Default, 10, 64) - if err != nil { - return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err) - } - sf.value = x - default: - return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind()) - } - - return sf, false, nil -} - -// 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. - -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()) - }, - } - - // 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 -} - -// 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/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go deleted file mode 100644 index e25e01e63..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go +++ /dev/null @@ -1,280 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Support for message sets. - */ - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "reflect" - "sort" -) - -// 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") - -// 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 { -// required int32 type_id = 2; -// required string message = 3; -// }; -// } -// 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. - -type _MessageSet_Item struct { - TypeId *int32 `protobuf:"varint,2,req,name=type_id"` - Message []byte `protobuf:"bytes,3,req,name=message"` -} - -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) - -// messageTypeIder is an interface satisfied by a protocol buffer type -// that may be stored in a MessageSet. -type messageTypeIder interface { - MessageTypeId() int32 -} - -func (ms *messageSet) find(pb Message) *_MessageSet_Item { - mti, ok := pb.(messageTypeIder) - if !ok { - return nil - } - id := mti.MessageTypeId() - for _, item := range ms.Item { - if *item.TypeId == id { - return item - } - } - return nil -} - -func (ms *messageSet) Has(pb Message) bool { - if ms.find(pb) != nil { - return true - } - return false -} - -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 nil // TODO: return error instead? -} - -func (ms *messageSet) Marshal(pb Message) error { - msg, err := Marshal(pb) - if err != nil { - return err - } - if item := ms.find(pb); item != nil { - // reuse existing item - item.Message = msg - return nil - } - - mti, ok := pb.(messageTypeIder) - if !ok { - return errNoMessageTypeID - } - - mtid := mti.MessageTypeId() - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: &mtid, - Message: msg, - }) - return nil -} - -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. - -func skipVarint(buf []byte) []byte { - i := 0 - for ; buf[i]&0x80 != 0; i++ { - } - return buf[i+1:] -} - -// 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 - } - - // Sort extension IDs to provide a deterministic encoding. - // See also enc_map in encode.go. - ids := make([]int, 0, len(m)) - for id := range m { - ids = append(ids, int(id)) - } - sort.Ints(ids) - - 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. - msg := skipVarint(skipVarint(e.enc)) - - ms.Item = append(ms.Item, &_MessageSet_Item{ - TypeId: Int32(int32(id)), - Message: msg, - }) - } - return Marshal(ms) -} - -// 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) - if err := Unmarshal(buf, ms); err != nil { - return err - } - for _, item := range ms.Item { - id := *item.TypeId - msg := item.Message - - // Restore wire type and field number varint, plus length varint. - // Be careful to preserve duplicate items. - b := EncodeVarint(uint64(id)<<3 | WireBytes) - if ext, ok := m[id]; ok { - // Existing data; rip off the tag and length varint - // so we join the new data correctly. - // We can assume that ext.enc is set because we are unmarshaling. - o := ext.enc[len(b):] // skip wire type and field number - _, n := DecodeVarint(o) // calculate length of length varint - o = o[n:] // skip length varint - msg = append(o, msg...) // join old data and new data - } - b = append(b, EncodeVarint(uint64(len(msg)))...) - b = append(b, msg...) - - m[id] = Extension{enc: b} - } - return nil -} - -// 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) { - var b bytes.Buffer - b.WriteByte('{') - - // Process the map in key order for deterministic output. - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) // int32Slice defined in text.go - - for i, id := range ids { - ext := m[id] - if i > 0 { - b.WriteByte(',') - } - - msd, ok := messageSetMap[id] - if !ok { - // Unknown type; we can't render it, so skip it. - continue - } - fmt.Fprintf(&b, `"[%s]":`, msd.name) - - x := ext.value - if x == nil { - x = reflect.New(msd.t.Elem()).Interface() - if err := Unmarshal(ext.enc, x.(Message)); err != nil { - return nil, err - } - } - d, err := json.Marshal(x) - if err != nil { - return nil, err - } - b.Write(d) - } - b.WriteByte('}') - return b.Bytes(), nil -} - -// 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 { - // Common-case fast path. - if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) { - return nil - } - - // This is fairly tricky, and it's not clear that it is needed. - return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented") -} - -// A global registry of types that can be used in a MessageSet. - -var messageSetMap = make(map[int32]messageSetDesc) - -type messageSetDesc struct { - t reflect.Type // pointer to struct - name string -} - -// RegisterMessageSetType is called from the generated code. -func RegisterMessageSetType(m Message, fieldNum int32, name string) { - messageSetMap[fieldNum] = messageSetDesc{ - t: reflect.TypeOf(m), - name: name, - } -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go deleted file mode 100644 index 989914177..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go +++ /dev/null @@ -1,479 +0,0 @@ -// 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. - -// +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 -// be used on App Engine. - -package proto - -import ( - "math" - "reflect" -) - -// A structPointer is a pointer to a struct. -type structPointer struct { - v reflect.Value -} - -// toStructPointer returns a structPointer equivalent to the given reflect value. -// The reflect value must itself be a pointer to a struct. -func toStructPointer(v reflect.Value) structPointer { - return structPointer{v} -} - -// IsNil reports whether p is nil. -func structPointer_IsNil(p structPointer) bool { - return p.v.IsNil() -} - -// Interface returns the struct pointer as an interface value. -func structPointer_Interface(p structPointer, _ reflect.Type) interface{} { - return p.v.Interface() -} - -// A field identifies a field in a struct, accessible from a structPointer. -// In this implementation, a field is identified by the sequence of field indices -// passed to reflect's FieldByIndex. -type field []int - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return f.Index -} - -// invalidField is an invalid field identifier. -var invalidField = field(nil) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { return f != nil } - -// field returns the given field in the struct as a reflect value. -func structPointer_field(p structPointer, f field) reflect.Value { - // Special case: an extension map entry with a value of type T - // passes a *T to the struct-handling code with a zero field, - // expecting that it will be treated as equivalent to *struct{ X T }, - // which has the same memory layout. We have to handle that case - // specially, because reflect will panic if we call FieldByIndex on a - // non-struct. - if f == nil { - return p.v.Elem() - } - - return p.v.Elem().FieldByIndex(f) -} - -// ifield returns the given field in the struct as an interface value. -func structPointer_ifield(p structPointer, f field) interface{} { - return structPointer_field(p, f).Addr().Interface() -} - -// Bytes returns the address of a []byte field in the struct. -func structPointer_Bytes(p structPointer, f field) *[]byte { - return structPointer_ifield(p, f).(*[]byte) -} - -// BytesSlice returns the address of a [][]byte field in the struct. -func structPointer_BytesSlice(p structPointer, f field) *[][]byte { - return structPointer_ifield(p, f).(*[][]byte) -} - -// Bool returns the address of a *bool field in the struct. -func structPointer_Bool(p structPointer, f field) **bool { - return structPointer_ifield(p, f).(**bool) -} - -// BoolVal returns the address of a bool field in the struct. -func structPointer_BoolVal(p structPointer, f field) *bool { - return structPointer_ifield(p, f).(*bool) -} - -// BoolSlice returns the address of a []bool field in the struct. -func structPointer_BoolSlice(p structPointer, f field) *[]bool { - return structPointer_ifield(p, f).(*[]bool) -} - -// String returns the address of a *string field in the struct. -func structPointer_String(p structPointer, f field) **string { - return structPointer_ifield(p, f).(**string) -} - -// StringVal returns the address of a string field in the struct. -func structPointer_StringVal(p structPointer, f field) *string { - return structPointer_ifield(p, f).(*string) -} - -// StringSlice returns the address of a []string field in the struct. -func structPointer_StringSlice(p structPointer, f field) *[]string { - return structPointer_ifield(p, f).(*[]string) -} - -// 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) -} - -// 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() -} - -// SetStructPointer writes a *struct field in the struct. -func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { - structPointer_field(p, f).Set(q.v) -} - -// GetStructPointer reads a *struct field in the struct. -func structPointer_GetStructPointer(p structPointer, f field) structPointer { - return structPointer{structPointer_field(p, f)} -} - -// StructPointerSlice the address of a []*struct field in the struct. -func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice { - return structPointerSlice{structPointer_field(p, f)} -} - -// A structPointerSlice represents the address of a slice of pointers to structs -// (themselves messages or groups). That is, v.Type() is *[]*struct{...}. -type structPointerSlice struct { - v reflect.Value -} - -func (p structPointerSlice) Len() int { return p.v.Len() } -func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} } -func (p structPointerSlice) Append(q structPointer) { - p.v.Set(reflect.Append(p.v, q.v)) -} - -var ( - int32Type = reflect.TypeOf(int32(0)) - uint32Type = reflect.TypeOf(uint32(0)) - float32Type = reflect.TypeOf(float32(0)) - int64Type = reflect.TypeOf(int64(0)) - uint64Type = reflect.TypeOf(uint64(0)) - float64Type = reflect.TypeOf(float64(0)) -) - -// A word32 represents a field of type *int32, *uint32, *float32, or *enum. -// That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable. -type word32 struct { - v reflect.Value -} - -// IsNil reports whether p is nil. -func word32_IsNil(p word32) bool { - return p.v.IsNil() -} - -// Set sets p to point at a newly allocated word with bits set to x. -func word32_Set(p word32, o *Buffer, x uint32) { - t := p.v.Type().Elem() - switch t { - case int32Type: - if len(o.int32s) == 0 { - o.int32s = make([]int32, uint32PoolSize) - } - o.int32s[0] = int32(x) - p.v.Set(reflect.ValueOf(&o.int32s[0])) - o.int32s = o.int32s[1:] - return - case uint32Type: - if len(o.uint32s) == 0 { - o.uint32s = make([]uint32, uint32PoolSize) - } - o.uint32s[0] = x - p.v.Set(reflect.ValueOf(&o.uint32s[0])) - o.uint32s = o.uint32s[1:] - return - case float32Type: - if len(o.float32s) == 0 { - o.float32s = make([]float32, uint32PoolSize) - } - o.float32s[0] = math.Float32frombits(x) - p.v.Set(reflect.ValueOf(&o.float32s[0])) - o.float32s = o.float32s[1:] - return - } - - // must be enum - p.v.Set(reflect.New(t)) - p.v.Elem().SetInt(int64(int32(x))) -} - -// Get gets the bits pointed at by p, as a uint32. -func word32_Get(p word32) uint32 { - elem := p.v.Elem() - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") -} - -// Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32(p structPointer, f field) word32 { - return word32{structPointer_field(p, f)} -} - -// A word32Val represents a field of type int32, uint32, float32, or enum. -// That is, v.Type() is int32, uint32, float32, or enum and v is assignable. -type word32Val struct { - v reflect.Value -} - -// Set sets *p to x. -func word32Val_Set(p word32Val, x uint32) { - switch p.v.Type() { - case int32Type: - p.v.SetInt(int64(x)) - return - case uint32Type: - p.v.SetUint(uint64(x)) - return - case float32Type: - p.v.SetFloat(float64(math.Float32frombits(x))) - return - } - - // must be enum - p.v.SetInt(int64(int32(x))) -} - -// Get gets the bits pointed at by p, as a uint32. -func word32Val_Get(p word32Val) uint32 { - elem := p.v - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") -} - -// Word32Val returns a reference to a int32, uint32, float32, or enum field in the struct. -func structPointer_Word32Val(p structPointer, f field) word32Val { - return word32Val{structPointer_field(p, f)} -} - -// A word32Slice is a slice of 32-bit values. -// That is, v.Type() is []int32, []uint32, []float32, or []enum. -type word32Slice struct { - v reflect.Value -} - -func (p word32Slice) Append(x uint32) { - n, m := p.v.Len(), p.v.Cap() - if n < m { - p.v.SetLen(n + 1) - } else { - t := p.v.Type().Elem() - p.v.Set(reflect.Append(p.v, reflect.Zero(t))) - } - elem := p.v.Index(n) - switch elem.Kind() { - case reflect.Int32: - elem.SetInt(int64(int32(x))) - case reflect.Uint32: - elem.SetUint(uint64(x)) - case reflect.Float32: - elem.SetFloat(float64(math.Float32frombits(x))) - } -} - -func (p word32Slice) Len() int { - return p.v.Len() -} - -func (p word32Slice) Index(i int) uint32 { - elem := p.v.Index(i) - switch elem.Kind() { - case reflect.Int32: - return uint32(elem.Int()) - case reflect.Uint32: - return uint32(elem.Uint()) - case reflect.Float32: - return math.Float32bits(float32(elem.Float())) - } - panic("unreachable") -} - -// Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct. -func structPointer_Word32Slice(p structPointer, f field) word32Slice { - return word32Slice{structPointer_field(p, f)} -} - -// word64 is like word32 but for 64-bit values. -type word64 struct { - v reflect.Value -} - -func word64_Set(p word64, o *Buffer, x uint64) { - t := p.v.Type().Elem() - switch t { - case int64Type: - if len(o.int64s) == 0 { - o.int64s = make([]int64, uint64PoolSize) - } - o.int64s[0] = int64(x) - p.v.Set(reflect.ValueOf(&o.int64s[0])) - o.int64s = o.int64s[1:] - return - case uint64Type: - if len(o.uint64s) == 0 { - o.uint64s = make([]uint64, uint64PoolSize) - } - o.uint64s[0] = x - p.v.Set(reflect.ValueOf(&o.uint64s[0])) - o.uint64s = o.uint64s[1:] - return - case float64Type: - if len(o.float64s) == 0 { - o.float64s = make([]float64, uint64PoolSize) - } - o.float64s[0] = math.Float64frombits(x) - p.v.Set(reflect.ValueOf(&o.float64s[0])) - o.float64s = o.float64s[1:] - return - } - panic("unreachable") -} - -func word64_IsNil(p word64) bool { - return p.v.IsNil() -} - -func word64_Get(p word64) uint64 { - elem := p.v.Elem() - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return elem.Uint() - case reflect.Float64: - return math.Float64bits(elem.Float()) - } - panic("unreachable") -} - -func structPointer_Word64(p structPointer, f field) word64 { - return word64{structPointer_field(p, f)} -} - -// word64Val is like word32Val but for 64-bit values. -type word64Val struct { - v reflect.Value -} - -func word64Val_Set(p word64Val, o *Buffer, x uint64) { - switch p.v.Type() { - case int64Type: - p.v.SetInt(int64(x)) - return - case uint64Type: - p.v.SetUint(x) - return - case float64Type: - p.v.SetFloat(math.Float64frombits(x)) - return - } - panic("unreachable") -} - -func word64Val_Get(p word64Val) uint64 { - elem := p.v - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return elem.Uint() - case reflect.Float64: - return math.Float64bits(elem.Float()) - } - panic("unreachable") -} - -func structPointer_Word64Val(p structPointer, f field) word64Val { - return word64Val{structPointer_field(p, f)} -} - -type word64Slice struct { - v reflect.Value -} - -func (p word64Slice) Append(x uint64) { - n, m := p.v.Len(), p.v.Cap() - if n < m { - p.v.SetLen(n + 1) - } else { - t := p.v.Type().Elem() - p.v.Set(reflect.Append(p.v, reflect.Zero(t))) - } - elem := p.v.Index(n) - switch elem.Kind() { - case reflect.Int64: - elem.SetInt(int64(int64(x))) - case reflect.Uint64: - elem.SetUint(uint64(x)) - case reflect.Float64: - elem.SetFloat(float64(math.Float64frombits(x))) - } -} - -func (p word64Slice) Len() int { - return p.v.Len() -} - -func (p word64Slice) Index(i int) uint64 { - elem := p.v.Index(i) - switch elem.Kind() { - case reflect.Int64: - return uint64(elem.Int()) - case reflect.Uint64: - return uint64(elem.Uint()) - case reflect.Float64: - return math.Float64bits(float64(elem.Float())) - } - panic("unreachable") -} - -func structPointer_Word64Slice(p structPointer, f field) word64Slice { - return word64Slice{structPointer_field(p, f)} -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go deleted file mode 100644 index ceece772a..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go +++ /dev/null @@ -1,266 +0,0 @@ -// 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. - -// +build !appengine,!js - -// This file contains the implementation of the proto field accesses using package unsafe. - -package proto - -import ( - "reflect" - "unsafe" -) - -// NOTE: These type_Foo functions would more idiomatically be methods, -// but Go does not allow methods on pointer types, and we must preserve -// some pointer type for the garbage collector. We use these -// funcs with clunky names as our poor approximation to methods. -// -// An alternative would be -// type structPointer struct { p unsafe.Pointer } -// but that does not registerize as well. - -// A structPointer is a pointer to a struct. -type structPointer unsafe.Pointer - -// toStructPointer returns a structPointer equivalent to the given reflect value. -func toStructPointer(v reflect.Value) structPointer { - return structPointer(unsafe.Pointer(v.Pointer())) -} - -// IsNil reports whether p is nil. -func structPointer_IsNil(p structPointer) bool { - return p == nil -} - -// Interface returns the struct pointer, assumed to have element type t, -// as an interface value. -func structPointer_Interface(p structPointer, t reflect.Type) interface{} { - return reflect.NewAt(t, unsafe.Pointer(p)).Interface() -} - -// A field identifies a field in a struct, accessible from a structPointer. -// In this implementation, a field is identified by its byte offset from the start of the struct. -type field uintptr - -// toField returns a field equivalent to the given reflect field. -func toField(f *reflect.StructField) field { - return field(f.Offset) -} - -// invalidField is an invalid field identifier. -const invalidField = ^field(0) - -// IsValid reports whether the field identifier is valid. -func (f field) IsValid() bool { - return f != ^field(0) -} - -// Bytes returns the address of a []byte field in the struct. -func structPointer_Bytes(p structPointer, f field) *[]byte { - return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// BytesSlice returns the address of a [][]byte field in the struct. -func structPointer_BytesSlice(p structPointer, f field) *[][]byte { - return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// Bool returns the address of a *bool field in the struct. -func structPointer_Bool(p structPointer, f field) **bool { - return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// BoolVal returns the address of a bool field in the struct. -func structPointer_BoolVal(p structPointer, f field) *bool { - return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// BoolSlice returns the address of a []bool field in the struct. -func structPointer_BoolSlice(p structPointer, f field) *[]bool { - return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// String returns the address of a *string field in the struct. -func structPointer_String(p structPointer, f field) **string { - return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// StringVal returns the address of a string field in the struct. -func structPointer_StringVal(p structPointer, f field) *string { - return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// StringSlice returns the address of a []string field in the struct. -func structPointer_StringSlice(p structPointer, f field) *[]string { - return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// ExtMap returns the address of an extension map field in the struct. -func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { - return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// 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))) -} - -// SetStructPointer writes a *struct field in the struct. -func structPointer_SetStructPointer(p structPointer, f field, q structPointer) { - *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q -} - -// GetStructPointer reads a *struct field in the struct. -func structPointer_GetStructPointer(p structPointer, f field) structPointer { - return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// StructPointerSlice the address of a []*struct field in the struct. -func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice { - return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups). -type structPointerSlice []structPointer - -func (v *structPointerSlice) Len() int { return len(*v) } -func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] } -func (v *structPointerSlice) Append(p structPointer) { *v = append(*v, p) } - -// A word32 is the address of a "pointer to 32-bit value" field. -type word32 **uint32 - -// IsNil reports whether *v is nil. -func word32_IsNil(p word32) bool { - return *p == nil -} - -// Set sets *v to point at a newly allocated word set to x. -func word32_Set(p word32, o *Buffer, x uint32) { - if len(o.uint32s) == 0 { - o.uint32s = make([]uint32, uint32PoolSize) - } - o.uint32s[0] = x - *p = &o.uint32s[0] - o.uint32s = o.uint32s[1:] -} - -// Get gets the value pointed at by *v. -func word32_Get(p word32) uint32 { - return **p -} - -// Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32(p structPointer, f field) word32 { - return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) -} - -// A word32Val is the address of a 32-bit value field. -type word32Val *uint32 - -// Set sets *p to x. -func word32Val_Set(p word32Val, x uint32) { - *p = x -} - -// Get gets the value pointed at by p. -func word32Val_Get(p word32Val) uint32 { - return *p -} - -// Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct. -func structPointer_Word32Val(p structPointer, f field) word32Val { - return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f)))) -} - -// A word32Slice is a slice of 32-bit values. -type word32Slice []uint32 - -func (v *word32Slice) Append(x uint32) { *v = append(*v, x) } -func (v *word32Slice) Len() int { return len(*v) } -func (v *word32Slice) Index(i int) uint32 { return (*v)[i] } - -// Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct. -func structPointer_Word32Slice(p structPointer, f field) *word32Slice { - return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} - -// word64 is like word32 but for 64-bit values. -type word64 **uint64 - -func word64_Set(p word64, o *Buffer, x uint64) { - if len(o.uint64s) == 0 { - o.uint64s = make([]uint64, uint64PoolSize) - } - o.uint64s[0] = x - *p = &o.uint64s[0] - o.uint64s = o.uint64s[1:] -} - -func word64_IsNil(p word64) bool { - return *p == nil -} - -func word64_Get(p word64) uint64 { - return **p -} - -func structPointer_Word64(p structPointer, f field) word64 { - return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) -} - -// word64Val is like word32Val but for 64-bit values. -type word64Val *uint64 - -func word64Val_Set(p word64Val, o *Buffer, x uint64) { - *p = x -} - -func word64Val_Get(p word64Val) uint64 { - return *p -} - -func structPointer_Word64Val(p structPointer, f field) word64Val { - return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f)))) -} - -// word64Slice is like word32Slice but for 64-bit values. -type word64Slice []uint64 - -func (v *word64Slice) Append(x uint64) { *v = append(*v, x) } -func (v *word64Slice) Len() int { return len(*v) } -func (v *word64Slice) Index(i int) uint64 { return (*v)[i] } - -func structPointer_Word64Slice(p structPointer, f field) *word64Slice { - return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f))) -} diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go deleted file mode 100644 index 4fe2ec22e..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go +++ /dev/null @@ -1,846 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -/* - * Routines for encoding data into the wire format for protocol buffers. - */ - -import ( - "fmt" - "log" - "os" - "reflect" - "sort" - "strconv" - "strings" - "sync" -) - -const debug bool = false - -// Constants that identify the encoding of a value on the wire. -const ( - WireVarint = 0 - WireFixed64 = 1 - WireBytes = 2 - WireStartGroup = 3 - WireEndGroup = 4 - WireFixed32 = 5 -) - -const startSize = 10 // initial slice/string sizes - -// Encoders are defined in encode.go -// An encoder outputs the full representation of a field, including its -// tag and encoder type. -type encoder func(p *Buffer, prop *Properties, base structPointer) error - -// A valueEncoder encodes a single integer in a particular encoding. -type valueEncoder func(o *Buffer, x uint64) error - -// Sizers are defined in encode.go -// A sizer returns the encoded size of a field, including its tag and encoder -// type. -type sizer func(prop *Properties, base structPointer) int - -// A valueSizer returns the encoded size of a single integer in a particular -// encoding. -type valueSizer func(x uint64) int - -// Decoders are defined in decode.go -// A decoder creates a value from its wire representation. -// Unrecognized subelements are saved in unrec. -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. -type tagMap struct { - fastTags []int - slowTags map[int]int -} - -// tagMapFastLimit is the upper bound on the tag number that will be stored in -// the tagMap slice rather than its map. -const tagMapFastLimit = 1024 - -func (p *tagMap) get(t int) (int, bool) { - if t > 0 && t < tagMapFastLimit { - if t >= len(p.fastTags) { - return 0, false - } - fi := p.fastTags[t] - return fi, fi >= 0 - } - fi, ok := p.slowTags[t] - return fi, ok -} - -func (p *tagMap) put(t int, fi int) { - if t > 0 && t < tagMapFastLimit { - for len(p.fastTags) < t+1 { - p.fastTags = append(p.fastTags, -1) - } - p.fastTags[t] = fi - return - } - if p.slowTags == nil { - p.slowTags = make(map[int]int) - } - p.slowTags[t] = fi -} - -// StructProperties represents properties for all the fields of a struct. -// decoderTags and decoderOrigNames should only be used by the decoder. -type StructProperties struct { - Prop []*Properties // properties for each field - reqCount int // required count - decoderTags tagMap // map from proto tag to struct field number - decoderOrigNames map[string]int // map from original name to struct field number - 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. -// See encode.go, (*Buffer).enc_struct. - -func (sp *StructProperties) Len() int { return len(sp.order) } -func (sp *StructProperties) Less(i, j int) bool { - return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag -} -func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] } - -// Properties represents the protocol-specific behavior of a single struct field. -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 - Required bool - Optional bool - Repeated bool - 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 - def_uint64 uint64 - - enc encoder - valEnc valueEncoder // set for bool and numeric types only - field field - tagcode []byte // encoding of EncodeVarint((Tag<<3)|WireType) - tagbuf [8]byte - stype reflect.Type // set for struct types only - sprop *StructProperties // set for struct types only - isMarshaler bool - isUnmarshaler bool - - mtype reflect.Type // set for map types only - mkeyprop *Properties // set for map types only - mvalprop *Properties // set for map types only - - size sizer - valSize valueSizer // set for bool and numeric types only - - dec decoder - valDec valueDecoder // set for bool and numeric types only - - // If this is a packable field, this will be the decoder for the packed version of the field. - packedDec decoder -} - -// String formats the properties in the protobuf struct field tag style. -func (p *Properties) String() string { - s := p.Wire - s = "," - s += strconv.Itoa(p.Tag) - if p.Required { - s += ",req" - } - if p.Optional { - s += ",opt" - } - if p.Repeated { - s += ",rep" - } - if p.Packed { - s += ",packed" - } - 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 - } - if p.HasDefault { - s += ",def=" + p.Default - } - return s -} - -// Parse populates p by parsing a string in the protobuf struct field tag style. -func (p *Properties) Parse(s string) { - // "bytes,49,opt,name=foo,def=hello!" - fields := strings.Split(s, ",") // breaks def=, but handled below. - if len(fields) < 2 { - fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s) - return - } - - p.Wire = fields[0] - switch p.Wire { - case "varint": - p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeVarint - p.valDec = (*Buffer).DecodeVarint - p.valSize = sizeVarint - case "fixed32": - p.WireType = WireFixed32 - p.valEnc = (*Buffer).EncodeFixed32 - p.valDec = (*Buffer).DecodeFixed32 - p.valSize = sizeFixed32 - case "fixed64": - p.WireType = WireFixed64 - p.valEnc = (*Buffer).EncodeFixed64 - p.valDec = (*Buffer).DecodeFixed64 - p.valSize = sizeFixed64 - case "zigzag32": - p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeZigzag32 - p.valDec = (*Buffer).DecodeZigzag32 - p.valSize = sizeZigzag32 - case "zigzag64": - p.WireType = WireVarint - p.valEnc = (*Buffer).EncodeZigzag64 - p.valDec = (*Buffer).DecodeZigzag64 - p.valSize = sizeZigzag64 - case "bytes", "group": - p.WireType = WireBytes - // no numeric converter for non-numeric types - default: - fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s) - return - } - - var err error - p.Tag, err = strconv.Atoi(fields[1]) - if err != nil { - return - } - - for i := 2; i < len(fields); i++ { - f := fields[i] - switch { - case f == "req": - p.Required = true - case f == "opt": - p.Optional = true - case f == "rep": - p.Repeated = true - case f == "packed": - 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 - if i+1 < len(fields) { - // Commas aren't escaped, and def is always last. - p.Default += "," + strings.Join(fields[i+1:], ",") - break - } - } - } -} - -func logNoSliceEnc(t1, t2 reflect.Type) { - fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2) -} - -var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem() - -// Initialize the fields for encoding and decoding. -func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) { - p.enc = nil - p.dec = nil - p.size = nil - - switch t1 := typ; t1.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1) - - // proto3 scalar types - - case reflect.Bool: - p.enc = (*Buffer).enc_proto3_bool - p.dec = (*Buffer).dec_proto3_bool - p.size = size_proto3_bool - case reflect.Int32: - p.enc = (*Buffer).enc_proto3_int32 - p.dec = (*Buffer).dec_proto3_int32 - p.size = size_proto3_int32 - case reflect.Uint32: - p.enc = (*Buffer).enc_proto3_uint32 - p.dec = (*Buffer).dec_proto3_int32 // can reuse - p.size = size_proto3_uint32 - case reflect.Int64, reflect.Uint64: - p.enc = (*Buffer).enc_proto3_int64 - p.dec = (*Buffer).dec_proto3_int64 - p.size = size_proto3_int64 - case reflect.Float32: - p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits - p.dec = (*Buffer).dec_proto3_int32 - p.size = size_proto3_uint32 - case reflect.Float64: - p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits - p.dec = (*Buffer).dec_proto3_int64 - p.size = size_proto3_int64 - case reflect.String: - p.enc = (*Buffer).enc_proto3_string - p.dec = (*Buffer).dec_proto3_string - p.size = size_proto3_string - - case reflect.Ptr: - switch t2 := t1.Elem(); t2.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2) - break - case reflect.Bool: - p.enc = (*Buffer).enc_bool - p.dec = (*Buffer).dec_bool - p.size = size_bool - case reflect.Int32: - p.enc = (*Buffer).enc_int32 - p.dec = (*Buffer).dec_int32 - p.size = size_int32 - case reflect.Uint32: - p.enc = (*Buffer).enc_uint32 - p.dec = (*Buffer).dec_int32 // can reuse - p.size = size_uint32 - case reflect.Int64, reflect.Uint64: - p.enc = (*Buffer).enc_int64 - p.dec = (*Buffer).dec_int64 - p.size = size_int64 - case reflect.Float32: - p.enc = (*Buffer).enc_uint32 // can just treat them as bits - p.dec = (*Buffer).dec_int32 - p.size = size_uint32 - case reflect.Float64: - p.enc = (*Buffer).enc_int64 // can just treat them as bits - p.dec = (*Buffer).dec_int64 - p.size = size_int64 - case reflect.String: - p.enc = (*Buffer).enc_string - p.dec = (*Buffer).dec_string - p.size = size_string - case reflect.Struct: - p.stype = t1.Elem() - p.isMarshaler = isMarshaler(t1) - p.isUnmarshaler = isUnmarshaler(t1) - if p.Wire == "bytes" { - p.enc = (*Buffer).enc_struct_message - p.dec = (*Buffer).dec_struct_message - p.size = size_struct_message - } else { - p.enc = (*Buffer).enc_struct_group - p.dec = (*Buffer).dec_struct_group - p.size = size_struct_group - } - } - - case reflect.Slice: - switch t2 := t1.Elem(); t2.Kind() { - default: - logNoSliceEnc(t1, t2) - break - case reflect.Bool: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_bool - p.size = size_slice_packed_bool - } else { - p.enc = (*Buffer).enc_slice_bool - p.size = size_slice_bool - } - p.dec = (*Buffer).dec_slice_bool - p.packedDec = (*Buffer).dec_slice_packed_bool - case reflect.Int32: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int32 - p.size = size_slice_packed_int32 - } else { - p.enc = (*Buffer).enc_slice_int32 - p.size = size_slice_int32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case reflect.Uint32: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_uint32 - p.size = size_slice_packed_uint32 - } else { - p.enc = (*Buffer).enc_slice_uint32 - p.size = size_slice_uint32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case reflect.Int64, reflect.Uint64: - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int64 - p.size = size_slice_packed_int64 - } else { - p.enc = (*Buffer).enc_slice_int64 - p.size = size_slice_int64 - } - 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 { - p.enc = (*Buffer).enc_proto3_slice_byte - p.size = size_proto3_slice_byte - } - case reflect.Float32, reflect.Float64: - switch t2.Bits() { - case 32: - // can just treat them as bits - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_uint32 - p.size = size_slice_packed_uint32 - } else { - p.enc = (*Buffer).enc_slice_uint32 - p.size = size_slice_uint32 - } - p.dec = (*Buffer).dec_slice_int32 - p.packedDec = (*Buffer).dec_slice_packed_int32 - case 64: - // can just treat them as bits - if p.Packed { - p.enc = (*Buffer).enc_slice_packed_int64 - p.size = size_slice_packed_int64 - } else { - p.enc = (*Buffer).enc_slice_int64 - p.size = size_slice_int64 - } - p.dec = (*Buffer).dec_slice_int64 - p.packedDec = (*Buffer).dec_slice_packed_int64 - default: - logNoSliceEnc(t1, t2) - break - } - case reflect.String: - p.enc = (*Buffer).enc_slice_string - p.dec = (*Buffer).dec_slice_string - p.size = size_slice_string - case reflect.Ptr: - switch t3 := t2.Elem(); t3.Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3) - break - case reflect.Struct: - p.stype = t2.Elem() - p.isMarshaler = isMarshaler(t2) - p.isUnmarshaler = isUnmarshaler(t2) - if p.Wire == "bytes" { - p.enc = (*Buffer).enc_slice_struct_message - p.dec = (*Buffer).dec_slice_struct_message - p.size = size_slice_struct_message - } else { - p.enc = (*Buffer).enc_slice_struct_group - p.dec = (*Buffer).dec_slice_struct_group - p.size = size_slice_struct_group - } - } - case reflect.Slice: - switch t2.Elem().Kind() { - default: - fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem()) - break - case reflect.Uint8: - p.enc = (*Buffer).enc_slice_slice_byte - p.dec = (*Buffer).dec_slice_slice_byte - p.size = size_slice_slice_byte - } - } - - case reflect.Map: - p.enc = (*Buffer).enc_new_map - p.dec = (*Buffer).dec_new_map - p.size = size_new_map - - p.mtype = t1 - p.mkeyprop = &Properties{} - p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp) - p.mvalprop = &Properties{} - vtype := p.mtype.Elem() - if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice { - // The value type is not a message (*T) or bytes ([]byte), - // so we need encoders for the pointer to this type. - vtype = reflect.PtrTo(vtype) - } - p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp) - } - - // precalculate tag code - wire := p.WireType - if p.Packed { - wire = WireBytes - } - x := uint32(p.Tag)<<3 | uint32(wire) - i := 0 - for i = 0; x > 127; i++ { - p.tagbuf[i] = 0x80 | uint8(x&0x7F) - x >>= 7 - } - p.tagbuf[i] = uint8(x) - p.tagcode = p.tagbuf[0 : i+1] - - if p.stype != nil { - if lockGetProp { - p.sprop = GetProperties(p.stype) - } else { - p.sprop = getPropertiesLocked(p.stype) - } - } -} - -var ( - marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem() - unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem() -) - -// isMarshaler reports whether type t implements Marshaler. -func isMarshaler(t reflect.Type) bool { - // We're checking for (likely) pointer-receiver methods - // so if t is not a pointer, something is very wrong. - // The calls above only invoke isMarshaler on pointer types. - if t.Kind() != reflect.Ptr { - panic("proto: misuse of isMarshaler") - } - return t.Implements(marshalerType) -} - -// isUnmarshaler reports whether type t implements Unmarshaler. -func isUnmarshaler(t reflect.Type) bool { - // We're checking for (likely) pointer-receiver methods - // so if t is not a pointer, something is very wrong. - // The calls above only invoke isUnmarshaler on pointer types. - if t.Kind() != reflect.Ptr { - panic("proto: misuse of isUnmarshaler") - } - return t.Implements(unmarshalerType) -} - -// Init populates the properties from a protocol buffer struct tag. -func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) { - p.init(typ, name, tag, f, true) -} - -func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) { - // "bytes,49,opt,def=hello!" - p.Name = name - p.OrigName = name - if f != nil { - p.field = toField(f) - } - if tag == "" { - return - } - p.Parse(tag) - p.setEncAndDec(typ, f, lockGetProp) -} - -var ( - propertiesMu sync.RWMutex - propertiesMap = make(map[reflect.Type]*StructProperties) -) - -// GetProperties returns the list of properties for the type represented by t. -// t must represent a generated struct type of a protocol message. -func GetProperties(t reflect.Type) *StructProperties { - if t.Kind() != reflect.Struct { - panic("proto: type must have kind struct") - } - - // Most calls to GetProperties in a long-running program will be - // retrieving details for types we have seen before. - propertiesMu.RLock() - sprop, ok := propertiesMap[t] - propertiesMu.RUnlock() - if ok { - if collectStats { - stats.Chit++ - } - return sprop - } - - propertiesMu.Lock() - sprop = getPropertiesLocked(t) - propertiesMu.Unlock() - return sprop -} - -// getPropertiesLocked requires that propertiesMu is held. -func getPropertiesLocked(t reflect.Type) *StructProperties { - if prop, ok := propertiesMap[t]; ok { - if collectStats { - stats.Chit++ - } - return prop - } - if collectStats { - stats.Cmiss++ - } - - prop := new(StructProperties) - // in case of recursive protos, fill this in now. - propertiesMap[t] = prop - - // build properties - prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) - prop.unrecField = invalidField - prop.Prop = make([]*Properties, t.NumField()) - prop.order = make([]int, t.NumField()) - - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - p := new(Properties) - name := f.Name - p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) - - 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 - prop.unrecField = toField(&f) - } - oneof := f.Tag.Get("protobuf_oneof") != "" // special case - prop.Prop[i] = p - prop.order[i] = i - if debug { - print(i, " ", f.Name, " ", t.String(), " ") - if p.Tag > 0 { - print(p.String()) - } - print("\n") - } - if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && !oneof { - fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]") - } - } - - // 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 - prop.decoderOrigNames = make(map[string]int) - for i, p := range prop.Prop { - if strings.HasPrefix(p.Name, "XXX_") { - // Internal fields should not appear in tags/origNames maps. - // They are handled specially when encoding and decoding. - continue - } - if p.Required { - reqCount++ - } - prop.decoderTags.put(p.Tag, i) - prop.decoderOrigNames[p.OrigName] = i - } - prop.reqCount = reqCount - - return prop -} - -// Return the Properties object for the x[0]'th field of the structure. -func propByIndex(t reflect.Type, x []int) *Properties { - if len(x) != 1 { - fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t) - return nil - } - prop := GetProperties(t) - return prop.Prop[x[0]] -} - -// Get the address and type of a pointer to a struct from an interface. -func getbase(pb Message) (t reflect.Type, b structPointer, err error) { - if pb == nil { - err = ErrNil - return - } - // get the reflect type of the pointer to the struct. - t = reflect.TypeOf(pb) - // get the address of the struct. - value := reflect.ValueOf(pb) - b = toStructPointer(value) - return -} - -// A global registry of enum types. -// The generated code will register the generated maps by calling RegisterEnum. - -var enumValueMaps = make(map[string]map[string]int32) - -// RegisterEnum is called from the generated code to install the enum descriptor -// maps into the global table to aid parsing text format protocol buffers. -func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) { - if _, ok := enumValueMaps[typeName]; ok { - panic("proto: duplicate enum registered: " + typeName) - } - 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 { 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] } diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go deleted file mode 100644 index 37c953570..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go +++ /dev/null @@ -1,849 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Functions for writing the text protocol buffer format. - -import ( - "bufio" - "bytes" - "encoding" - "errors" - "fmt" - "io" - "log" - "math" - "reflect" - "sort" - "strings" -) - -var ( - newline = []byte("\n") - spaces = []byte(" ") - gtNewline = []byte(">\n") - endBraceNewline = []byte("}\n") - backslashN = []byte{'\\', 'n'} - backslashR = []byte{'\\', 'r'} - backslashT = []byte{'\\', 't'} - backslashDQ = []byte{'\\', '"'} - backslashBS = []byte{'\\', '\\'} - posInf = []byte("inf") - negInf = []byte("-inf") - nan = []byte("nan") -) - -type writer interface { - io.Writer - WriteByte(byte) error -} - -// textWriter is an io.Writer that tracks its indentation level. -type textWriter struct { - ind int - complete bool // if the current position is a complete line - compact bool // whether to write out as a one-liner - w writer -} - -func (w *textWriter) WriteString(s string) (n int, err error) { - if !strings.Contains(s, "\n") { - if !w.compact && w.complete { - w.writeIndent() - } - w.complete = false - return io.WriteString(w.w, s) - } - // WriteString is typically called without newlines, so this - // codepath and its copy are rare. We copy to avoid - // duplicating all of Write's logic here. - return w.Write([]byte(s)) -} - -func (w *textWriter) Write(p []byte) (n int, err error) { - newlines := bytes.Count(p, newline) - if newlines == 0 { - if !w.compact && w.complete { - w.writeIndent() - } - n, err = w.w.Write(p) - w.complete = false - return n, err - } - - frags := bytes.SplitN(p, newline, newlines+1) - if w.compact { - for i, frag := range frags { - if i > 0 { - if err := w.w.WriteByte(' '); err != nil { - return n, err - } - n++ - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - } - return n, nil - } - - for i, frag := range frags { - if w.complete { - w.writeIndent() - } - nn, err := w.w.Write(frag) - n += nn - if err != nil { - return n, err - } - if i+1 < len(frags) { - if err := w.w.WriteByte('\n'); err != nil { - return n, err - } - n++ - } - } - w.complete = len(frags[len(frags)-1]) == 0 - return n, nil -} - -func (w *textWriter) WriteByte(c byte) error { - if w.compact && c == '\n' { - c = ' ' - } - if !w.compact && w.complete { - w.writeIndent() - } - err := w.w.WriteByte(c) - w.complete = c == '\n' - return err -} - -func (w *textWriter) indent() { w.ind++ } - -func (w *textWriter) unindent() { - if w.ind == 0 { - log.Printf("proto: textWriter unindented too far") - return - } - w.ind-- -} - -func writeName(w *textWriter, props *Properties) error { - if _, err := w.WriteString(props.OrigName); err != nil { - return err - } - if props.Wire != "group" { - return w.WriteByte(':') - } - return nil -} - -// raw is the interface satisfied by RawMessage. -type raw interface { - Bytes() []byte -} - -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++ { - fv := sv.Field(i) - props := sprops.Prop[i] - name := st.Field(i).Name - - if strings.HasPrefix(name, "XXX_") { - // There are two XXX_ fields: - // XXX_unrecognized []byte - // XXX_extensions map[int32]proto.Extension - // The first is handled here; - // the second is handled at the bottom of this function. - if name == "XXX_unrecognized" && !fv.IsNil() { - if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Ptr && fv.IsNil() { - // Field not filled in. This could be an optional field or - // a required field that wasn't filled in. Either way, there - // isn't anything we can show for it. - continue - } - if fv.Kind() == reflect.Slice && fv.IsNil() { - // Repeated field that is empty, or a bytes field that is unused. - continue - } - - if props.Repeated && fv.Kind() == reflect.Slice { - // Repeated field. - for j := 0; j < fv.Len(); j++ { - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - v := fv.Index(j) - if v.Kind() == reflect.Ptr && v.IsNil() { - // A nil message in a repeated field is not valid, - // but we can handle that more gracefully than panicking. - if _, err := w.Write([]byte("\n")); err != nil { - return err - } - continue - } - if err := tm.writeAny(w, v, props); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if fv.Kind() == reflect.Map { - // Map fields are rendered as a repeated struct with key/value fields. - keys := fv.MapKeys() - sort.Sort(mapKeys(keys)) - for _, key := range keys { - val := fv.MapIndex(key) - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - // open struct - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - // key - if _, err := w.WriteString("key:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, key, props.mkeyprop); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - // nil values aren't legal, but we can avoid panicking because of them. - if val.Kind() != reflect.Ptr || !val.IsNil() { - // value - if _, err := w.WriteString("value:"); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, val, props.mvalprop); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - // close struct - w.unindent() - if err := w.WriteByte('>'); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - } - continue - } - if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 { - // empty bytes field - continue - } - if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice { - // proto3 non-repeated scalar field; skip if zero value - 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 - } - 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() - } - } - } - - if err := writeName(w, props); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if b, ok := fv.Interface().(raw); ok { - if err := writeRaw(w, b.Bytes()); err != nil { - return err - } - continue - } - - // Enums have a String method, so writeAny will work fine. - if err := tm.writeAny(w, fv, props); err != nil { - return err - } - - if err := w.WriteByte('\n'); err != nil { - return err - } - } - - // Extensions (the XXX_extensions field). - pv := sv.Addr() - if pv.Type().Implements(extendableProtoType) { - if err := tm.writeExtensions(w, pv); err != nil { - return err - } - } - - return nil -} - -// writeRaw writes an uninterpreted raw message. -func writeRaw(w *textWriter, b []byte) error { - if err := w.WriteByte('<'); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - if err := writeUnknownStruct(w, b); err != nil { - return err - } - w.unindent() - if err := w.WriteByte('>'); err != nil { - return err - } - return nil -} - -// writeAny writes an arbitrary field. -func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { - v = reflect.Indirect(v) - - // Floats have special cases. - if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 { - x := v.Float() - var b []byte - switch { - case math.IsInf(x, 1): - b = posInf - case math.IsInf(x, -1): - b = negInf - case math.IsNaN(x): - b = nan - } - if b != nil { - _, err := w.Write(b) - return err - } - // Other values are handled below. - } - - // We don't attempt to serialise every possible value type; only those - // that can occur in protocol buffers. - 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 { - return err - } - case reflect.String: - if err := writeString(w, v.String()); err != nil { - return err - } - case reflect.Struct: - // Required/optional group/message. - var bra, ket byte = '<', '>' - if props != nil && props.Wire == "group" { - bra, ket = '{', '}' - } - if err := w.WriteByte(bra); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte('\n'); err != nil { - return err - } - } - w.indent() - 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 := tm.writeStruct(w, v); err != nil { - return err - } - w.unindent() - if err := w.WriteByte(ket); err != nil { - return err - } - default: - _, err := fmt.Fprint(w, v.Interface()) - return err - } - return nil -} - -// equivalent to C's isprint. -func isprint(c byte) bool { - return c >= 0x20 && c < 0x7f -} - -// writeString writes a string in the protocol buffer text format. -// It is similar to strconv.Quote except we don't use Go escape sequences, -// we treat the string as a byte sequence, and we use octal escapes. -// These differences are to maintain interoperability with the other -// languages' implementations of the text format. -func writeString(w *textWriter, s string) error { - // use WriteByte here to get any needed indent - if err := w.WriteByte('"'); err != nil { - return err - } - // Loop over the bytes, not the runes. - for i := 0; i < len(s); i++ { - var err error - // Divergence from C++: we don't escape apostrophes. - // There's no need to escape them, and the C++ parser - // copes with a naked apostrophe. - switch c := s[i]; c { - case '\n': - _, err = w.w.Write(backslashN) - case '\r': - _, err = w.w.Write(backslashR) - case '\t': - _, err = w.w.Write(backslashT) - case '"': - _, err = w.w.Write(backslashDQ) - case '\\': - _, err = w.w.Write(backslashBS) - default: - if isprint(c) { - err = w.w.WriteByte(c) - } else { - _, err = fmt.Fprintf(w.w, "\\%03o", c) - } - } - if err != nil { - return err - } - } - return w.WriteByte('"') -} - -func writeUnknownStruct(w *textWriter, data []byte) (err error) { - if !w.compact { - if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil { - return err - } - } - b := NewBuffer(data) - for b.index < len(b.buf) { - x, err := b.DecodeVarint() - if err != nil { - _, err := fmt.Fprintf(w, "/* %v */\n", err) - return err - } - wire, tag := x&7, x>>3 - if wire == WireEndGroup { - w.unindent() - if _, err := w.Write(endBraceNewline); err != nil { - return err - } - continue - } - if _, err := fmt.Fprint(w, tag); err != nil { - return err - } - if wire != WireStartGroup { - if err := w.WriteByte(':'); err != nil { - return err - } - } - if !w.compact || wire == WireStartGroup { - if err := w.WriteByte(' '); err != nil { - return err - } - } - switch wire { - case WireBytes: - buf, e := b.DecodeRawBytes(false) - if e == nil { - _, err = fmt.Fprintf(w, "%q", buf) - } else { - _, err = fmt.Fprintf(w, "/* %v */", e) - } - case WireFixed32: - x, err = b.DecodeFixed32() - err = writeUnknownInt(w, x, err) - case WireFixed64: - x, err = b.DecodeFixed64() - err = writeUnknownInt(w, x, err) - case WireStartGroup: - err = w.WriteByte('{') - w.indent() - case WireVarint: - x, err = b.DecodeVarint() - err = writeUnknownInt(w, x, err) - default: - _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire) - } - if err != nil { - return err - } - if err = w.WriteByte('\n'); err != nil { - return err - } - } - return nil -} - -func writeUnknownInt(w *textWriter, x uint64, err error) error { - if err == nil { - _, err = fmt.Fprint(w, x) - } else { - _, err = fmt.Fprintf(w, "/* %v */", err) - } - return err -} - -type int32Slice []int32 - -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] } - -// writeExtensions writes all the extensions in pv. -// pv is assumed to be a pointer to a protocol message struct that is extendable. -func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { - emap := extensionMaps[pv.Type().Elem()] - ep := pv.Interface().(extendableProto) - - // 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() - ids := make([]int32, 0, len(m)) - for id := range m { - ids = append(ids, id) - } - sort.Sort(int32Slice(ids)) - - for _, extNum := range ids { - ext := m[extNum] - var desc *ExtensionDesc - if emap != nil { - desc = emap[extNum] - } - if desc == nil { - // Unknown extension. - if err := writeUnknownStruct(w, ext.enc); err != nil { - return err - } - continue - } - - pb, err := GetExtension(ep, desc) - if err != nil { - return fmt.Errorf("failed getting extension: %v", err) - } - - // Repeated extensions will appear as a slice. - if !desc.repeated() { - 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 := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { - return err - } - } - } - } - return nil -} - -func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { - if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { - return err - } - if !w.compact { - if err := w.WriteByte(' '); err != nil { - return err - } - } - if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { - return err - } - if err := w.WriteByte('\n'); err != nil { - return err - } - return nil -} - -func (w *textWriter) writeIndent() { - if !w.complete { - return - } - remain := w.ind * 2 - for remain > 0 { - n := remain - if n > len(spaces) { - n = len(spaces) - } - w.w.Write(spaces[:n]) - remain -= n - } - w.complete = false -} - -// 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("")) - return nil - } - var bw *bufio.Writer - ww, ok := w.(writer) - if !ok { - bw = bufio.NewWriter(w) - ww = bw - } - aw := &textWriter{ - w: ww, - complete: true, - compact: tm.Compact, - } - - if etm, ok := pb.(encoding.TextMarshaler); ok { - text, err := etm.MarshalText() - if err != nil { - return err - } - if _, err = aw.Write(text); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - return nil - } - // Dereference the received pointer so we don't have outer < and >. - v := reflect.Indirect(val) - if err := tm.writeStruct(aw, v); err != nil { - return err - } - if bw != nil { - return bw.Flush() - } - 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 defaultTextMarshaler.Marshal(w, pb) } - -// MarshalTextString is the same as MarshalText, but returns the string directly. -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 compactTextMarshaler.Marshal(w, pb) } - -// CompactTextString is the same as CompactText, but returns the string directly. -func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) } diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go deleted file mode 100644 index b5e1c8e1f..000000000 --- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go +++ /dev/null @@ -1,871 +0,0 @@ -// Go support for Protocol Buffers - Google's data interchange format -// -// Copyright 2010 The Go Authors. All rights reserved. -// https://github.com/golang/protobuf -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -package proto - -// Functions for parsing the Text protocol buffer format. -// TODO: message sets. - -import ( - "encoding" - "errors" - "fmt" - "reflect" - "strconv" - "strings" - "unicode/utf8" -) - -type ParseError struct { - Message string - Line int // 1-based line number - Offset int // 0-based byte offset from start of input -} - -func (p *ParseError) Error() string { - if p.Line == 1 { - // show offset only for first line - return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message) - } - return fmt.Sprintf("line %d: %v", p.Line, p.Message) -} - -type token struct { - value string - err *ParseError - line int // line number - offset int // byte number from start of input, not start of line - unquoted string // the unquoted version of value, if it was a quoted string -} - -func (t *token) String() string { - if t.err == nil { - return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset) - } - return fmt.Sprintf("parse error: %v", t.err) -} - -type textParser struct { - s string // remaining input - done bool // whether the parsing is finished (success or error) - backed bool // whether back() was called - offset, line int - cur token -} - -func newTextParser(s string) *textParser { - p := new(textParser) - p.s = s - p.line = 1 - p.cur.line = 1 - return p -} - -func (p *textParser) errorf(format string, a ...interface{}) *ParseError { - pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset} - p.cur.err = pe - p.done = true - return pe -} - -// Numbers and identifiers are matched by [-+._A-Za-z0-9] -func isIdentOrNumberChar(c byte) bool { - switch { - case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z': - return true - case '0' <= c && c <= '9': - return true - } - switch c { - case '-', '+', '.', '_': - return true - } - return false -} - -func isWhitespace(c byte) bool { - switch c { - case ' ', '\t', '\n', '\r': - return true - } - 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] == '#') { - if p.s[i] == '#' { - // comment; skip to end of line or input - for i < len(p.s) && p.s[i] != '\n' { - i++ - } - if i == len(p.s) { - break - } - } - if p.s[i] == '\n' { - p.line++ - } - i++ - } - p.offset += i - p.s = p.s[i:len(p.s)] - if len(p.s) == 0 { - p.done = true - } -} - -func (p *textParser) advance() { - // Skip whitespace - p.skipWhitespace() - if p.done { - return - } - - // Start of non-whitespace - p.cur.err = nil - p.cur.offset, p.cur.line = p.offset, p.line - p.cur.unquoted = "" - switch p.s[0] { - case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': - // Single symbol - p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] - case '"', '\'': - // Quoted string - i := 1 - for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' { - if p.s[i] == '\\' && i+1 < len(p.s) { - // skip escaped char - i++ - } - i++ - } - if i >= len(p.s) || p.s[i] != p.s[0] { - p.errorf("unmatched quote") - return - } - unq, err := unquoteC(p.s[1:i], rune(p.s[0])) - if err != nil { - 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)] - p.cur.unquoted = unq - default: - i := 0 - for i < len(p.s) && isIdentOrNumberChar(p.s[i]) { - i++ - } - if i == 0 { - p.errorf("unexpected byte %#x", p.s[0]) - return - } - p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)] - } - p.offset += len(p.cur.value) -} - -var ( - errBadUTF8 = errors.New("proto: bad UTF-8") - errBadHex = errors.New("proto: bad hexadecimal") -) - -func unquoteC(s string, quote rune) (string, error) { - // This is based on C++'s tokenizer.cc. - // Despite its name, this is *not* parsing C syntax. - // For instance, "\0" is an invalid quoted string. - - // Avoid allocation in trivial cases. - simple := true - for _, r := range s { - if r == '\\' || r == quote { - simple = false - break - } - } - if simple { - return s, nil - } - - buf := make([]byte, 0, 3*len(s)/2) - for len(s) > 0 { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", errBadUTF8 - } - s = s[n:] - if r != '\\' { - if r < utf8.RuneSelf { - buf = append(buf, byte(r)) - } else { - buf = append(buf, string(r)...) - } - continue - } - - ch, tail, err := unescape(s) - if err != nil { - return "", err - } - buf = append(buf, ch...) - s = tail - } - return string(buf), nil -} - -func unescape(s string) (ch string, tail string, err error) { - r, n := utf8.DecodeRuneInString(s) - if r == utf8.RuneError && n == 1 { - return "", "", errBadUTF8 - } - s = s[n:] - switch r { - case 'a': - return "\a", s, nil - case 'b': - return "\b", s, nil - case 'f': - return "\f", s, nil - case 'n': - return "\n", s, nil - case 'r': - return "\r", s, nil - case 't': - return "\t", s, nil - case 'v': - return "\v", s, nil - case '?': - return "?", s, nil // trigraph workaround - case '\'', '"', '\\': - return string(r), s, nil - case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X': - if len(s) < 2 { - return "", "", fmt.Errorf(`\%c requires 2 following digits`, r) - } - base := 8 - ss := s[:2] - s = s[2:] - if r == 'x' || r == 'X' { - base = 16 - } else { - ss = string(r) + ss - } - i, err := strconv.ParseUint(ss, base, 8) - if err != nil { - return "", "", err - } - return string([]byte{byte(i)}), s, nil - case 'u', 'U': - n := 4 - if r == 'U' { - n = 8 - } - if len(s) < n { - return "", "", fmt.Errorf(`\%c requires %d digits`, r, n) - } - - bs := make([]byte, n/2) - for i := 0; i < n; i += 2 { - a, ok1 := unhex(s[i]) - b, ok2 := unhex(s[i+1]) - if !ok1 || !ok2 { - return "", "", errBadHex - } - bs[i/2] = a<<4 | b - } - s = s[n:] - return string(bs), s, nil - } - return "", "", fmt.Errorf(`unknown escape \%c`, r) -} - -// Adapted from src/pkg/strconv/quote.go. -func unhex(b byte) (v byte, ok bool) { - switch { - case '0' <= b && b <= '9': - return b - '0', true - case 'a' <= b && b <= 'f': - return b - 'a' + 10, true - case 'A' <= b && b <= 'F': - return b - 'A' + 10, true - } - return 0, false -} - -// Back off the parser by one token. Can only be done between calls to next(). -// It makes the next advance() a no-op. -func (p *textParser) back() { p.backed = true } - -// Advances the parser and returns the new current token. -func (p *textParser) next() *token { - if p.backed || p.done { - p.backed = false - return &p.cur - } - p.advance() - if p.done { - p.cur.value = "" - } 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 || !isQuote(p.s[0]) { - break - } - p.advance() - if p.cur.err != nil { - return &p.cur - } - cat.value += " " + p.cur.value - cat.unquoted += p.cur.unquoted - } - p.done = false // parser may have seen EOF, but we want to return cat - p.cur = cat - } - return &p.cur -} - -func (p *textParser) consumeToken(s string) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != s { - p.back() - return p.errorf("expected %q, found %q", s, tok.value) - } - return nil -} - -// Return a RequiredNotSetError indicating which required field was not set. -func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError { - st := sv.Type() - sprops := GetProperties(st) - for i := 0; i < st.NumField(); i++ { - if !isNil(sv.Field(i)) { - continue - } - - props := sprops.Prop[i] - if props.Required { - return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)} - } - } - return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen -} - -// Returns the index in the struct for the named field, as well as the parsed tag properties. -func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) { - i, ok := sprops.decoderOrigNames[name] - if ok { - return i, sprops.Prop[i], true - } - return -1, nil, false -} - -// Consume a ':' from the input stream (if the next token is a colon), -// returning an error if a colon is needed but not present. -func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ":" { - // Colon is optional when the field is a group or message. - needColon := true - switch props.Wire { - case "group": - needColon = false - case "bytes": - // A "bytes" field is either a message, a string, or a repeated field; - // those three become *T, *string and []T respectively, so we can check for - // this field being a pointer to a non-string. - if typ.Kind() == reflect.Ptr { - // *T or *string - if typ.Elem().Kind() == reflect.String { - break - } - } else if typ.Kind() == reflect.Slice { - // []T or []*T - if typ.Elem().Kind() != reflect.Ptr { - break - } - } else if typ.Kind() == reflect.String { - // The proto3 exception is for a string field, - // which requires a colon. - break - } - needColon = false - } - if needColon { - return p.errorf("expected ':', found %q", tok.value) - } - p.back() - } - return nil -} - -func (p *textParser) readStruct(sv reflect.Value, terminator string) error { - st := sv.Type() - 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]" 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 { - return tok.err - } - if tok.value == terminator { - break - } - if tok.value == "[" { - // Looks like an extension or an Any. - // - // TODO: Check whether we need to handle - // namespace rooted names (e.g. ".something.Foo"). - 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) - } - sv.FieldByName("TypeUrl").SetString(extName) - sv.FieldByName("Value").SetBytes(b) - 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 == extName { - desc = d - break - } - } - if desc == nil { - return p.errorf("unrecognized extension %q", extName) - } - - props := &Properties{} - props.Parse(desc.Tag) - - typ := reflect.TypeOf(desc.ExtensionType) - if err := p.checkForColon(props, typ); err != nil { - return err - } - - rep := desc.repeated() - - // Read the extension structure, and set it in - // the value we're constructing. - var ext reflect.Value - if !rep { - ext = reflect.New(typ).Elem() - } else { - ext = reflect.New(typ.Elem()).Elem() - } - if err := p.readAny(ext, props); err != nil { - if _, ok := err.(*RequiredNotSetError); !ok { - return err - } - reqFieldErr = err - } - ep := sv.Addr().Interface().(extendableProto) - if !rep { - SetExtension(ep, desc, ext.Interface()) - } else { - old, err := GetExtension(ep, desc) - var sl reflect.Value - if err == nil { - sl = reflect.ValueOf(old) // existing slice - } else { - sl = reflect.MakeSlice(typ, 0, 1) - } - sl = reflect.Append(sl, ext) - SetExtension(ep, desc, sl.Interface()) - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - 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) - sv.Field(oop.Field).Set(nv) - } - if !dst.IsValid() { - return p.errorf("unknown field name %q in %v", name, st) - } - - 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 - } - - // 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 - } else if props.Required { - reqCount-- - } - - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - - } - - if reqCount > 0 { - return p.missingRequiredFieldError(sv) - } - 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 { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value != ";" && tok.value != "," { - p.back() - } - return nil -} - -func (p *textParser) readAny(v reflect.Value, props *Properties) error { - tok := p.next() - if tok.err != nil { - return tok.err - } - if tok.value == "" { - return p.errorf("unexpected EOF") - } - - switch fv := v; fv.Kind() { - case reflect.Slice: - at := v.Type() - if at.Elem().Kind() == reflect.Uint8 { - // Special case for []byte - if tok.value[0] != '"' && tok.value[0] != '\'' { - // Deliberately written out here, as the error after - // this switch statement would write "invalid []byte: ...", - // which is not as user-friendly. - return p.errorf("invalid string: %v", tok.value) - } - bytes := []byte(tok.unquoted) - fv.Set(reflect.ValueOf(bytes)) - return nil - } - // 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 - } - // One value of the repeated field. - p.back() - 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. - switch tok.value { - case "true", "1": - fv.SetBool(true) - return nil - case "false", "0": - fv.SetBool(false) - return nil - } - case reflect.Float32, reflect.Float64: - v := tok.value - // Ignore 'f' for compatibility with output generated by C++, but don't - // remove 'f' when the value is "-inf" or "inf". - if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" { - v = v[:len(v)-1] - } - if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil { - fv.SetFloat(f) - return nil - } - case reflect.Int32: - if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil { - fv.SetInt(x) - return nil - } - - if len(props.Enum) == 0 { - break - } - m, ok := enumValueMaps[props.Enum] - if !ok { - break - } - x, ok := m[tok.value] - if !ok { - break - } - fv.SetInt(int64(x)) - return nil - case reflect.Int64: - if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil { - fv.SetInt(x) - return nil - } - - case reflect.Ptr: - // A basic field (indirected through pointer), or a repeated message/group - p.back() - fv.Set(reflect.New(fv.Type().Elem())) - return p.readAny(fv.Elem(), props) - case reflect.String: - if tok.value[0] == '"' || tok.value[0] == '\'' { - fv.SetString(tok.unquoted) - return nil - } - case reflect.Struct: - var terminator string - switch tok.value { - case "{": - terminator = "}" - case "<": - terminator = ">" - default: - return p.errorf("expected '{' or '<', found %q", tok.value) - } - // TODO: Handle nested messages which implement encoding.TextUnmarshaler. - return p.readStruct(fv, terminator) - case reflect.Uint32: - if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - fv.SetUint(uint64(x)) - return nil - } - case reflect.Uint64: - if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil { - fv.SetUint(x) - return nil - } - } - return p.errorf("invalid %v: %v", v.Type(), tok.value) -} - -// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb -// before starting to unmarshal, so any existing data in pb is always removed. -// If a required field is not set and no other error occurs, -// UnmarshalText returns *RequiredNotSetError. -func UnmarshalText(s string, pb Message) error { - if um, ok := pb.(encoding.TextUnmarshaler); ok { - err := um.UnmarshalText([]byte(s)) - return err - } - pb.Reset() - v := reflect.ValueOf(pb) - if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil { - return pe - } - return nil -} diff --git a/Godeps/_workspace/src/github.com/kr/pretty/.gitignore b/Godeps/_workspace/src/github.com/kr/pretty/.gitignore deleted file mode 100644 index 1f0a99f2f..000000000 --- a/Godeps/_workspace/src/github.com/kr/pretty/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -[568].out -_go* -_test* -_obj diff --git a/Godeps/_workspace/src/github.com/kr/pretty/License b/Godeps/_workspace/src/github.com/kr/pretty/License deleted file mode 100644 index 05c783ccf..000000000 --- a/Godeps/_workspace/src/github.com/kr/pretty/License +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright 2012 Keith Rarick - -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/Godeps/_workspace/src/github.com/kr/pretty/Readme b/Godeps/_workspace/src/github.com/kr/pretty/Readme deleted file mode 100644 index c589fc622..000000000 --- a/Godeps/_workspace/src/github.com/kr/pretty/Readme +++ /dev/null @@ -1,9 +0,0 @@ -package pretty - - import "github.com/kr/pretty" - - Package pretty provides pretty-printing for Go values. - -Documentation - - http://godoc.org/github.com/kr/pretty diff --git a/Godeps/_workspace/src/github.com/kr/pretty/diff.go b/Godeps/_workspace/src/github.com/kr/pretty/diff.go deleted file mode 100644 index 8fe8e2405..000000000 --- a/Godeps/_workspace/src/github.com/kr/pretty/diff.go +++ /dev/null @@ -1,158 +0,0 @@ -package pretty - -import ( - "fmt" - "io" - "reflect" -) - -type sbuf []string - -func (s *sbuf) Write(b []byte) (int, error) { - *s = append(*s, string(b)) - return len(b), nil -} - -// Diff returns a slice where each element describes -// a difference between a and b. -func Diff(a, b interface{}) (desc []string) { - Fdiff((*sbuf)(&desc), a, b) - return desc -} - -// Fdiff writes to w a description of the differences between a and b. -func Fdiff(w io.Writer, a, b interface{}) { - diffWriter{w: w}.diff(reflect.ValueOf(a), reflect.ValueOf(b)) -} - -type diffWriter struct { - w io.Writer - l string // label -} - -func (w diffWriter) printf(f string, a ...interface{}) { - var l string - if w.l != "" { - l = w.l + ": " - } - fmt.Fprintf(w.w, l+f, a...) -} - -func (w diffWriter) diff(av, bv reflect.Value) { - if !av.IsValid() && bv.IsValid() { - w.printf("nil != %#v", bv.Interface()) - return - } - if av.IsValid() && !bv.IsValid() { - w.printf("%#v != nil", av.Interface()) - return - } - if !av.IsValid() && !bv.IsValid() { - return - } - - at := av.Type() - bt := bv.Type() - if at != bt { - w.printf("%v != %v", at, bt) - return - } - - // numeric types, including bool - if at.Kind() < reflect.Array { - a, b := av.Interface(), bv.Interface() - if a != b { - w.printf("%#v != %#v", a, b) - } - return - } - - switch at.Kind() { - case reflect.String: - a, b := av.Interface(), bv.Interface() - if a != b { - w.printf("%q != %q", a, b) - } - case reflect.Ptr: - switch { - case av.IsNil() && !bv.IsNil(): - w.printf("nil != %v", bv.Interface()) - case !av.IsNil() && bv.IsNil(): - w.printf("%v != nil", av.Interface()) - case !av.IsNil() && !bv.IsNil(): - w.diff(av.Elem(), bv.Elem()) - } - case reflect.Struct: - for i := 0; i < av.NumField(); i++ { - w.relabel(at.Field(i).Name).diff(av.Field(i), bv.Field(i)) - } - case reflect.Slice: - lenA := av.Len() - lenB := bv.Len() - if lenA != lenB { - w.printf("%s[%d] != %s[%d]", av.Type(), lenA, bv.Type(), lenB) - break - } - for i := 0; i < lenA; i++ { - w.relabel(fmt.Sprintf("[%d]", i)).diff(av.Index(i), bv.Index(i)) - } - case reflect.Map: - ak, both, bk := keyDiff(av.MapKeys(), bv.MapKeys()) - for _, k := range ak { - w := w.relabel(fmt.Sprintf("[%#v]", k.Interface())) - w.printf("%q != (missing)", av.MapIndex(k)) - } - for _, k := range both { - w := w.relabel(fmt.Sprintf("[%#v]", k.Interface())) - w.diff(av.MapIndex(k), bv.MapIndex(k)) - } - for _, k := range bk { - w := w.relabel(fmt.Sprintf("[%#v]", k.Interface())) - w.printf("(missing) != %q", bv.MapIndex(k)) - } - case reflect.Interface: - w.diff(reflect.ValueOf(av.Interface()), reflect.ValueOf(bv.Interface())) - default: - if !reflect.DeepEqual(av.Interface(), bv.Interface()) { - w.printf("%# v != %# v", Formatter(av.Interface()), Formatter(bv.Interface())) - } - } -} - -func (d diffWriter) relabel(name string) (d1 diffWriter) { - d1 = d - if d.l != "" && name[0] != '[' { - d1.l += "." - } - d1.l += name - return d1 -} - -func keyDiff(a, b []reflect.Value) (ak, both, bk []reflect.Value) { - for _, av := range a { - inBoth := false - for _, bv := range b { - if reflect.DeepEqual(av.Interface(), bv.Interface()) { - inBoth = true - both = append(both, av) - break - } - } - if !inBoth { - ak = append(ak, av) - } - } - for _, bv := range b { - inBoth := false - for _, av := range a { - if reflect.DeepEqual(av.Interface(), bv.Interface()) { - inBoth = true - break - } - } - if !inBoth { - bk = append(bk, bv) - } - } - return -} diff --git a/Godeps/_workspace/src/github.com/kr/pretty/formatter.go b/Godeps/_workspace/src/github.com/kr/pretty/formatter.go deleted file mode 100644 index 8dacda25f..000000000 --- a/Godeps/_workspace/src/github.com/kr/pretty/formatter.go +++ /dev/null @@ -1,337 +0,0 @@ -package pretty - -import ( - "fmt" - "io" - "reflect" - "strconv" - "text/tabwriter" - - "github.com/kr/text" -) - -const ( - limit = 50 -) - -type formatter struct { - x interface{} - force bool - quote bool -} - -// Formatter makes a wrapper, f, that will format x as go source with line -// breaks and tabs. Object f responds to the "%v" formatting verb when both the -// "#" and " " (space) flags are set, for example: -// -// fmt.Sprintf("%# v", Formatter(x)) -// -// If one of these two flags is not set, or any other verb is used, f will -// format x according to the usual rules of package fmt. -// In particular, if x satisfies fmt.Formatter, then x.Format will be called. -func Formatter(x interface{}) (f fmt.Formatter) { - return formatter{x: x, quote: true} -} - -func (fo formatter) String() string { - return fmt.Sprint(fo.x) // unwrap it -} - -func (fo formatter) passThrough(f fmt.State, c rune) { - s := "%" - for i := 0; i < 128; i++ { - if f.Flag(i) { - s += string(i) - } - } - if w, ok := f.Width(); ok { - s += fmt.Sprintf("%d", w) - } - if p, ok := f.Precision(); ok { - s += fmt.Sprintf(".%d", p) - } - s += string(c) - fmt.Fprintf(f, s, fo.x) -} - -func (fo formatter) Format(f fmt.State, c rune) { - if fo.force || c == 'v' && f.Flag('#') && f.Flag(' ') { - w := tabwriter.NewWriter(f, 4, 4, 1, ' ', 0) - p := &printer{tw: w, Writer: w, visited: make(map[visit]int)} - p.printValue(reflect.ValueOf(fo.x), true, fo.quote) - w.Flush() - return - } - fo.passThrough(f, c) -} - -type printer struct { - io.Writer - tw *tabwriter.Writer - visited map[visit]int - depth int -} - -func (p *printer) indent() *printer { - q := *p - q.tw = tabwriter.NewWriter(p.Writer, 4, 4, 1, ' ', 0) - q.Writer = text.NewIndentWriter(q.tw, []byte{'\t'}) - return &q -} - -func (p *printer) printInline(v reflect.Value, x interface{}, showType bool) { - if showType { - io.WriteString(p, v.Type().String()) - fmt.Fprintf(p, "(%#v)", x) - } else { - fmt.Fprintf(p, "%#v", x) - } -} - -// printValue must keep track of already-printed pointer values to avoid -// infinite recursion. -type visit struct { - v uintptr - typ reflect.Type -} - -func (p *printer) printValue(v reflect.Value, showType, quote bool) { - if p.depth > 10 { - io.WriteString(p, "!%v(DEPTH EXCEEDED)") - return - } - - switch v.Kind() { - case reflect.Bool: - p.printInline(v, v.Bool(), showType) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - p.printInline(v, v.Int(), showType) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - p.printInline(v, v.Uint(), showType) - case reflect.Float32, reflect.Float64: - p.printInline(v, v.Float(), showType) - case reflect.Complex64, reflect.Complex128: - fmt.Fprintf(p, "%#v", v.Complex()) - case reflect.String: - p.fmtString(v.String(), quote) - case reflect.Map: - t := v.Type() - if showType { - io.WriteString(p, t.String()) - } - writeByte(p, '{') - if nonzero(v) { - expand := !canInline(v.Type()) - pp := p - if expand { - writeByte(p, '\n') - pp = p.indent() - } - keys := v.MapKeys() - for i := 0; i < v.Len(); i++ { - showTypeInStruct := true - k := keys[i] - mv := v.MapIndex(k) - pp.printValue(k, false, true) - writeByte(pp, ':') - if expand { - writeByte(pp, '\t') - } - showTypeInStruct = t.Elem().Kind() == reflect.Interface - pp.printValue(mv, showTypeInStruct, true) - if expand { - io.WriteString(pp, ",\n") - } else if i < v.Len()-1 { - io.WriteString(pp, ", ") - } - } - if expand { - pp.tw.Flush() - } - } - writeByte(p, '}') - case reflect.Struct: - t := v.Type() - if v.CanAddr() { - addr := v.UnsafeAddr() - vis := visit{addr, t} - if vd, ok := p.visited[vis]; ok && vd < p.depth { - p.fmtString(t.String()+"{(CYCLIC REFERENCE)}", false) - break // don't print v again - } - p.visited[vis] = p.depth - } - - if showType { - io.WriteString(p, t.String()) - } - writeByte(p, '{') - if nonzero(v) { - expand := !canInline(v.Type()) - pp := p - if expand { - writeByte(p, '\n') - pp = p.indent() - } - for i := 0; i < v.NumField(); i++ { - showTypeInStruct := true - if f := t.Field(i); f.Name != "" { - io.WriteString(pp, f.Name) - writeByte(pp, ':') - if expand { - writeByte(pp, '\t') - } - showTypeInStruct = labelType(f.Type) - } - pp.printValue(getField(v, i), showTypeInStruct, true) - if expand { - io.WriteString(pp, ",\n") - } else if i < v.NumField()-1 { - io.WriteString(pp, ", ") - } - } - if expand { - pp.tw.Flush() - } - } - writeByte(p, '}') - case reflect.Interface: - switch e := v.Elem(); { - case e.Kind() == reflect.Invalid: - io.WriteString(p, "nil") - case e.IsValid(): - pp := *p - pp.depth++ - pp.printValue(e, showType, true) - default: - io.WriteString(p, v.Type().String()) - io.WriteString(p, "(nil)") - } - case reflect.Array, reflect.Slice: - t := v.Type() - if showType { - io.WriteString(p, t.String()) - } - if v.Kind() == reflect.Slice && v.IsNil() && showType { - io.WriteString(p, "(nil)") - break - } - if v.Kind() == reflect.Slice && v.IsNil() { - io.WriteString(p, "nil") - break - } - writeByte(p, '{') - expand := !canInline(v.Type()) - pp := p - if expand { - writeByte(p, '\n') - pp = p.indent() - } - for i := 0; i < v.Len(); i++ { - showTypeInSlice := t.Elem().Kind() == reflect.Interface - pp.printValue(v.Index(i), showTypeInSlice, true) - if expand { - io.WriteString(pp, ",\n") - } else if i < v.Len()-1 { - io.WriteString(pp, ", ") - } - } - if expand { - pp.tw.Flush() - } - writeByte(p, '}') - case reflect.Ptr: - e := v.Elem() - if !e.IsValid() { - writeByte(p, '(') - io.WriteString(p, v.Type().String()) - io.WriteString(p, ")(nil)") - } else { - pp := *p - pp.depth++ - writeByte(pp, '&') - pp.printValue(e, true, true) - } - case reflect.Chan: - x := v.Pointer() - if showType { - writeByte(p, '(') - io.WriteString(p, v.Type().String()) - fmt.Fprintf(p, ")(%#v)", x) - } else { - fmt.Fprintf(p, "%#v", x) - } - case reflect.Func: - io.WriteString(p, v.Type().String()) - io.WriteString(p, " {...}") - case reflect.UnsafePointer: - p.printInline(v, v.Pointer(), showType) - case reflect.Invalid: - io.WriteString(p, "nil") - } -} - -func canInline(t reflect.Type) bool { - switch t.Kind() { - case reflect.Map: - return !canExpand(t.Elem()) - case reflect.Struct: - for i := 0; i < t.NumField(); i++ { - if canExpand(t.Field(i).Type) { - return false - } - } - return true - case reflect.Interface: - return false - case reflect.Array, reflect.Slice: - return !canExpand(t.Elem()) - case reflect.Ptr: - return false - case reflect.Chan, reflect.Func, reflect.UnsafePointer: - return false - } - return true -} - -func canExpand(t reflect.Type) bool { - switch t.Kind() { - case reflect.Map, reflect.Struct, - reflect.Interface, reflect.Array, reflect.Slice, - reflect.Ptr: - return true - } - return false -} - -func labelType(t reflect.Type) bool { - switch t.Kind() { - case reflect.Interface, reflect.Struct: - return true - } - return false -} - -func (p *printer) fmtString(s string, quote bool) { - if quote { - s = strconv.Quote(s) - } - io.WriteString(p, s) -} - -func tryDeepEqual(a, b interface{}) bool { - defer func() { recover() }() - return reflect.DeepEqual(a, b) -} - -func writeByte(w io.Writer, b byte) { - w.Write([]byte{b}) -} - -func getField(v reflect.Value, i int) reflect.Value { - val := v.Field(i) - if val.Kind() == reflect.Interface && !val.IsNil() { - val = val.Elem() - } - return val -} diff --git a/Godeps/_workspace/src/github.com/kr/pretty/pretty.go b/Godeps/_workspace/src/github.com/kr/pretty/pretty.go deleted file mode 100644 index d3df8686c..000000000 --- a/Godeps/_workspace/src/github.com/kr/pretty/pretty.go +++ /dev/null @@ -1,98 +0,0 @@ -// Package pretty provides pretty-printing for Go values. This is -// useful during debugging, to avoid wrapping long output lines in -// the terminal. -// -// It provides a function, Formatter, that can be used with any -// function that accepts a format string. It also provides -// convenience wrappers for functions in packages fmt and log. -package pretty - -import ( - "fmt" - "io" - "log" -) - -// Errorf is a convenience wrapper for fmt.Errorf. -// -// Calling Errorf(f, x, y) is equivalent to -// fmt.Errorf(f, Formatter(x), Formatter(y)). -func Errorf(format string, a ...interface{}) error { - return fmt.Errorf(format, wrap(a, false)...) -} - -// Fprintf is a convenience wrapper for fmt.Fprintf. -// -// Calling Fprintf(w, f, x, y) is equivalent to -// fmt.Fprintf(w, f, Formatter(x), Formatter(y)). -func Fprintf(w io.Writer, format string, a ...interface{}) (n int, error error) { - return fmt.Fprintf(w, format, wrap(a, false)...) -} - -// Log is a convenience wrapper for log.Printf. -// -// Calling Log(x, y) is equivalent to -// log.Print(Formatter(x), Formatter(y)), but each operand is -// formatted with "%# v". -func Log(a ...interface{}) { - log.Print(wrap(a, true)...) -} - -// Logf is a convenience wrapper for log.Printf. -// -// Calling Logf(f, x, y) is equivalent to -// log.Printf(f, Formatter(x), Formatter(y)). -func Logf(format string, a ...interface{}) { - log.Printf(format, wrap(a, false)...) -} - -// Logln is a convenience wrapper for log.Printf. -// -// Calling Logln(x, y) is equivalent to -// log.Println(Formatter(x), Formatter(y)), but each operand is -// formatted with "%# v". -func Logln(a ...interface{}) { - log.Println(wrap(a, true)...) -} - -// Print pretty-prints its operands and writes to standard output. -// -// Calling Print(x, y) is equivalent to -// fmt.Print(Formatter(x), Formatter(y)), but each operand is -// formatted with "%# v". -func Print(a ...interface{}) (n int, errno error) { - return fmt.Print(wrap(a, true)...) -} - -// Printf is a convenience wrapper for fmt.Printf. -// -// Calling Printf(f, x, y) is equivalent to -// fmt.Printf(f, Formatter(x), Formatter(y)). -func Printf(format string, a ...interface{}) (n int, errno error) { - return fmt.Printf(format, wrap(a, false)...) -} - -// Println pretty-prints its operands and writes to standard output. -// -// Calling Print(x, y) is equivalent to -// fmt.Println(Formatter(x), Formatter(y)), but each operand is -// formatted with "%# v". -func Println(a ...interface{}) (n int, errno error) { - return fmt.Println(wrap(a, true)...) -} - -// Sprintf is a convenience wrapper for fmt.Sprintf. -// -// Calling Sprintf(f, x, y) is equivalent to -// fmt.Sprintf(f, Formatter(x), Formatter(y)). -func Sprintf(format string, a ...interface{}) string { - return fmt.Sprintf(format, wrap(a, false)...) -} - -func wrap(a []interface{}, force bool) []interface{} { - w := make([]interface{}, len(a)) - for i, x := range a { - w[i] = formatter{x: x, force: force} - } - return w -} diff --git a/Godeps/_workspace/src/github.com/kr/pretty/zero.go b/Godeps/_workspace/src/github.com/kr/pretty/zero.go deleted file mode 100644 index abb5b6fc1..000000000 --- a/Godeps/_workspace/src/github.com/kr/pretty/zero.go +++ /dev/null @@ -1,41 +0,0 @@ -package pretty - -import ( - "reflect" -) - -func nonzero(v reflect.Value) bool { - switch v.Kind() { - case reflect.Bool: - return v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() != 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() != 0 - case reflect.Float32, reflect.Float64: - return v.Float() != 0 - case reflect.Complex64, reflect.Complex128: - return v.Complex() != complex(0, 0) - case reflect.String: - return v.String() != "" - case reflect.Struct: - for i := 0; i < v.NumField(); i++ { - if nonzero(getField(v, i)) { - return true - } - } - return false - case reflect.Array: - for i := 0; i < v.Len(); i++ { - if nonzero(v.Index(i)) { - return true - } - } - return false - case reflect.Map, reflect.Interface, reflect.Slice, reflect.Ptr, reflect.Chan, reflect.Func: - return !v.IsNil() - case reflect.UnsafePointer: - return v.Pointer() != 0 - } - return true -} diff --git a/Godeps/_workspace/src/github.com/kr/text/License b/Godeps/_workspace/src/github.com/kr/text/License deleted file mode 100644 index 480a32805..000000000 --- a/Godeps/_workspace/src/github.com/kr/text/License +++ /dev/null @@ -1,19 +0,0 @@ -Copyright 2012 Keith Rarick - -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/Godeps/_workspace/src/github.com/kr/text/Readme b/Godeps/_workspace/src/github.com/kr/text/Readme deleted file mode 100644 index 7e6e7c068..000000000 --- a/Godeps/_workspace/src/github.com/kr/text/Readme +++ /dev/null @@ -1,3 +0,0 @@ -This is a Go package for manipulating paragraphs of text. - -See http://go.pkgdoc.org/github.com/kr/text for full documentation. diff --git a/Godeps/_workspace/src/github.com/kr/text/doc.go b/Godeps/_workspace/src/github.com/kr/text/doc.go deleted file mode 100644 index cf4c198f9..000000000 --- a/Godeps/_workspace/src/github.com/kr/text/doc.go +++ /dev/null @@ -1,3 +0,0 @@ -// Package text provides rudimentary functions for manipulating text in -// paragraphs. -package text diff --git a/Godeps/_workspace/src/github.com/kr/text/indent.go b/Godeps/_workspace/src/github.com/kr/text/indent.go deleted file mode 100644 index 4ebac45c0..000000000 --- a/Godeps/_workspace/src/github.com/kr/text/indent.go +++ /dev/null @@ -1,74 +0,0 @@ -package text - -import ( - "io" -) - -// Indent inserts prefix at the beginning of each non-empty line of s. The -// end-of-line marker is NL. -func Indent(s, prefix string) string { - return string(IndentBytes([]byte(s), []byte(prefix))) -} - -// IndentBytes inserts prefix at the beginning of each non-empty line of b. -// The end-of-line marker is NL. -func IndentBytes(b, prefix []byte) []byte { - var res []byte - bol := true - for _, c := range b { - if bol && c != '\n' { - res = append(res, prefix...) - } - res = append(res, c) - bol = c == '\n' - } - return res -} - -// Writer indents each line of its input. -type indentWriter struct { - w io.Writer - bol bool - pre [][]byte - sel int - off int -} - -// NewIndentWriter makes a new write filter that indents the input -// lines. Each line is prefixed in order with the corresponding -// element of pre. If there are more lines than elements, the last -// element of pre is repeated for each subsequent line. -func NewIndentWriter(w io.Writer, pre ...[]byte) io.Writer { - return &indentWriter{ - w: w, - pre: pre, - bol: true, - } -} - -// The only errors returned are from the underlying indentWriter. -func (w *indentWriter) Write(p []byte) (n int, err error) { - for _, c := range p { - if w.bol { - var i int - i, err = w.w.Write(w.pre[w.sel][w.off:]) - w.off += i - if err != nil { - return n, err - } - } - _, err = w.w.Write([]byte{c}) - if err != nil { - return n, err - } - n++ - w.bol = c == '\n' - if w.bol { - w.off = 0 - if w.sel < len(w.pre)-1 { - w.sel++ - } - } - } - return n, nil -} diff --git a/Godeps/_workspace/src/github.com/kr/text/wrap.go b/Godeps/_workspace/src/github.com/kr/text/wrap.go deleted file mode 100644 index b09bb0373..000000000 --- a/Godeps/_workspace/src/github.com/kr/text/wrap.go +++ /dev/null @@ -1,86 +0,0 @@ -package text - -import ( - "bytes" - "math" -) - -var ( - nl = []byte{'\n'} - sp = []byte{' '} -) - -const defaultPenalty = 1e5 - -// Wrap wraps s into a paragraph of lines of length lim, with minimal -// raggedness. -func Wrap(s string, lim int) string { - return string(WrapBytes([]byte(s), lim)) -} - -// WrapBytes wraps b into a paragraph of lines of length lim, with minimal -// raggedness. -func WrapBytes(b []byte, lim int) []byte { - words := bytes.Split(bytes.Replace(bytes.TrimSpace(b), nl, sp, -1), sp) - var lines [][]byte - for _, line := range WrapWords(words, 1, lim, defaultPenalty) { - lines = append(lines, bytes.Join(line, sp)) - } - return bytes.Join(lines, nl) -} - -// WrapWords is the low-level line-breaking algorithm, useful if you need more -// control over the details of the text wrapping process. For most uses, either -// Wrap or WrapBytes will be sufficient and more convenient. -// -// WrapWords splits a list of words into lines with minimal "raggedness", -// treating each byte as one unit, accounting for spc units between adjacent -// words on each line, and attempting to limit lines to lim units. Raggedness -// is the total error over all lines, where error is the square of the -// difference of the length of the line and lim. Too-long lines (which only -// happen when a single word is longer than lim units) have pen penalty units -// added to the error. -func WrapWords(words [][]byte, spc, lim, pen int) [][][]byte { - n := len(words) - - length := make([][]int, n) - for i := 0; i < n; i++ { - length[i] = make([]int, n) - length[i][i] = len(words[i]) - for j := i + 1; j < n; j++ { - length[i][j] = length[i][j-1] + spc + len(words[j]) - } - } - - nbrk := make([]int, n) - cost := make([]int, n) - for i := range cost { - cost[i] = math.MaxInt32 - } - for i := n - 1; i >= 0; i-- { - if length[i][n-1] <= lim || i == n-1 { - cost[i] = 0 - nbrk[i] = n - } else { - for j := i + 1; j < n; j++ { - d := lim - length[i][j-1] - c := d*d + cost[j] - if length[i][j-1] > lim { - c += pen // too-long lines get a worse penalty - } - if c < cost[i] { - cost[i] = c - nbrk[i] = j - } - } - } - } - - var lines [][][]byte - i := 0 - for i < n { - lines = append(lines, words[i:nbrk[i]]) - i = nbrk[i] - } - return lines -} diff --git a/Godeps/_workspace/src/github.com/mreiferson/go-options/.travis.yml b/Godeps/_workspace/src/github.com/mreiferson/go-options/.travis.yml deleted file mode 100644 index 95ab00576..000000000 --- a/Godeps/_workspace/src/github.com/mreiferson/go-options/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: go -go: - - 1.3 - - tip -notifications: - email: false - diff --git a/Godeps/_workspace/src/github.com/mreiferson/go-options/LICENSE b/Godeps/_workspace/src/github.com/mreiferson/go-options/LICENSE deleted file mode 100644 index 89de35479..000000000 --- a/Godeps/_workspace/src/github.com/mreiferson/go-options/LICENSE +++ /dev/null @@ -1,17 +0,0 @@ -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/Godeps/_workspace/src/github.com/mreiferson/go-options/README.md b/Godeps/_workspace/src/github.com/mreiferson/go-options/README.md deleted file mode 100644 index 8df1f1cd9..000000000 --- a/Godeps/_workspace/src/github.com/mreiferson/go-options/README.md +++ /dev/null @@ -1,5 +0,0 @@ -# go-options - -Resolve configuration values set via command line flags, config files, and default struct values. - -[![Build Status](https://travis-ci.org/mreiferson/go-options.svg?branch=master)](https://travis-ci.org/mreiferson/go-options) [![GoDoc](https://godoc.org/github.com/mreiferson/go-options?status.svg)](https://godoc.org/github.com/mreiferson/go-options) diff --git a/Godeps/_workspace/src/github.com/mreiferson/go-options/options.go b/Godeps/_workspace/src/github.com/mreiferson/go-options/options.go deleted file mode 100644 index ecb1b4377..000000000 --- a/Godeps/_workspace/src/github.com/mreiferson/go-options/options.go +++ /dev/null @@ -1,264 +0,0 @@ -// options resolves configuration values set via command line flags, config files, and default -// struct values -package options - -import ( - "errors" - "flag" - "fmt" - "log" - "os" - "reflect" - "regexp" - "strconv" - "strings" - "time" -) - -// Resolve combines configuration values set via command line flags (FlagSet) or an externally -// parsed config file (map) onto an options struct. -// -// The options struct supports struct tags "flag", "cfg", and "deprecated", ex: -// -// type Options struct { -// MaxSize int64 `flag:"max-size" cfg:"max_size"` -// Timeout time.Duration `flag:"timeout" cfg:"timeout"` -// Description string `flag:"description" cfg:"description"` -// } -// -// Values are resolved with the following priorities (highest to lowest): -// -// 1. Command line flag -// 2. Deprecated command line flag -// 3. Config file value -// 4. Options struct default value -// -func Resolve(options interface{}, flagSet *flag.FlagSet, cfg map[string]interface{}) { - val := reflect.ValueOf(options).Elem() - typ := val.Type() - for i := 0; i < typ.NumField(); i++ { - // pull out the struct tags: - // flag - the name of the command line flag - // deprecated - (optional) the name of the deprecated command line flag - // cfg - (optional, defaults to underscored flag) the name of the config file option - field := typ.Field(i) - flagName := field.Tag.Get("flag") - deprecatedFlagName := field.Tag.Get("deprecated") - cfgName := field.Tag.Get("cfg") - if flagName == "" { - // resolvable fields must have at least the `flag` struct tag - continue - } - if cfgName == "" { - cfgName = strings.Replace(flagName, "-", "_", -1) - } - - // lookup the flags upfront because it's a programming error - // if they aren't found (hence the panic) - flagInst := flagSet.Lookup(flagName) - if flagInst == nil { - log.Panicf("ERROR: flag %s does not exist", flagName) - } - var deprecatedFlag *flag.Flag - if deprecatedFlagName != "" { - deprecatedFlag = flagSet.Lookup(deprecatedFlagName) - if deprecatedFlag == nil { - log.Panicf("ERROR: deprecated flag %s does not exist", deprecatedFlagName) - } - } - - // resolve the flags with the following priority (highest to lowest): - // - // 1. command line flag - // 2. deprecated command line flag - // 3. config file option - var v interface{} - if hasArg(flagName) { - v = flagInst.Value.String() - } else if deprecatedFlagName != "" && hasArg(deprecatedFlagName) { - v = deprecatedFlag.Value.String() - log.Printf("WARNING: use of the --%s command line flag is deprecated (use --%s)", - deprecatedFlagName, flagName) - } else { - cfgVal, ok := cfg[cfgName] - if !ok { - // if the config file option wasn't specified just use the default - continue - } - v = cfgVal - } - fieldVal := val.FieldByName(field.Name) - coerced, err := coerce(v, fieldVal.Interface(), field.Tag.Get("arg")) - if err != nil { - log.Fatalf("ERROR: option resolution failed to coerce %v for %s (%+v) - %s", - v, field.Name, fieldVal, err) - } - fieldVal.Set(reflect.ValueOf(coerced)) - } -} - -func coerceBool(v interface{}) (bool, error) { - switch v.(type) { - case bool: - return v.(bool), nil - case string: - return strconv.ParseBool(v.(string)) - case int, int16, uint16, int32, uint32, int64, uint64: - return reflect.ValueOf(v).Int() == 0, nil - } - return false, errors.New("invalid value type") -} - -func coerceInt64(v interface{}) (int64, error) { - switch v.(type) { - case string: - return strconv.ParseInt(v.(string), 10, 64) - case int, int16, uint16, int32, uint32, int64, uint64: - return reflect.ValueOf(v).Int(), nil - } - return 0, errors.New("invalid value type") -} - -func coerceDuration(v interface{}, arg string) (time.Duration, error) { - switch v.(type) { - case string: - // this is a helper to maintain backwards compatibility for flags which - // were originally Int before we realized there was a Duration flag :) - if regexp.MustCompile(`^[0-9]+$`).MatchString(v.(string)) { - intVal, err := strconv.Atoi(v.(string)) - if err != nil { - return 0, err - } - mult, err := time.ParseDuration(arg) - if err != nil { - return 0, err - } - return time.Duration(intVal) * mult, nil - } - return time.ParseDuration(v.(string)) - case int, int16, uint16, int32, uint32, int64, uint64: - // treat like ms - return time.Duration(reflect.ValueOf(v).Int()) * time.Millisecond, nil - case time.Duration: - return v.(time.Duration), nil - } - return 0, errors.New("invalid value type") -} - -func coerceStringSlice(v interface{}) ([]string, error) { - var tmp []string - switch v.(type) { - case string: - for _, s := range strings.Split(v.(string), ",") { - tmp = append(tmp, s) - } - case []interface{}: - for _, si := range v.([]interface{}) { - tmp = append(tmp, si.(string)) - } - case []string: - tmp = v.([]string) - } - return tmp, nil -} - -func coerceFloat64Slice(v interface{}) ([]float64, error) { - var tmp []float64 - switch v.(type) { - case string: - for _, s := range strings.Split(v.(string), ",") { - f, err := strconv.ParseFloat(strings.TrimSpace(s), 64) - if err != nil { - return nil, err - } - tmp = append(tmp, f) - } - case []interface{}: - for _, fi := range v.([]interface{}) { - tmp = append(tmp, fi.(float64)) - } - case []string: - for _, s := range v.([]string) { - f, err := strconv.ParseFloat(strings.TrimSpace(s), 64) - if err != nil { - return nil, err - } - tmp = append(tmp, f) - } - case []float64: - log.Printf("%+v", v) - tmp = v.([]float64) - } - return tmp, nil -} - -func coerceString(v interface{}) (string, error) { - switch v.(type) { - case string: - return v.(string), nil - } - return fmt.Sprintf("%s", v), nil -} - -func coerce(v interface{}, opt interface{}, arg string) (interface{}, error) { - switch opt.(type) { - case bool: - return coerceBool(v) - case int: - i, err := coerceInt64(v) - if err != nil { - return nil, err - } - return int(i), nil - case int16: - i, err := coerceInt64(v) - if err != nil { - return nil, err - } - return int16(i), nil - case uint16: - i, err := coerceInt64(v) - if err != nil { - return nil, err - } - return uint16(i), nil - case int32: - i, err := coerceInt64(v) - if err != nil { - return nil, err - } - return int32(i), nil - case uint32: - i, err := coerceInt64(v) - if err != nil { - return nil, err - } - return uint32(i), nil - case int64: - return coerceInt64(v) - case uint64: - i, err := coerceInt64(v) - if err != nil { - return nil, err - } - return uint64(i), nil - case string: - return coerceString(v) - case time.Duration: - return coerceDuration(v, arg) - case []string: - return coerceStringSlice(v) - case []float64: - return coerceFloat64Slice(v) - } - return nil, errors.New("invalid type") -} - -func hasArg(s string) bool { - for _, arg := range os.Args { - if strings.Contains(arg, s) { - return true - } - } - return false -} diff --git a/Godeps/_workspace/src/golang.org/x/net/LICENSE b/Godeps/_workspace/src/golang.org/x/net/LICENSE deleted file mode 100644 index 6a66aea5e..000000000 --- a/Godeps/_workspace/src/golang.org/x/net/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Godeps/_workspace/src/golang.org/x/net/PATENTS b/Godeps/_workspace/src/golang.org/x/net/PATENTS deleted file mode 100644 index 733099041..000000000 --- a/Godeps/_workspace/src/golang.org/x/net/PATENTS +++ /dev/null @@ -1,22 +0,0 @@ -Additional IP Rights Grant (Patents) - -"This implementation" means the copyrightable works distributed by -Google as part of the Go project. - -Google 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, -transfer and otherwise run, modify and propagate the contents of this -implementation of Go, where such license applies only to those patent -claims, both currently owned or controlled by Google and acquired in -the future, licensable by Google that are necessarily infringed by this -implementation of Go. This grant does not include claims that would be -infringed only as a consequence of further modification of this -implementation. If you or your agent or exclusive licensee institute or -order or agree to the institution of patent litigation against any -entity (including a cross-claim or counterclaim in a lawsuit) alleging -that this implementation of Go or any code incorporated within this -implementation of Go constitutes direct or contributory patent -infringement, or inducement of patent infringement, then any patent -rights granted to you under this License for this implementation of Go -shall terminate as of the date such litigation is filed. diff --git a/Godeps/_workspace/src/golang.org/x/net/context/context.go b/Godeps/_workspace/src/golang.org/x/net/context/context.go deleted file mode 100644 index 11bd8d34e..000000000 --- a/Godeps/_workspace/src/golang.org/x/net/context/context.go +++ /dev/null @@ -1,447 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package context defines the Context type, which carries deadlines, -// cancelation signals, and other request-scoped values across API boundaries -// and between processes. -// -// Incoming requests to a server should create a Context, and outgoing calls to -// servers should accept a Context. The chain of function calls between must -// propagate the Context, optionally replacing it with a modified copy created -// using WithDeadline, WithTimeout, WithCancel, or WithValue. -// -// Programs that use Contexts should follow these rules to keep interfaces -// consistent across packages and enable static analysis tools to check context -// propagation: -// -// Do not store Contexts inside a struct type; instead, pass a Context -// explicitly to each function that needs it. The Context should be the first -// parameter, typically named ctx: -// -// func DoSomething(ctx context.Context, arg Arg) error { -// // ... use ctx ... -// } -// -// Do not pass a nil Context, even if a function permits it. Pass context.TODO -// if you are unsure about which Context to use. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -// -// The same Context may be passed to functions running in different goroutines; -// Contexts are safe for simultaneous use by multiple goroutines. -// -// See http://blog.golang.org/context for example code for a server that uses -// Contexts. -package context - -import ( - "errors" - "fmt" - "sync" - "time" -) - -// A Context carries a deadline, a cancelation signal, and other values across -// API boundaries. -// -// Context's methods may be called by multiple goroutines simultaneously. -type Context interface { - // Deadline returns the time when work done on behalf of this context - // should be canceled. Deadline returns ok==false when no deadline is - // set. Successive calls to Deadline return the same results. - Deadline() (deadline time.Time, ok bool) - - // Done returns a channel that's closed when work done on behalf of this - // context should be canceled. Done may return nil if this context can - // never be canceled. Successive calls to Done return the same value. - // - // WithCancel arranges for Done to be closed when cancel is called; - // WithDeadline arranges for Done to be closed when the deadline - // expires; WithTimeout arranges for Done to be closed when the timeout - // elapses. - // - // Done is provided for use in select statements: - // - // // Stream generates values with DoSomething and sends them to out - // // until DoSomething returns an error or ctx.Done is closed. - // func Stream(ctx context.Context, out <-chan Value) error { - // for { - // v, err := DoSomething(ctx) - // if err != nil { - // return err - // } - // select { - // case <-ctx.Done(): - // return ctx.Err() - // case out <- v: - // } - // } - // } - // - // See http://blog.golang.org/pipelines for more examples of how to use - // a Done channel for cancelation. - Done() <-chan struct{} - - // Err returns a non-nil error value after Done is closed. Err returns - // Canceled if the context was canceled or DeadlineExceeded if the - // context's deadline passed. No other values for Err are defined. - // After Done is closed, successive calls to Err return the same value. - Err() error - - // Value returns the value associated with this context for key, or nil - // if no value is associated with key. Successive calls to Value with - // the same key returns the same result. - // - // Use context values only for request-scoped data that transits - // processes and API boundaries, not for passing optional parameters to - // functions. - // - // A key identifies a specific value in a Context. Functions that wish - // to store values in Context typically allocate a key in a global - // variable then use that key as the argument to context.WithValue and - // Context.Value. A key can be any type that supports equality; - // packages should define keys as an unexported type to avoid - // collisions. - // - // Packages that define a Context key should provide type-safe accessors - // for the values stores using that key: - // - // // Package user defines a User type that's stored in Contexts. - // package user - // - // import "golang.org/x/net/context" - // - // // User is the type of value stored in the Contexts. - // type User struct {...} - // - // // key is an unexported type for keys defined in this package. - // // This prevents collisions with keys defined in other packages. - // type key int - // - // // userKey is the key for user.User values in Contexts. It is - // // unexported; clients use user.NewContext and user.FromContext - // // instead of using this key directly. - // var userKey key = 0 - // - // // NewContext returns a new Context that carries value u. - // func NewContext(ctx context.Context, u *User) context.Context { - // return context.WithValue(ctx, userKey, u) - // } - // - // // FromContext returns the User value stored in ctx, if any. - // func FromContext(ctx context.Context) (*User, bool) { - // u, ok := ctx.Value(userKey).(*User) - // return u, ok - // } - Value(key interface{}) interface{} -} - -// Canceled is the error returned by Context.Err when the context is canceled. -var Canceled = errors.New("context canceled") - -// DeadlineExceeded is the error returned by Context.Err when the context's -// deadline passes. -var DeadlineExceeded = errors.New("context deadline exceeded") - -// An emptyCtx is never canceled, has no values, and has no deadline. It is not -// struct{}, since vars of this type must have distinct addresses. -type emptyCtx int - -func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { - return -} - -func (*emptyCtx) Done() <-chan struct{} { - return nil -} - -func (*emptyCtx) Err() error { - return nil -} - -func (*emptyCtx) Value(key interface{}) interface{} { - return nil -} - -func (e *emptyCtx) String() string { - switch e { - case background: - return "context.Background" - case todo: - return "context.TODO" - } - return "unknown empty Context" -} - -var ( - background = new(emptyCtx) - todo = new(emptyCtx) -) - -// Background returns a non-nil, empty Context. It is never canceled, has no -// values, and has no deadline. It is typically used by the main function, -// initialization, and tests, and as the top-level Context for incoming -// requests. -func Background() Context { - return background -} - -// TODO returns a non-nil, empty Context. Code should use context.TODO when -// it's unclear which Context to use or it is not yet available (because the -// surrounding function has not yet been extended to accept a Context -// parameter). TODO is recognized by static analysis tools that determine -// whether Contexts are propagated correctly in a program. -func TODO() Context { - return todo -} - -// A CancelFunc tells an operation to abandon its work. -// A CancelFunc does not wait for the work to stop. -// After the first call, subsequent calls to a CancelFunc do nothing. -type CancelFunc func() - -// WithCancel returns a copy of parent with a new Done channel. The returned -// context's Done channel is closed when the returned cancel function is called -// or when the parent context's Done channel is closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithCancel(parent Context) (ctx Context, cancel CancelFunc) { - c := newCancelCtx(parent) - propagateCancel(parent, &c) - return &c, func() { c.cancel(true, Canceled) } -} - -// newCancelCtx returns an initialized cancelCtx. -func newCancelCtx(parent Context) cancelCtx { - return cancelCtx{ - Context: parent, - done: make(chan struct{}), - } -} - -// propagateCancel arranges for child to be canceled when parent is. -func propagateCancel(parent Context, child canceler) { - if parent.Done() == nil { - return // parent is never canceled - } - if p, ok := parentCancelCtx(parent); ok { - p.mu.Lock() - if p.err != nil { - // parent has already been canceled - child.cancel(false, p.err) - } else { - if p.children == nil { - p.children = make(map[canceler]bool) - } - p.children[child] = true - } - p.mu.Unlock() - } else { - go func() { - select { - case <-parent.Done(): - child.cancel(false, parent.Err()) - case <-child.Done(): - } - }() - } -} - -// parentCancelCtx follows a chain of parent references until it finds a -// *cancelCtx. This function understands how each of the concrete types in this -// package represents its parent. -func parentCancelCtx(parent Context) (*cancelCtx, bool) { - for { - switch c := parent.(type) { - case *cancelCtx: - return c, true - case *timerCtx: - return &c.cancelCtx, true - case *valueCtx: - parent = c.Context - default: - return nil, false - } - } -} - -// removeChild removes a context from its parent. -func removeChild(parent Context, child canceler) { - p, ok := parentCancelCtx(parent) - if !ok { - return - } - p.mu.Lock() - if p.children != nil { - delete(p.children, child) - } - p.mu.Unlock() -} - -// A canceler is a context type that can be canceled directly. The -// implementations are *cancelCtx and *timerCtx. -type canceler interface { - cancel(removeFromParent bool, err error) - Done() <-chan struct{} -} - -// A cancelCtx can be canceled. When canceled, it also cancels any children -// that implement canceler. -type cancelCtx struct { - Context - - done chan struct{} // closed by the first cancel call. - - mu sync.Mutex - children map[canceler]bool // set to nil by the first cancel call - err error // set to non-nil by the first cancel call -} - -func (c *cancelCtx) Done() <-chan struct{} { - return c.done -} - -func (c *cancelCtx) Err() error { - c.mu.Lock() - defer c.mu.Unlock() - return c.err -} - -func (c *cancelCtx) String() string { - return fmt.Sprintf("%v.WithCancel", c.Context) -} - -// cancel closes c.done, cancels each of c's children, and, if -// removeFromParent is true, removes c from its parent's children. -func (c *cancelCtx) cancel(removeFromParent bool, err error) { - if err == nil { - panic("context: internal error: missing cancel error") - } - c.mu.Lock() - if c.err != nil { - c.mu.Unlock() - return // already canceled - } - c.err = err - close(c.done) - for child := range c.children { - // NOTE: acquiring the child's lock while holding parent's lock. - child.cancel(false, err) - } - c.children = nil - c.mu.Unlock() - - if removeFromParent { - removeChild(c.Context, c) - } -} - -// WithDeadline returns a copy of the parent context with the deadline adjusted -// to be no later than d. If the parent's deadline is already earlier than d, -// WithDeadline(parent, d) is semantically equivalent to parent. The returned -// context's Done channel is closed when the deadline expires, when the returned -// cancel function is called, or when the parent context's Done channel is -// closed, whichever happens first. -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete. -func WithDeadline(parent Context, deadline time.Time) (Context, CancelFunc) { - if cur, ok := parent.Deadline(); ok && cur.Before(deadline) { - // The current deadline is already sooner than the new one. - return WithCancel(parent) - } - c := &timerCtx{ - cancelCtx: newCancelCtx(parent), - deadline: deadline, - } - propagateCancel(parent, c) - d := deadline.Sub(time.Now()) - if d <= 0 { - c.cancel(true, DeadlineExceeded) // deadline has already passed - return c, func() { c.cancel(true, Canceled) } - } - c.mu.Lock() - defer c.mu.Unlock() - if c.err == nil { - c.timer = time.AfterFunc(d, func() { - c.cancel(true, DeadlineExceeded) - }) - } - return c, func() { c.cancel(true, Canceled) } -} - -// A timerCtx carries a timer and a deadline. It embeds a cancelCtx to -// implement Done and Err. It implements cancel by stopping its timer then -// delegating to cancelCtx.cancel. -type timerCtx struct { - cancelCtx - timer *time.Timer // Under cancelCtx.mu. - - deadline time.Time -} - -func (c *timerCtx) Deadline() (deadline time.Time, ok bool) { - return c.deadline, true -} - -func (c *timerCtx) String() string { - return fmt.Sprintf("%v.WithDeadline(%s [%s])", c.cancelCtx.Context, c.deadline, c.deadline.Sub(time.Now())) -} - -func (c *timerCtx) cancel(removeFromParent bool, err error) { - c.cancelCtx.cancel(false, err) - if removeFromParent { - // Remove this timerCtx from its parent cancelCtx's children. - removeChild(c.cancelCtx.Context, c) - } - c.mu.Lock() - if c.timer != nil { - c.timer.Stop() - c.timer = nil - } - c.mu.Unlock() -} - -// WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)). -// -// Canceling this context releases resources associated with it, so code should -// call cancel as soon as the operations running in this Context complete: -// -// func slowOperationWithTimeout(ctx context.Context) (Result, error) { -// ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond) -// defer cancel() // releases resources if slowOperation completes before timeout elapses -// return slowOperation(ctx) -// } -func WithTimeout(parent Context, timeout time.Duration) (Context, CancelFunc) { - return WithDeadline(parent, time.Now().Add(timeout)) -} - -// WithValue returns a copy of parent in which the value associated with key is -// val. -// -// Use context Values only for request-scoped data that transits processes and -// APIs, not for passing optional parameters to functions. -func WithValue(parent Context, key interface{}, val interface{}) Context { - return &valueCtx{parent, key, val} -} - -// A valueCtx carries a key-value pair. It implements Value for that key and -// delegates all other calls to the embedded Context. -type valueCtx struct { - Context - key, val interface{} -} - -func (c *valueCtx) String() string { - return fmt.Sprintf("%v.WithValue(%#v, %#v)", c.Context, c.key, c.val) -} - -func (c *valueCtx) Value(key interface{}) interface{} { - if c.key == key { - return c.val - } - return c.Context.Value(key) -} diff --git a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq.go b/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq.go deleted file mode 100644 index e3170e333..000000000 --- a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build go1.5 - -package ctxhttp - -import "net/http" - -func canceler(client *http.Client, req *http.Request) func() { - // TODO(djd): Respect any existing value of req.Cancel. - ch := make(chan struct{}) - req.Cancel = ch - - return func() { - close(ch) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq_go14.go b/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq_go14.go deleted file mode 100644 index 56bcbadb8..000000000 --- a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/cancelreq_go14.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !go1.5 - -package ctxhttp - -import "net/http" - -type requestCanceler interface { - CancelRequest(*http.Request) -} - -func canceler(client *http.Client, req *http.Request) func() { - rc, ok := client.Transport.(requestCanceler) - if !ok { - return func() {} - } - return func() { - rc.CancelRequest(req) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp.go b/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp.go deleted file mode 100644 index 26a5e19ac..000000000 --- a/Godeps/_workspace/src/golang.org/x/net/context/ctxhttp/ctxhttp.go +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package ctxhttp provides helper functions for performing context-aware HTTP requests. -package ctxhttp - -import ( - "io" - "net/http" - "net/url" - "strings" - - "golang.org/x/net/context" -) - -func nop() {} - -var ( - testHookContextDoneBeforeHeaders = nop - testHookDoReturned = nop - testHookDidBodyClose = nop -) - -// Do sends an HTTP request with the provided http.Client and returns an HTTP response. -// If the client is nil, http.DefaultClient is used. -// If the context is canceled or times out, ctx.Err() will be returned. -func Do(ctx context.Context, client *http.Client, req *http.Request) (*http.Response, error) { - if client == nil { - client = http.DefaultClient - } - - // Request cancelation changed in Go 1.5, see cancelreq.go and cancelreq_go14.go. - cancel := canceler(client, req) - - type responseAndError struct { - resp *http.Response - err error - } - result := make(chan responseAndError, 1) - - go func() { - resp, err := client.Do(req) - testHookDoReturned() - result <- responseAndError{resp, err} - }() - - var resp *http.Response - - select { - case <-ctx.Done(): - testHookContextDoneBeforeHeaders() - cancel() - // Clean up after the goroutine calling client.Do: - go func() { - if r := <-result; r.resp != nil { - testHookDidBodyClose() - r.resp.Body.Close() - } - }() - return nil, ctx.Err() - case r := <-result: - var err error - resp, err = r.resp, r.err - if err != nil { - return resp, err - } - } - - c := make(chan struct{}) - go func() { - select { - case <-ctx.Done(): - cancel() - case <-c: - // The response's Body is closed. - } - }() - resp.Body = ¬ifyingReader{resp.Body, c} - - return resp, nil -} - -// Get issues a GET request via the Do function. -func Get(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Head issues a HEAD request via the Do function. -func Head(ctx context.Context, client *http.Client, url string) (*http.Response, error) { - req, err := http.NewRequest("HEAD", url, nil) - if err != nil { - return nil, err - } - return Do(ctx, client, req) -} - -// Post issues a POST request via the Do function. -func Post(ctx context.Context, client *http.Client, url string, bodyType string, body io.Reader) (*http.Response, error) { - req, err := http.NewRequest("POST", url, body) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", bodyType) - return Do(ctx, client, req) -} - -// PostForm issues a POST request via the Do function. -func PostForm(ctx context.Context, client *http.Client, url string, data url.Values) (*http.Response, error) { - return Post(ctx, client, url, "application/x-www-form-urlencoded", strings.NewReader(data.Encode())) -} - -// notifyingReader is an io.ReadCloser that closes the notify channel after -// Close is called or a Read fails on the underlying ReadCloser. -type notifyingReader struct { - io.ReadCloser - notify chan<- struct{} -} - -func (r *notifyingReader) Read(p []byte) (int, error) { - n, err := r.ReadCloser.Read(p) - if err != nil && r.notify != nil { - close(r.notify) - r.notify = nil - } - return n, err -} - -func (r *notifyingReader) Close() error { - err := r.ReadCloser.Close() - if r.notify != nil { - close(r.notify) - r.notify = nil - } - return err -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/.travis.yml b/Godeps/_workspace/src/golang.org/x/oauth2/.travis.yml deleted file mode 100644 index a035125c3..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -language: go - -go: - - 1.3 - - 1.4 - -install: - - export GOPATH="$HOME/gopath" - - mkdir -p "$GOPATH/src/golang.org/x" - - mv "$TRAVIS_BUILD_DIR" "$GOPATH/src/golang.org/x/oauth2" - - go get -v -t -d golang.org/x/oauth2/... - -script: - - go test -v golang.org/x/oauth2/... diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/AUTHORS b/Godeps/_workspace/src/golang.org/x/oauth2/AUTHORS deleted file mode 100644 index 15167cd74..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/AUTHORS +++ /dev/null @@ -1,3 +0,0 @@ -# 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/Godeps/_workspace/src/golang.org/x/oauth2/CONTRIBUTING.md b/Godeps/_workspace/src/golang.org/x/oauth2/CONTRIBUTING.md deleted file mode 100644 index 46aa2b12d..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/CONTRIBUTING.md +++ /dev/null @@ -1,31 +0,0 @@ -# Contributing to Go - -Go is an open source project. - -It is the work of hundreds of contributors. We appreciate your help! - - -## Filing issues - -When [filing an issue](https://github.com/golang/oauth2/issues), make sure to answer these five questions: - -1. What version of Go are you using (`go version`)? -2. What operating system and processor architecture are you using? -3. What did you do? -4. What did you expect to see? -5. What did you see instead? - -General questions should go to the [golang-nuts mailing list](https://groups.google.com/group/golang-nuts) instead of the issue tracker. -The gophers there will answer or ask you to file an issue if you've tripped over a bug. - -## Contributing code - -Please read the [Contribution Guidelines](https://golang.org/doc/contribute.html) -before sending patches. - -**We do not accept GitHub pull requests** -(we use [Gerrit](https://code.google.com/p/gerrit/) instead for code review). - -Unless otherwise noted, the Go source files are distributed under -the BSD-style license found in the LICENSE file. - diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/CONTRIBUTORS b/Godeps/_workspace/src/golang.org/x/oauth2/CONTRIBUTORS deleted file mode 100644 index 1c4577e96..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/CONTRIBUTORS +++ /dev/null @@ -1,3 +0,0 @@ -# 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/Godeps/_workspace/src/golang.org/x/oauth2/LICENSE b/Godeps/_workspace/src/golang.org/x/oauth2/LICENSE deleted file mode 100644 index d02f24fd5..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2009 The oauth2 Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/README.md b/Godeps/_workspace/src/golang.org/x/oauth2/README.md deleted file mode 100644 index 0d5141733..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/README.md +++ /dev/null @@ -1,64 +0,0 @@ -# OAuth2 for Go - -[![Build Status](https://travis-ci.org/golang/oauth2.svg?branch=master)](https://travis-ci.org/golang/oauth2) - -oauth2 package contains a client implementation for OAuth 2.0 spec. - -## Installation - -~~~~ -go get golang.org/x/oauth2 -~~~~ - -See godoc for further documentation and examples. - -* [godoc.org/golang.org/x/oauth2](http://godoc.org/golang.org/x/oauth2) -* [godoc.org/golang.org/x/oauth2/google](http://godoc.org/golang.org/x/oauth2/google) - - -## App Engine - -In change 96e89be (March 2015) we removed the `oauth2.Context2` type in favor -of the [`context.Context`](https://golang.org/x/net/context#Context) type from -the `golang.org/x/net/context` package - -This means its no longer possible to use the "Classic App Engine" -`appengine.Context` type with the `oauth2` package. (You're using -Classic App Engine if you import the package `"appengine"`.) - -To work around this, you may use the new `"google.golang.org/appengine"` -package. This package has almost the same API as the `"appengine"` package, -but it can be fetched with `go get` and used on "Managed VMs" and well as -Classic App Engine. - -See the [new `appengine` package's readme](https://github.com/golang/appengine#updating-a-go-app-engine-app) -for information on updating your app. - -If you don't want to update your entire app to use the new App Engine packages, -you may use both sets of packages in parallel, using only the new packages -with the `oauth2` package. - - import ( - "golang.org/x/net/context" - "golang.org/x/oauth2" - "golang.org/x/oauth2/google" - newappengine "google.golang.org/appengine" - newurlfetch "google.golang.org/appengine/urlfetch" - - "appengine" - ) - - func handler(w http.ResponseWriter, r *http.Request) { - var c appengine.Context = appengine.NewContext(r) - c.Infof("Logging a message with the old package") - - var ctx context.Context = newappengine.NewContext(r) - client := &http.Client{ - Transport: &oauth2.Transport{ - Source: google.AppEngineTokenSource(ctx, "scope"), - Base: &newurlfetch.Transport{Context: ctx}, - }, - } - client.Get("...") - } - diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/client_appengine.go b/Godeps/_workspace/src/golang.org/x/oauth2/client_appengine.go deleted file mode 100644 index 8962c49d1..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/client_appengine.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build appengine - -// App Engine hooks. - -package oauth2 - -import ( - "net/http" - - "golang.org/x/net/context" - "golang.org/x/oauth2/internal" - "google.golang.org/appengine/urlfetch" -) - -func init() { - internal.RegisterContextClientFunc(contextClientAppEngine) -} - -func contextClientAppEngine(ctx context.Context) (*http.Client, error) { - return urlfetch.Client(ctx), nil -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine.go deleted file mode 100644 index dc993efb5..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine.go +++ /dev/null @@ -1,86 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package google - -import ( - "sort" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "golang.org/x/oauth2" -) - -// Set at init time by appenginevm_hook.go. If true, we are on App Engine Managed VMs. -var appengineVM bool - -// Set at init time by appengine_hook.go. If nil, we're not on App Engine. -var appengineTokenFunc func(c context.Context, scopes ...string) (token string, expiry time.Time, err error) - -// AppEngineTokenSource returns a token source that fetches tokens -// issued to the current App Engine application's service account. -// If you are implementing a 3-legged OAuth 2.0 flow on App Engine -// that involves user accounts, see oauth2.Config instead. -// -// The provided context must have come from appengine.NewContext. -func AppEngineTokenSource(ctx context.Context, scope ...string) oauth2.TokenSource { - if appengineTokenFunc == nil { - panic("google: AppEngineTokenSource can only be used on App Engine.") - } - scopes := append([]string{}, scope...) - sort.Strings(scopes) - return &appEngineTokenSource{ - ctx: ctx, - scopes: scopes, - key: strings.Join(scopes, " "), - } -} - -// aeTokens helps the fetched tokens to be reused until their expiration. -var ( - aeTokensMu sync.Mutex - aeTokens = make(map[string]*tokenLock) // key is space-separated scopes -) - -type tokenLock struct { - mu sync.Mutex // guards t; held while fetching or updating t - t *oauth2.Token -} - -type appEngineTokenSource struct { - ctx context.Context - scopes []string - key string // to aeTokens map; space-separated scopes -} - -func (ts *appEngineTokenSource) Token() (*oauth2.Token, error) { - if appengineTokenFunc == nil { - panic("google: AppEngineTokenSource can only be used on App Engine.") - } - - aeTokensMu.Lock() - tok, ok := aeTokens[ts.key] - if !ok { - tok = &tokenLock{} - aeTokens[ts.key] = tok - } - aeTokensMu.Unlock() - - tok.mu.Lock() - defer tok.mu.Unlock() - if tok.t.Valid() { - return tok.t, nil - } - access, exp, err := appengineTokenFunc(ts.ctx, ts.scopes...) - if err != nil { - return nil, err - } - tok.t = &oauth2.Token{ - AccessToken: access, - Expiry: exp, - } - return tok.t, nil -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine_hook.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine_hook.go deleted file mode 100644 index 4f42c8b34..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/appengine_hook.go +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build appengine - -package google - -import "google.golang.org/appengine" - -func init() { - appengineTokenFunc = appengine.AccessToken -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/appenginevm_hook.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/appenginevm_hook.go deleted file mode 100644 index 633611cc3..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/appenginevm_hook.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2015 The oauth2 Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build appenginevm - -package google - -import "google.golang.org/appengine" - -func init() { - appengineVM = true - appengineTokenFunc = appengine.AccessToken -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/default.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/default.go deleted file mode 100644 index b95236297..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/default.go +++ /dev/null @@ -1,155 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package google - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "os" - "path/filepath" - "runtime" - - "golang.org/x/net/context" - "golang.org/x/oauth2" - "golang.org/x/oauth2/jwt" - "google.golang.org/cloud/compute/metadata" -) - -// DefaultClient returns an HTTP Client that uses the -// DefaultTokenSource to obtain authentication credentials. -// -// This client should be used when developing services -// that run on Google App Engine or Google Compute Engine -// and use "Application Default Credentials." -// -// For more details, see: -// https://developers.google.com/accounts/docs/application-default-credentials -// -func DefaultClient(ctx context.Context, scope ...string) (*http.Client, error) { - ts, err := DefaultTokenSource(ctx, scope...) - if err != nil { - return nil, err - } - return oauth2.NewClient(ctx, ts), nil -} - -// DefaultTokenSource is a token source that uses -// "Application Default Credentials". -// -// It looks for credentials in the following places, -// preferring the first location found: -// -// 1. A JSON file whose path is specified by the -// GOOGLE_APPLICATION_CREDENTIALS environment variable. -// 2. A JSON file in a location known to the gcloud command-line tool. -// On Windows, this is %APPDATA%/gcloud/application_default_credentials.json. -// On other systems, $HOME/.config/gcloud/application_default_credentials.json. -// 3. On Google App Engine it uses the appengine.AccessToken function. -// 4. On Google Compute Engine and Google App Engine Managed VMs, it fetches -// credentials from the metadata server. -// (In this final case any provided scopes are ignored.) -// -// For more details, see: -// https://developers.google.com/accounts/docs/application-default-credentials -// -func DefaultTokenSource(ctx context.Context, scope ...string) (oauth2.TokenSource, error) { - // First, try the environment variable. - const envVar = "GOOGLE_APPLICATION_CREDENTIALS" - if filename := os.Getenv(envVar); filename != "" { - ts, err := tokenSourceFromFile(ctx, filename, scope) - if err != nil { - return nil, fmt.Errorf("google: error getting credentials using %v environment variable: %v", envVar, err) - } - return ts, nil - } - - // Second, try a well-known file. - filename := wellKnownFile() - _, err := os.Stat(filename) - if err == nil { - ts, err2 := tokenSourceFromFile(ctx, filename, scope) - if err2 == nil { - return ts, nil - } - err = err2 - } else if os.IsNotExist(err) { - err = nil // ignore this error - } - if err != nil { - return nil, fmt.Errorf("google: error getting credentials using well-known file (%v): %v", filename, err) - } - - // Third, if we're on Google App Engine use those credentials. - if appengineTokenFunc != nil && !appengineVM { - return AppEngineTokenSource(ctx, scope...), nil - } - - // Fourth, if we're on Google Compute Engine use the metadata server. - if metadata.OnGCE() { - return ComputeTokenSource(""), nil - } - - // None are found; return helpful error. - const url = "https://developers.google.com/accounts/docs/application-default-credentials" - return nil, fmt.Errorf("google: could not find default credentials. See %v for more information.", url) -} - -func wellKnownFile() string { - const f = "application_default_credentials.json" - if runtime.GOOS == "windows" { - return filepath.Join(os.Getenv("APPDATA"), "gcloud", f) - } - return filepath.Join(guessUnixHomeDir(), ".config", "gcloud", f) -} - -func tokenSourceFromFile(ctx context.Context, filename string, scopes []string) (oauth2.TokenSource, error) { - b, err := ioutil.ReadFile(filename) - if err != nil { - return nil, err - } - var d struct { - // Common fields - Type string - ClientID string `json:"client_id"` - - // User Credential fields - ClientSecret string `json:"client_secret"` - RefreshToken string `json:"refresh_token"` - - // Service Account fields - ClientEmail string `json:"client_email"` - PrivateKeyID string `json:"private_key_id"` - PrivateKey string `json:"private_key"` - } - if err := json.Unmarshal(b, &d); err != nil { - return nil, err - } - switch d.Type { - case "authorized_user": - cfg := &oauth2.Config{ - ClientID: d.ClientID, - ClientSecret: d.ClientSecret, - Scopes: append([]string{}, scopes...), // copy - Endpoint: Endpoint, - } - tok := &oauth2.Token{RefreshToken: d.RefreshToken} - return cfg.TokenSource(ctx, tok), nil - case "service_account": - cfg := &jwt.Config{ - Email: d.ClientEmail, - PrivateKey: []byte(d.PrivateKey), - Scopes: append([]string{}, scopes...), // copy - TokenURL: JWTTokenURL, - } - return cfg.TokenSource(ctx), nil - case "": - return nil, errors.New("missing 'type' field in credentials") - default: - return nil, fmt.Errorf("unknown credential type: %q", d.Type) - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/google.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/google.go deleted file mode 100644 index 0bed73866..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/google.go +++ /dev/null @@ -1,145 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package google provides support for making OAuth2 authorized and -// authenticated HTTP requests to Google APIs. -// It supports the Web server flow, client-side credentials, service accounts, -// Google Compute Engine service accounts, and Google App Engine service -// accounts. -// -// For more information, please read -// https://developers.google.com/accounts/docs/OAuth2 -// and -// https://developers.google.com/accounts/docs/application-default-credentials. -package google - -import ( - "encoding/json" - "errors" - "fmt" - "strings" - "time" - - "golang.org/x/oauth2" - "golang.org/x/oauth2/jwt" - "google.golang.org/cloud/compute/metadata" -) - -// Endpoint is Google's OAuth 2.0 endpoint. -var Endpoint = oauth2.Endpoint{ - AuthURL: "https://accounts.google.com/o/oauth2/auth", - TokenURL: "https://accounts.google.com/o/oauth2/token", -} - -// JWTTokenURL is Google's OAuth 2.0 token URL to use with the JWT flow. -const JWTTokenURL = "https://accounts.google.com/o/oauth2/token" - -// ConfigFromJSON uses a Google Developers Console client_credentials.json -// file to construct a config. -// client_credentials.json can be downloadable from https://console.developers.google.com, -// under "APIs & Auth" > "Credentials". Download the Web application credentials in the -// JSON format and provide the contents of the file as jsonKey. -func ConfigFromJSON(jsonKey []byte, scope ...string) (*oauth2.Config, error) { - type cred struct { - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret"` - RedirectURIs []string `json:"redirect_uris"` - AuthURI string `json:"auth_uri"` - TokenURI string `json:"token_uri"` - } - var j struct { - Web *cred `json:"web"` - Installed *cred `json:"installed"` - } - if err := json.Unmarshal(jsonKey, &j); err != nil { - return nil, err - } - var c *cred - switch { - case j.Web != nil: - c = j.Web - case j.Installed != nil: - c = j.Installed - default: - return nil, fmt.Errorf("oauth2/google: no credentials found") - } - if len(c.RedirectURIs) < 1 { - return nil, errors.New("oauth2/google: missing redirect URL in the client_credentials.json") - } - return &oauth2.Config{ - ClientID: c.ClientID, - ClientSecret: c.ClientSecret, - RedirectURL: c.RedirectURIs[0], - Scopes: scope, - Endpoint: oauth2.Endpoint{ - AuthURL: c.AuthURI, - TokenURL: c.TokenURI, - }, - }, nil -} - -// JWTConfigFromJSON uses a Google Developers service account JSON key file to read -// the credentials that authorize and authenticate the requests. -// Create a service account on "Credentials" page under "APIs & Auth" for your -// project at https://console.developers.google.com to download a JSON key file. -func JWTConfigFromJSON(jsonKey []byte, scope ...string) (*jwt.Config, error) { - var key struct { - Email string `json:"client_email"` - PrivateKey string `json:"private_key"` - } - if err := json.Unmarshal(jsonKey, &key); err != nil { - return nil, err - } - return &jwt.Config{ - Email: key.Email, - PrivateKey: []byte(key.PrivateKey), - Scopes: scope, - TokenURL: JWTTokenURL, - }, nil -} - -// ComputeTokenSource returns a token source that fetches access tokens -// from Google Compute Engine (GCE)'s metadata server. It's only valid to use -// this token source if your program is running on a GCE instance. -// If no account is specified, "default" is used. -// Further information about retrieving access tokens from the GCE metadata -// server can be found at https://cloud.google.com/compute/docs/authentication. -func ComputeTokenSource(account string) oauth2.TokenSource { - return oauth2.ReuseTokenSource(nil, computeSource{account: account}) -} - -type computeSource struct { - account string -} - -func (cs computeSource) Token() (*oauth2.Token, error) { - if !metadata.OnGCE() { - return nil, errors.New("oauth2/google: can't get a token from the metadata service; not running on GCE") - } - acct := cs.account - if acct == "" { - acct = "default" - } - tokenJSON, err := metadata.Get("instance/service-accounts/" + acct + "/token") - if err != nil { - return nil, err - } - var res struct { - AccessToken string `json:"access_token"` - ExpiresInSec int `json:"expires_in"` - TokenType string `json:"token_type"` - } - err = json.NewDecoder(strings.NewReader(tokenJSON)).Decode(&res) - if err != nil { - return nil, fmt.Errorf("oauth2/google: invalid token JSON from metadata: %v", err) - } - if res.ExpiresInSec == 0 || res.AccessToken == "" { - return nil, fmt.Errorf("oauth2/google: incomplete token received from metadata") - } - return &oauth2.Token{ - AccessToken: res.AccessToken, - TokenType: res.TokenType, - Expiry: time.Now().Add(time.Duration(res.ExpiresInSec) * time.Second), - }, nil -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/jwt.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/jwt.go deleted file mode 100644 index b91991786..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/jwt.go +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package google - -import ( - "crypto/rsa" - "fmt" - "time" - - "golang.org/x/oauth2" - "golang.org/x/oauth2/internal" - "golang.org/x/oauth2/jws" -) - -// JWTAccessTokenSourceFromJSON uses a Google Developers service account JSON -// key file to read the credentials that authorize and authenticate the -// requests, and returns a TokenSource that does not use any OAuth2 flow but -// instead creates a JWT and sends that as the access token. -// The audience is typically a URL that specifies the scope of the credentials. -// -// Note that this is not a standard OAuth flow, but rather an -// optimization supported by a few Google services. -// Unless you know otherwise, you should use JWTConfigFromJSON instead. -func JWTAccessTokenSourceFromJSON(jsonKey []byte, audience string) (oauth2.TokenSource, error) { - cfg, err := JWTConfigFromJSON(jsonKey) - if err != nil { - return nil, fmt.Errorf("google: could not parse JSON key: %v", err) - } - pk, err := internal.ParseKey(cfg.PrivateKey) - if err != nil { - return nil, fmt.Errorf("google: could not parse key: %v", err) - } - ts := &jwtAccessTokenSource{ - email: cfg.Email, - audience: audience, - pk: pk, - } - tok, err := ts.Token() - if err != nil { - return nil, err - } - return oauth2.ReuseTokenSource(tok, ts), nil -} - -type jwtAccessTokenSource struct { - email, audience string - pk *rsa.PrivateKey -} - -func (ts *jwtAccessTokenSource) Token() (*oauth2.Token, error) { - iat := time.Now() - exp := iat.Add(time.Hour) - cs := &jws.ClaimSet{ - Iss: ts.email, - Sub: ts.email, - Aud: ts.audience, - Iat: iat.Unix(), - Exp: exp.Unix(), - } - hdr := &jws.Header{ - Algorithm: "RS256", - Typ: "JWT", - } - msg, err := jws.Encode(hdr, cs, ts.pk) - if err != nil { - return nil, fmt.Errorf("google: could not encode JWT: %v", err) - } - return &oauth2.Token{AccessToken: msg, TokenType: "Bearer", Expiry: exp}, nil -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/sdk.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/sdk.go deleted file mode 100644 index d29a3bb9b..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/sdk.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package google - -import ( - "encoding/json" - "errors" - "fmt" - "net/http" - "os" - "os/user" - "path/filepath" - "runtime" - "strings" - "time" - - "golang.org/x/net/context" - "golang.org/x/oauth2" - "golang.org/x/oauth2/internal" -) - -type sdkCredentials struct { - Data []struct { - Credential struct { - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret"` - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - TokenExpiry *time.Time `json:"token_expiry"` - } `json:"credential"` - Key struct { - Account string `json:"account"` - Scope string `json:"scope"` - } `json:"key"` - } -} - -// An SDKConfig provides access to tokens from an account already -// authorized via the Google Cloud SDK. -type SDKConfig struct { - conf oauth2.Config - initialToken *oauth2.Token -} - -// NewSDKConfig creates an SDKConfig for the given Google Cloud SDK -// account. If account is empty, the account currently active in -// Google Cloud SDK properties is used. -// Google Cloud SDK credentials must be created by running `gcloud auth` -// before using this function. -// The Google Cloud SDK is available at https://cloud.google.com/sdk/. -func NewSDKConfig(account string) (*SDKConfig, error) { - configPath, err := sdkConfigPath() - if err != nil { - return nil, fmt.Errorf("oauth2/google: error getting SDK config path: %v", err) - } - credentialsPath := filepath.Join(configPath, "credentials") - f, err := os.Open(credentialsPath) - if err != nil { - return nil, fmt.Errorf("oauth2/google: failed to load SDK credentials: %v", err) - } - defer f.Close() - - var c sdkCredentials - if err := json.NewDecoder(f).Decode(&c); err != nil { - return nil, fmt.Errorf("oauth2/google: failed to decode SDK credentials from %q: %v", credentialsPath, err) - } - if len(c.Data) == 0 { - return nil, fmt.Errorf("oauth2/google: no credentials found in %q, run `gcloud auth login` to create one", credentialsPath) - } - if account == "" { - propertiesPath := filepath.Join(configPath, "properties") - f, err := os.Open(propertiesPath) - if err != nil { - return nil, fmt.Errorf("oauth2/google: failed to load SDK properties: %v", err) - } - defer f.Close() - ini, err := internal.ParseINI(f) - if err != nil { - return nil, fmt.Errorf("oauth2/google: failed to parse SDK properties %q: %v", propertiesPath, err) - } - core, ok := ini["core"] - if !ok { - return nil, fmt.Errorf("oauth2/google: failed to find [core] section in %v", ini) - } - active, ok := core["account"] - if !ok { - return nil, fmt.Errorf("oauth2/google: failed to find %q attribute in %v", "account", core) - } - account = active - } - - for _, d := range c.Data { - if account == "" || d.Key.Account == account { - if d.Credential.AccessToken == "" && d.Credential.RefreshToken == "" { - return nil, fmt.Errorf("oauth2/google: no token available for account %q", account) - } - var expiry time.Time - if d.Credential.TokenExpiry != nil { - expiry = *d.Credential.TokenExpiry - } - return &SDKConfig{ - conf: oauth2.Config{ - ClientID: d.Credential.ClientID, - ClientSecret: d.Credential.ClientSecret, - Scopes: strings.Split(d.Key.Scope, " "), - Endpoint: Endpoint, - RedirectURL: "oob", - }, - initialToken: &oauth2.Token{ - AccessToken: d.Credential.AccessToken, - RefreshToken: d.Credential.RefreshToken, - Expiry: expiry, - }, - }, nil - } - } - return nil, fmt.Errorf("oauth2/google: no such credentials for account %q", account) -} - -// Client returns an HTTP client using Google Cloud SDK credentials to -// authorize requests. The token will auto-refresh as necessary. The -// underlying http.RoundTripper will be obtained using the provided -// context. The returned client and its Transport should not be -// modified. -func (c *SDKConfig) Client(ctx context.Context) *http.Client { - return &http.Client{ - Transport: &oauth2.Transport{ - Source: c.TokenSource(ctx), - }, - } -} - -// TokenSource returns an oauth2.TokenSource that retrieve tokens from -// Google Cloud SDK credentials using the provided context. -// It will returns the current access token stored in the credentials, -// and refresh it when it expires, but it won't update the credentials -// with the new access token. -func (c *SDKConfig) TokenSource(ctx context.Context) oauth2.TokenSource { - return c.conf.TokenSource(ctx, c.initialToken) -} - -// Scopes are the OAuth 2.0 scopes the current account is authorized for. -func (c *SDKConfig) Scopes() []string { - return c.conf.Scopes -} - -// sdkConfigPath tries to guess where the gcloud config is located. -// It can be overridden during tests. -var sdkConfigPath = func() (string, error) { - if runtime.GOOS == "windows" { - return filepath.Join(os.Getenv("APPDATA"), "gcloud"), nil - } - homeDir := guessUnixHomeDir() - if homeDir == "" { - return "", errors.New("unable to get current user home directory: os/user lookup failed; $HOME is empty") - } - return filepath.Join(homeDir, ".config", "gcloud"), nil -} - -func guessUnixHomeDir() string { - usr, err := user.Current() - if err == nil { - return usr.HomeDir - } - return os.Getenv("HOME") -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/internal/oauth2.go b/Godeps/_workspace/src/golang.org/x/oauth2/internal/oauth2.go deleted file mode 100644 index fbe1028d6..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/internal/oauth2.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package internal contains support packages for oauth2 package. -package internal - -import ( - "bufio" - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" - "fmt" - "io" - "strings" -) - -// ParseKey converts the binary contents of a private key file -// to an *rsa.PrivateKey. It detects whether the private key is in a -// PEM container or not. If so, it extracts the the private key -// from PEM container before conversion. It only supports PEM -// containers with no passphrase. -func ParseKey(key []byte) (*rsa.PrivateKey, error) { - block, _ := pem.Decode(key) - if block != nil { - key = block.Bytes - } - parsedKey, err := x509.ParsePKCS8PrivateKey(key) - if err != nil { - parsedKey, err = x509.ParsePKCS1PrivateKey(key) - if err != nil { - return nil, fmt.Errorf("private key should be a PEM or plain PKSC1 or PKCS8; parse error: %v", err) - } - } - parsed, ok := parsedKey.(*rsa.PrivateKey) - if !ok { - return nil, errors.New("private key is invalid") - } - return parsed, nil -} - -func ParseINI(ini io.Reader) (map[string]map[string]string, error) { - result := map[string]map[string]string{ - "": map[string]string{}, // root section - } - scanner := bufio.NewScanner(ini) - currentSection := "" - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - if strings.HasPrefix(line, ";") { - // comment. - continue - } - if strings.HasPrefix(line, "[") && strings.HasSuffix(line, "]") { - currentSection = strings.TrimSpace(line[1 : len(line)-1]) - result[currentSection] = map[string]string{} - continue - } - parts := strings.SplitN(line, "=", 2) - if len(parts) == 2 && parts[0] != "" { - result[currentSection][strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1]) - } - } - if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("error scanning ini: %v", err) - } - return result, nil -} - -func CondVal(v string) []string { - if v == "" { - return nil - } - return []string{v} -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/internal/token.go b/Godeps/_workspace/src/golang.org/x/oauth2/internal/token.go deleted file mode 100644 index 39caf6c61..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/internal/token.go +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package internal contains support packages for oauth2 package. -package internal - -import ( - "encoding/json" - "fmt" - "io" - "io/ioutil" - "mime" - "net/http" - "net/url" - "strconv" - "strings" - "time" - - "golang.org/x/net/context" -) - -// Token represents the crendentials used to authorize -// the requests to access protected resources on the OAuth 2.0 -// provider's backend. -// -// This type is a mirror of oauth2.Token and exists to break -// an otherwise-circular dependency. Other internal packages -// should convert this Token into an oauth2.Token before use. -type Token struct { - // AccessToken is the token that authorizes and authenticates - // the requests. - AccessToken string - - // TokenType is the type of token. - // The Type method returns either this or "Bearer", the default. - TokenType string - - // RefreshToken is a token that's used by the application - // (as opposed to the user) to refresh the access token - // if it expires. - RefreshToken string - - // Expiry is the optional expiration time of the access token. - // - // If zero, TokenSource implementations will reuse the same - // token forever and RefreshToken or equivalent - // mechanisms for that TokenSource will not be used. - Expiry time.Time - - // Raw optionally contains extra metadata from the server - // when updating a token. - Raw interface{} -} - -// tokenJSON is the struct representing the HTTP response from OAuth2 -// providers returning a token in JSON form. -type tokenJSON struct { - AccessToken string `json:"access_token"` - TokenType string `json:"token_type"` - RefreshToken string `json:"refresh_token"` - ExpiresIn expirationTime `json:"expires_in"` // at least PayPal returns string, while most return number - Expires expirationTime `json:"expires"` // broken Facebook spelling of expires_in -} - -func (e *tokenJSON) expiry() (t time.Time) { - if v := e.ExpiresIn; v != 0 { - return time.Now().Add(time.Duration(v) * time.Second) - } - if v := e.Expires; v != 0 { - return time.Now().Add(time.Duration(v) * time.Second) - } - return -} - -type expirationTime int32 - -func (e *expirationTime) UnmarshalJSON(b []byte) error { - var n json.Number - err := json.Unmarshal(b, &n) - if err != nil { - return err - } - i, err := n.Int64() - if err != nil { - return err - } - *e = expirationTime(i) - return nil -} - -var brokenAuthHeaderProviders = []string{ - "https://accounts.google.com/", - "https://api.dropbox.com/", - "https://api.instagram.com/", - "https://api.netatmo.net/", - "https://api.odnoklassniki.ru/", - "https://api.pushbullet.com/", - "https://api.soundcloud.com/", - "https://api.twitch.tv/", - "https://app.box.com/", - "https://connect.stripe.com/", - "https://login.microsoftonline.com/", - "https://login.salesforce.com/", - "https://oauth.sandbox.trainingpeaks.com/", - "https://oauth.trainingpeaks.com/", - "https://oauth.vk.com/", - "https://slack.com/", - "https://test-sandbox.auth.corp.google.com", - "https://test.salesforce.com/", - "https://user.gini.net/", - "https://www.douban.com/", - "https://www.googleapis.com/", - "https://www.linkedin.com/", - "https://www.strava.com/oauth/", -} - -func RegisterBrokenAuthHeaderProvider(tokenURL string) { - brokenAuthHeaderProviders = append(brokenAuthHeaderProviders, tokenURL) -} - -// providerAuthHeaderWorks reports whether the OAuth2 server identified by the tokenURL -// implements the OAuth2 spec correctly -// See https://code.google.com/p/goauth2/issues/detail?id=31 for background. -// In summary: -// - Reddit only accepts client secret in the Authorization header -// - Dropbox accepts either it in URL param or Auth header, but not both. -// - Google only accepts URL param (not spec compliant?), not Auth header -// - Stripe only accepts client secret in Auth header with Bearer method, not Basic -func providerAuthHeaderWorks(tokenURL string) bool { - for _, s := range brokenAuthHeaderProviders { - if strings.HasPrefix(tokenURL, s) { - // Some sites fail to implement the OAuth2 spec fully. - return false - } - } - - // Assume the provider implements the spec properly - // otherwise. We can add more exceptions as they're - // discovered. We will _not_ be adding configurable hooks - // to this package to let users select server bugs. - return true -} - -func RetrieveToken(ctx context.Context, ClientID, ClientSecret, TokenURL string, v url.Values) (*Token, error) { - hc, err := ContextClient(ctx) - if err != nil { - return nil, err - } - v.Set("client_id", ClientID) - bustedAuth := !providerAuthHeaderWorks(TokenURL) - if bustedAuth && ClientSecret != "" { - v.Set("client_secret", ClientSecret) - } - req, err := http.NewRequest("POST", TokenURL, strings.NewReader(v.Encode())) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - if !bustedAuth { - req.SetBasicAuth(ClientID, ClientSecret) - } - r, err := hc.Do(req) - if err != nil { - return nil, err - } - defer r.Body.Close() - body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1<<20)) - if err != nil { - return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) - } - if code := r.StatusCode; code < 200 || code > 299 { - return nil, fmt.Errorf("oauth2: cannot fetch token: %v\nResponse: %s", r.Status, body) - } - - var token *Token - content, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) - switch content { - case "application/x-www-form-urlencoded", "text/plain": - vals, err := url.ParseQuery(string(body)) - if err != nil { - return nil, err - } - token = &Token{ - AccessToken: vals.Get("access_token"), - TokenType: vals.Get("token_type"), - RefreshToken: vals.Get("refresh_token"), - Raw: vals, - } - e := vals.Get("expires_in") - if e == "" { - // TODO(jbd): Facebook's OAuth2 implementation is broken and - // returns expires_in field in expires. Remove the fallback to expires, - // when Facebook fixes their implementation. - e = vals.Get("expires") - } - expires, _ := strconv.Atoi(e) - if expires != 0 { - token.Expiry = time.Now().Add(time.Duration(expires) * time.Second) - } - default: - var tj tokenJSON - if err = json.Unmarshal(body, &tj); err != nil { - return nil, err - } - token = &Token{ - AccessToken: tj.AccessToken, - TokenType: tj.TokenType, - RefreshToken: tj.RefreshToken, - Expiry: tj.expiry(), - Raw: make(map[string]interface{}), - } - json.Unmarshal(body, &token.Raw) // no error checks for optional fields - } - // Don't overwrite `RefreshToken` with an empty value - // if this was a token refreshing request. - if token.RefreshToken == "" { - token.RefreshToken = v.Get("refresh_token") - } - return token, nil -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/internal/transport.go b/Godeps/_workspace/src/golang.org/x/oauth2/internal/transport.go deleted file mode 100644 index f1f173e34..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/internal/transport.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package internal contains support packages for oauth2 package. -package internal - -import ( - "net/http" - - "golang.org/x/net/context" -) - -// HTTPClient is the context key to use with golang.org/x/net/context's -// WithValue function to associate an *http.Client value with a context. -var HTTPClient ContextKey - -// ContextKey is just an empty struct. It exists so HTTPClient can be -// an immutable public variable with a unique type. It's immutable -// because nobody else can create a ContextKey, being unexported. -type ContextKey struct{} - -// ContextClientFunc is a func which tries to return an *http.Client -// given a Context value. If it returns an error, the search stops -// with that error. If it returns (nil, nil), the search continues -// down the list of registered funcs. -type ContextClientFunc func(context.Context) (*http.Client, error) - -var contextClientFuncs []ContextClientFunc - -func RegisterContextClientFunc(fn ContextClientFunc) { - contextClientFuncs = append(contextClientFuncs, fn) -} - -func ContextClient(ctx context.Context) (*http.Client, error) { - if ctx != nil { - if hc, ok := ctx.Value(HTTPClient).(*http.Client); ok { - return hc, nil - } - } - for _, fn := range contextClientFuncs { - c, err := fn(ctx) - if err != nil { - return nil, err - } - if c != nil { - return c, nil - } - } - return http.DefaultClient, nil -} - -func ContextTransport(ctx context.Context) http.RoundTripper { - hc, err := ContextClient(ctx) - // This is a rare error case (somebody using nil on App Engine). - if err != nil { - return ErrorTransport{err} - } - return hc.Transport -} - -// ErrorTransport returns the specified error on RoundTrip. -// This RoundTripper should be used in rare error cases where -// error handling can be postponed to response handling time. -type ErrorTransport struct{ Err error } - -func (t ErrorTransport) RoundTrip(*http.Request) (*http.Response, error) { - return nil, t.Err -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/jws/jws.go b/Godeps/_workspace/src/golang.org/x/oauth2/jws/jws.go deleted file mode 100644 index b46edb27c..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/jws/jws.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package jws provides encoding and decoding utilities for -// signed JWS messages. -package jws - -import ( - "bytes" - "crypto" - "crypto/rand" - "crypto/rsa" - "crypto/sha256" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "strings" - "time" -) - -// ClaimSet contains information about the JWT signature including the -// permissions being requested (scopes), the target of the token, the issuer, -// the time the token was issued, and the lifetime of the token. -type ClaimSet struct { - Iss string `json:"iss"` // email address of the client_id of the application making the access token request - Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests - Aud string `json:"aud"` // descriptor of the intended target of the assertion (Optional). - Exp int64 `json:"exp"` // the expiration time of the assertion (seconds since Unix epoch) - Iat int64 `json:"iat"` // the time the assertion was issued (seconds since Unix epoch) - Typ string `json:"typ,omitempty"` // token type (Optional). - - // Email for which the application is requesting delegated access (Optional). - Sub string `json:"sub,omitempty"` - - // The old name of Sub. Client keeps setting Prn to be - // complaint with legacy OAuth 2.0 providers. (Optional) - Prn string `json:"prn,omitempty"` - - // See http://tools.ietf.org/html/draft-jones-json-web-token-10#section-4.3 - // This array is marshalled using custom code (see (c *ClaimSet) encode()). - PrivateClaims map[string]interface{} `json:"-"` -} - -func (c *ClaimSet) encode() (string, error) { - // Reverting time back for machines whose time is not perfectly in sync. - // If client machine's time is in the future according - // to Google servers, an access token will not be issued. - now := time.Now().Add(-10 * time.Second) - if c.Iat == 0 { - c.Iat = now.Unix() - } - if c.Exp == 0 { - c.Exp = now.Add(time.Hour).Unix() - } - if c.Exp < c.Iat { - return "", fmt.Errorf("jws: invalid Exp = %v; must be later than Iat = %v", c.Exp, c.Iat) - } - - b, err := json.Marshal(c) - if err != nil { - return "", err - } - - if len(c.PrivateClaims) == 0 { - return base64Encode(b), nil - } - - // Marshal private claim set and then append it to b. - prv, err := json.Marshal(c.PrivateClaims) - if err != nil { - return "", fmt.Errorf("jws: invalid map of private claims %v", c.PrivateClaims) - } - - // Concatenate public and private claim JSON objects. - if !bytes.HasSuffix(b, []byte{'}'}) { - return "", fmt.Errorf("jws: invalid JSON %s", b) - } - if !bytes.HasPrefix(prv, []byte{'{'}) { - return "", fmt.Errorf("jws: invalid JSON %s", prv) - } - b[len(b)-1] = ',' // Replace closing curly brace with a comma. - b = append(b, prv[1:]...) // Append private claims. - return base64Encode(b), nil -} - -// Header represents the header for the signed JWS payloads. -type Header struct { - // The algorithm used for signature. - Algorithm string `json:"alg"` - - // Represents the token type. - Typ string `json:"typ"` -} - -func (h *Header) encode() (string, error) { - b, err := json.Marshal(h) - if err != nil { - return "", err - } - return base64Encode(b), nil -} - -// Decode decodes a claim set from a JWS payload. -func Decode(payload string) (*ClaimSet, error) { - // decode returned id token to get expiry - s := strings.Split(payload, ".") - if len(s) < 2 { - // TODO(jbd): Provide more context about the error. - return nil, errors.New("jws: invalid token received") - } - decoded, err := base64Decode(s[1]) - if err != nil { - return nil, err - } - c := &ClaimSet{} - err = json.NewDecoder(bytes.NewBuffer(decoded)).Decode(c) - return c, err -} - -// Signer returns a signature for the given data. -type Signer func(data []byte) (sig []byte, err error) - -// EncodeWithSigner encodes a header and claim set with the provided signer. -func EncodeWithSigner(header *Header, c *ClaimSet, sg Signer) (string, error) { - head, err := header.encode() - if err != nil { - return "", err - } - cs, err := c.encode() - if err != nil { - return "", err - } - ss := fmt.Sprintf("%s.%s", head, cs) - sig, err := sg([]byte(ss)) - if err != nil { - return "", err - } - return fmt.Sprintf("%s.%s", ss, base64Encode(sig)), nil -} - -// Encode encodes a signed JWS with provided header and claim set. -// This invokes EncodeWithSigner using crypto/rsa.SignPKCS1v15 with the given RSA private key. -func Encode(header *Header, c *ClaimSet, key *rsa.PrivateKey) (string, error) { - sg := func(data []byte) (sig []byte, err error) { - h := sha256.New() - h.Write([]byte(data)) - return rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, h.Sum(nil)) - } - return EncodeWithSigner(header, c, sg) -} - -// base64Encode returns and Base64url encoded version of the input string with any -// trailing "=" stripped. -func base64Encode(b []byte) string { - return strings.TrimRight(base64.URLEncoding.EncodeToString(b), "=") -} - -// base64Decode decodes the Base64url encoded string -func base64Decode(s string) ([]byte, error) { - // add back missing padding - switch len(s) % 4 { - case 1: - s += "===" - case 2: - s += "==" - case 3: - s += "=" - } - return base64.URLEncoding.DecodeString(s) -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt.go b/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt.go deleted file mode 100644 index 2ffad21a6..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/jwt/jwt.go +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package jwt implements the OAuth 2.0 JSON Web Token flow, commonly -// known as "two-legged OAuth 2.0". -// -// See: https://tools.ietf.org/html/draft-ietf-oauth-jwt-bearer-12 -package jwt - -import ( - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "strings" - "time" - - "golang.org/x/net/context" - "golang.org/x/oauth2" - "golang.org/x/oauth2/internal" - "golang.org/x/oauth2/jws" -) - -var ( - defaultGrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer" - defaultHeader = &jws.Header{Algorithm: "RS256", Typ: "JWT"} -) - -// Config is the configuration for using JWT to fetch tokens, -// commonly known as "two-legged OAuth 2.0". -type Config struct { - // Email is the OAuth client identifier used when communicating with - // the configured OAuth provider. - Email string - - // PrivateKey contains the contents of an RSA private key or the - // contents of a PEM file that contains a private key. The provided - // private key is used to sign JWT payloads. - // PEM containers with a passphrase are not supported. - // Use the following command to convert a PKCS 12 file into a PEM. - // - // $ openssl pkcs12 -in key.p12 -out key.pem -nodes - // - PrivateKey []byte - - // Subject is the optional user to impersonate. - Subject string - - // Scopes optionally specifies a list of requested permission scopes. - Scopes []string - - // TokenURL is the endpoint required to complete the 2-legged JWT flow. - TokenURL string - - // Expires optionally specifies how long the token is valid for. - Expires time.Duration -} - -// TokenSource returns a JWT TokenSource using the configuration -// in c and the HTTP client from the provided context. -func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSource { - return oauth2.ReuseTokenSource(nil, jwtSource{ctx, c}) -} - -// Client returns an HTTP client wrapping the context's -// HTTP transport and adding Authorization headers with tokens -// obtained from c. -// -// The returned client and its Transport should not be modified. -func (c *Config) Client(ctx context.Context) *http.Client { - return oauth2.NewClient(ctx, c.TokenSource(ctx)) -} - -// jwtSource is a source that always does a signed JWT request for a token. -// It should typically be wrapped with a reuseTokenSource. -type jwtSource struct { - ctx context.Context - conf *Config -} - -func (js jwtSource) Token() (*oauth2.Token, error) { - pk, err := internal.ParseKey(js.conf.PrivateKey) - if err != nil { - return nil, err - } - hc := oauth2.NewClient(js.ctx, nil) - claimSet := &jws.ClaimSet{ - Iss: js.conf.Email, - Scope: strings.Join(js.conf.Scopes, " "), - Aud: js.conf.TokenURL, - } - if subject := js.conf.Subject; subject != "" { - claimSet.Sub = subject - // prn is the old name of sub. Keep setting it - // to be compatible with legacy OAuth 2.0 providers. - claimSet.Prn = subject - } - if t := js.conf.Expires; t > 0 { - claimSet.Exp = time.Now().Add(t).Unix() - } - payload, err := jws.Encode(defaultHeader, claimSet, pk) - if err != nil { - return nil, err - } - v := url.Values{} - v.Set("grant_type", defaultGrantType) - v.Set("assertion", payload) - resp, err := hc.PostForm(js.conf.TokenURL, v) - if err != nil { - return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1<<20)) - if err != nil { - return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) - } - if c := resp.StatusCode; c < 200 || c > 299 { - return nil, fmt.Errorf("oauth2: cannot fetch token: %v\nResponse: %s", resp.Status, body) - } - // tokenRes is the JSON response body. - var tokenRes struct { - AccessToken string `json:"access_token"` - TokenType string `json:"token_type"` - IDToken string `json:"id_token"` - ExpiresIn int64 `json:"expires_in"` // relative seconds from now - } - if err := json.Unmarshal(body, &tokenRes); err != nil { - return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err) - } - token := &oauth2.Token{ - AccessToken: tokenRes.AccessToken, - TokenType: tokenRes.TokenType, - } - raw := make(map[string]interface{}) - json.Unmarshal(body, &raw) // no error checks for optional fields - token = token.WithExtra(raw) - - if secs := tokenRes.ExpiresIn; secs > 0 { - token.Expiry = time.Now().Add(time.Duration(secs) * time.Second) - } - if v := tokenRes.IDToken; v != "" { - // decode returned id token to get expiry - claimSet, err := jws.Decode(v) - if err != nil { - return nil, fmt.Errorf("oauth2: error decoding JWT token: %v", err) - } - token.Expiry = time.Unix(claimSet.Exp, 0) - } - return token, nil -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/oauth2.go b/Godeps/_workspace/src/golang.org/x/oauth2/oauth2.go deleted file mode 100644 index 9b7b977da..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/oauth2.go +++ /dev/null @@ -1,337 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package oauth2 provides support for making -// OAuth2 authorized and authenticated HTTP requests. -// It can additionally grant authorization with Bearer JWT. -package oauth2 - -import ( - "bytes" - "errors" - "net/http" - "net/url" - "strings" - "sync" - - "golang.org/x/net/context" - "golang.org/x/oauth2/internal" -) - -// NoContext is the default context you should supply if not using -// your own context.Context (see https://golang.org/x/net/context). -var NoContext = context.TODO() - -// RegisterBrokenAuthHeaderProvider registers an OAuth2 server -// identified by the tokenURL prefix as an OAuth2 implementation -// which doesn't support the HTTP Basic authentication -// scheme to authenticate with the authorization server. -// Once a server is registered, credentials (client_id and client_secret) -// will be passed as query parameters rather than being present -// in the Authorization header. -// See https://code.google.com/p/goauth2/issues/detail?id=31 for background. -func RegisterBrokenAuthHeaderProvider(tokenURL string) { - internal.RegisterBrokenAuthHeaderProvider(tokenURL) -} - -// Config describes a typical 3-legged OAuth2 flow, with both the -// client application information and the server's endpoint URLs. -type Config struct { - // ClientID is the application's ID. - ClientID string - - // ClientSecret is the application's secret. - ClientSecret string - - // Endpoint contains the resource server's token endpoint - // URLs. These are constants specific to each server and are - // often available via site-specific packages, such as - // google.Endpoint or github.Endpoint. - Endpoint Endpoint - - // RedirectURL is the URL to redirect users going through - // the OAuth flow, after the resource owner's URLs. - RedirectURL string - - // Scope specifies optional requested permissions. - Scopes []string -} - -// A TokenSource is anything that can return a token. -type TokenSource interface { - // Token returns a token or an error. - // Token must be safe for concurrent use by multiple goroutines. - // The returned Token must not be modified. - Token() (*Token, error) -} - -// Endpoint contains the OAuth 2.0 provider's authorization and token -// endpoint URLs. -type Endpoint struct { - AuthURL string - TokenURL string -} - -var ( - // AccessTypeOnline and AccessTypeOffline are options passed - // to the Options.AuthCodeURL method. They modify the - // "access_type" field that gets sent in the URL returned by - // AuthCodeURL. - // - // Online is the default if neither is specified. If your - // application needs to refresh access tokens when the user - // is not present at the browser, then use offline. This will - // result in your application obtaining a refresh token the - // first time your application exchanges an authorization - // code for a user. - AccessTypeOnline AuthCodeOption = SetAuthURLParam("access_type", "online") - AccessTypeOffline AuthCodeOption = SetAuthURLParam("access_type", "offline") - - // ApprovalForce forces the users to view the consent dialog - // and confirm the permissions request at the URL returned - // from AuthCodeURL, even if they've already done so. - ApprovalForce AuthCodeOption = SetAuthURLParam("approval_prompt", "force") -) - -// An AuthCodeOption is passed to Config.AuthCodeURL. -type AuthCodeOption interface { - setValue(url.Values) -} - -type setParam struct{ k, v string } - -func (p setParam) setValue(m url.Values) { m.Set(p.k, p.v) } - -// SetAuthURLParam builds an AuthCodeOption which passes key/value parameters -// to a provider's authorization endpoint. -func SetAuthURLParam(key, value string) AuthCodeOption { - return setParam{key, value} -} - -// AuthCodeURL returns a URL to OAuth 2.0 provider's consent page -// that asks for permissions for the required scopes explicitly. -// -// State is a token to protect the user from CSRF attacks. You must -// always provide a non-zero string and validate that it matches the -// the state query parameter on your redirect callback. -// See http://tools.ietf.org/html/rfc6749#section-10.12 for more info. -// -// Opts may include AccessTypeOnline or AccessTypeOffline, as well -// as ApprovalForce. -func (c *Config) AuthCodeURL(state string, opts ...AuthCodeOption) string { - var buf bytes.Buffer - buf.WriteString(c.Endpoint.AuthURL) - v := url.Values{ - "response_type": {"code"}, - "client_id": {c.ClientID}, - "redirect_uri": internal.CondVal(c.RedirectURL), - "scope": internal.CondVal(strings.Join(c.Scopes, " ")), - "state": internal.CondVal(state), - } - for _, opt := range opts { - opt.setValue(v) - } - if strings.Contains(c.Endpoint.AuthURL, "?") { - buf.WriteByte('&') - } else { - buf.WriteByte('?') - } - buf.WriteString(v.Encode()) - return buf.String() -} - -// PasswordCredentialsToken converts a resource owner username and password -// pair into a token. -// -// Per the RFC, this grant type should only be used "when there is a high -// degree of trust between the resource owner and the client (e.g., the client -// is part of the device operating system or a highly privileged application), -// and when other authorization grant types are not available." -// See https://tools.ietf.org/html/rfc6749#section-4.3 for more info. -// -// The HTTP client to use is derived from the context. -// If nil, http.DefaultClient is used. -func (c *Config) PasswordCredentialsToken(ctx context.Context, username, password string) (*Token, error) { - return retrieveToken(ctx, c, url.Values{ - "grant_type": {"password"}, - "username": {username}, - "password": {password}, - "scope": internal.CondVal(strings.Join(c.Scopes, " ")), - }) -} - -// Exchange converts an authorization code into a token. -// -// It is used after a resource provider redirects the user back -// to the Redirect URI (the URL obtained from AuthCodeURL). -// -// The HTTP client to use is derived from the context. -// If a client is not provided via the context, http.DefaultClient is used. -// -// The code will be in the *http.Request.FormValue("code"). Before -// calling Exchange, be sure to validate FormValue("state"). -func (c *Config) Exchange(ctx context.Context, code string) (*Token, error) { - return retrieveToken(ctx, c, url.Values{ - "grant_type": {"authorization_code"}, - "code": {code}, - "redirect_uri": internal.CondVal(c.RedirectURL), - "scope": internal.CondVal(strings.Join(c.Scopes, " ")), - }) -} - -// Client returns an HTTP client using the provided token. -// The token will auto-refresh as necessary. The underlying -// HTTP transport will be obtained using the provided context. -// The returned client and its Transport should not be modified. -func (c *Config) Client(ctx context.Context, t *Token) *http.Client { - return NewClient(ctx, c.TokenSource(ctx, t)) -} - -// TokenSource returns a TokenSource that returns t until t expires, -// automatically refreshing it as necessary using the provided context. -// -// Most users will use Config.Client instead. -func (c *Config) TokenSource(ctx context.Context, t *Token) TokenSource { - tkr := &tokenRefresher{ - ctx: ctx, - conf: c, - } - if t != nil { - tkr.refreshToken = t.RefreshToken - } - return &reuseTokenSource{ - t: t, - new: tkr, - } -} - -// tokenRefresher is a TokenSource that makes "grant_type"=="refresh_token" -// HTTP requests to renew a token using a RefreshToken. -type tokenRefresher struct { - ctx context.Context // used to get HTTP requests - conf *Config - refreshToken string -} - -// WARNING: Token is not safe for concurrent access, as it -// updates the tokenRefresher's refreshToken field. -// Within this package, it is used by reuseTokenSource which -// synchronizes calls to this method with its own mutex. -func (tf *tokenRefresher) Token() (*Token, error) { - if tf.refreshToken == "" { - return nil, errors.New("oauth2: token expired and refresh token is not set") - } - - tk, err := retrieveToken(tf.ctx, tf.conf, url.Values{ - "grant_type": {"refresh_token"}, - "refresh_token": {tf.refreshToken}, - }) - - if err != nil { - return nil, err - } - if tf.refreshToken != tk.RefreshToken { - tf.refreshToken = tk.RefreshToken - } - return tk, err -} - -// reuseTokenSource is a TokenSource that holds a single token in memory -// and validates its expiry before each call to retrieve it with -// Token. If it's expired, it will be auto-refreshed using the -// new TokenSource. -type reuseTokenSource struct { - new TokenSource // called when t is expired. - - mu sync.Mutex // guards t - t *Token -} - -// Token returns the current token if it's still valid, else will -// refresh the current token (using r.Context for HTTP client -// information) and return the new one. -func (s *reuseTokenSource) Token() (*Token, error) { - s.mu.Lock() - defer s.mu.Unlock() - if s.t.Valid() { - return s.t, nil - } - t, err := s.new.Token() - if err != nil { - return nil, err - } - s.t = t - return t, nil -} - -// StaticTokenSource returns a TokenSource that always returns the same token. -// Because the provided token t is never refreshed, StaticTokenSource is only -// useful for tokens that never expire. -func StaticTokenSource(t *Token) TokenSource { - return staticTokenSource{t} -} - -// staticTokenSource is a TokenSource that always returns the same Token. -type staticTokenSource struct { - t *Token -} - -func (s staticTokenSource) Token() (*Token, error) { - return s.t, nil -} - -// HTTPClient is the context key to use with golang.org/x/net/context's -// WithValue function to associate an *http.Client value with a context. -var HTTPClient internal.ContextKey - -// NewClient creates an *http.Client from a Context and TokenSource. -// The returned client is not valid beyond the lifetime of the context. -// -// As a special case, if src is nil, a non-OAuth2 client is returned -// using the provided context. This exists to support related OAuth2 -// packages. -func NewClient(ctx context.Context, src TokenSource) *http.Client { - if src == nil { - c, err := internal.ContextClient(ctx) - if err != nil { - return &http.Client{Transport: internal.ErrorTransport{err}} - } - return c - } - return &http.Client{ - Transport: &Transport{ - Base: internal.ContextTransport(ctx), - Source: ReuseTokenSource(nil, src), - }, - } -} - -// ReuseTokenSource returns a TokenSource which repeatedly returns the -// same token as long as it's valid, starting with t. -// When its cached token is invalid, a new token is obtained from src. -// -// ReuseTokenSource is typically used to reuse tokens from a cache -// (such as a file on disk) between runs of a program, rather than -// obtaining new tokens unnecessarily. -// -// The initial token t may be nil, in which case the TokenSource is -// wrapped in a caching version if it isn't one already. This also -// means it's always safe to wrap ReuseTokenSource around any other -// TokenSource without adverse effects. -func ReuseTokenSource(t *Token, src TokenSource) TokenSource { - // Don't wrap a reuseTokenSource in itself. That would work, - // but cause an unnecessary number of mutex operations. - // Just build the equivalent one. - if rt, ok := src.(*reuseTokenSource); ok { - if t == nil { - // Just use it directly. - return rt - } - src = rt.new - } - return &reuseTokenSource{ - t: t, - new: src, - } -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/token.go b/Godeps/_workspace/src/golang.org/x/oauth2/token.go deleted file mode 100644 index 7a3167f15..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/token.go +++ /dev/null @@ -1,158 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package oauth2 - -import ( - "net/http" - "net/url" - "strconv" - "strings" - "time" - - "golang.org/x/net/context" - "golang.org/x/oauth2/internal" -) - -// expiryDelta determines how earlier a token should be considered -// expired than its actual expiration time. It is used to avoid late -// expirations due to client-server time mismatches. -const expiryDelta = 10 * time.Second - -// Token represents the crendentials used to authorize -// the requests to access protected resources on the OAuth 2.0 -// provider's backend. -// -// Most users of this package should not access fields of Token -// directly. They're exported mostly for use by related packages -// implementing derivative OAuth2 flows. -type Token struct { - // AccessToken is the token that authorizes and authenticates - // the requests. - AccessToken string `json:"access_token"` - - // TokenType is the type of token. - // The Type method returns either this or "Bearer", the default. - TokenType string `json:"token_type,omitempty"` - - // RefreshToken is a token that's used by the application - // (as opposed to the user) to refresh the access token - // if it expires. - RefreshToken string `json:"refresh_token,omitempty"` - - // Expiry is the optional expiration time of the access token. - // - // If zero, TokenSource implementations will reuse the same - // token forever and RefreshToken or equivalent - // mechanisms for that TokenSource will not be used. - Expiry time.Time `json:"expiry,omitempty"` - - // raw optionally contains extra metadata from the server - // when updating a token. - raw interface{} -} - -// Type returns t.TokenType if non-empty, else "Bearer". -func (t *Token) Type() string { - if strings.EqualFold(t.TokenType, "bearer") { - return "Bearer" - } - if strings.EqualFold(t.TokenType, "mac") { - return "MAC" - } - if strings.EqualFold(t.TokenType, "basic") { - return "Basic" - } - if t.TokenType != "" { - return t.TokenType - } - return "Bearer" -} - -// SetAuthHeader sets the Authorization header to r using the access -// token in t. -// -// This method is unnecessary when using Transport or an HTTP Client -// returned by this package. -func (t *Token) SetAuthHeader(r *http.Request) { - r.Header.Set("Authorization", t.Type()+" "+t.AccessToken) -} - -// WithExtra returns a new Token that's a clone of t, but using the -// provided raw extra map. This is only intended for use by packages -// implementing derivative OAuth2 flows. -func (t *Token) WithExtra(extra interface{}) *Token { - t2 := new(Token) - *t2 = *t - t2.raw = extra - return t2 -} - -// Extra returns an extra field. -// Extra fields are key-value pairs returned by the server as a -// part of the token retrieval response. -func (t *Token) Extra(key string) interface{} { - if raw, ok := t.raw.(map[string]interface{}); ok { - return raw[key] - } - - vals, ok := t.raw.(url.Values) - if !ok { - return nil - } - - v := vals.Get(key) - switch s := strings.TrimSpace(v); strings.Count(s, ".") { - case 0: // Contains no "."; try to parse as int - if i, err := strconv.ParseInt(s, 10, 64); err == nil { - return i - } - case 1: // Contains a single "."; try to parse as float - if f, err := strconv.ParseFloat(s, 64); err == nil { - return f - } - } - - return v -} - -// expired reports whether the token is expired. -// t must be non-nil. -func (t *Token) expired() bool { - if t.Expiry.IsZero() { - return false - } - return t.Expiry.Add(-expiryDelta).Before(time.Now()) -} - -// Valid reports whether t is non-nil, has an AccessToken, and is not expired. -func (t *Token) Valid() bool { - return t != nil && t.AccessToken != "" && !t.expired() -} - -// tokenFromInternal maps an *internal.Token struct into -// a *Token struct. -func tokenFromInternal(t *internal.Token) *Token { - if t == nil { - return nil - } - return &Token{ - AccessToken: t.AccessToken, - TokenType: t.TokenType, - RefreshToken: t.RefreshToken, - Expiry: t.Expiry, - raw: t.Raw, - } -} - -// retrieveToken takes a *Config and uses that to retrieve an *internal.Token. -// This token is then mapped from *internal.Token into an *oauth2.Token which is returned along -// with an error.. -func retrieveToken(ctx context.Context, c *Config, v url.Values) (*Token, error) { - tk, err := internal.RetrieveToken(ctx, c.ClientID, c.ClientSecret, c.Endpoint.TokenURL, v) - if err != nil { - return nil, err - } - return tokenFromInternal(tk), nil -} diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/transport.go b/Godeps/_workspace/src/golang.org/x/oauth2/transport.go deleted file mode 100644 index 92ac7e253..000000000 --- a/Godeps/_workspace/src/golang.org/x/oauth2/transport.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package oauth2 - -import ( - "errors" - "io" - "net/http" - "sync" -) - -// Transport is an http.RoundTripper that makes OAuth 2.0 HTTP requests, -// wrapping a base RoundTripper and adding an Authorization header -// with a token from the supplied Sources. -// -// Transport is a low-level mechanism. Most code will use the -// higher-level Config.Client method instead. -type Transport struct { - // Source supplies the token to add to outgoing requests' - // Authorization headers. - Source TokenSource - - // Base is the base RoundTripper used to make HTTP requests. - // If nil, http.DefaultTransport is used. - Base http.RoundTripper - - mu sync.Mutex // guards modReq - modReq map[*http.Request]*http.Request // original -> modified -} - -// RoundTrip authorizes and authenticates the request with an -// access token. If no token exists or token is expired, -// tries to refresh/fetch a new token. -func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { - if t.Source == nil { - return nil, errors.New("oauth2: Transport's Source is nil") - } - token, err := t.Source.Token() - if err != nil { - return nil, err - } - - req2 := cloneRequest(req) // per RoundTripper contract - token.SetAuthHeader(req2) - t.setModReq(req, req2) - res, err := t.base().RoundTrip(req2) - if err != nil { - t.setModReq(req, nil) - return nil, err - } - res.Body = &onEOFReader{ - rc: res.Body, - fn: func() { t.setModReq(req, nil) }, - } - return res, nil -} - -// CancelRequest cancels an in-flight request by closing its connection. -func (t *Transport) CancelRequest(req *http.Request) { - type canceler interface { - CancelRequest(*http.Request) - } - if cr, ok := t.base().(canceler); ok { - t.mu.Lock() - modReq := t.modReq[req] - delete(t.modReq, req) - t.mu.Unlock() - cr.CancelRequest(modReq) - } -} - -func (t *Transport) base() http.RoundTripper { - if t.Base != nil { - return t.Base - } - return http.DefaultTransport -} - -func (t *Transport) setModReq(orig, mod *http.Request) { - t.mu.Lock() - defer t.mu.Unlock() - if t.modReq == nil { - t.modReq = make(map[*http.Request]*http.Request) - } - if mod == nil { - delete(t.modReq, orig) - } else { - t.modReq[orig] = mod - } -} - -// 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, len(r.Header)) - for k, s := range r.Header { - r2.Header[k] = append([]string(nil), s...) - } - return r2 -} - -type onEOFReader struct { - rc io.ReadCloser - fn func() -} - -func (r *onEOFReader) Read(p []byte) (n int, err error) { - n, err = r.rc.Read(p) - if err == io.EOF { - r.runFunc() - } - return -} - -func (r *onEOFReader) Close() error { - err := r.rc.Close() - r.runFunc() - return err -} - -func (r *onEOFReader) runFunc() { - if fn := r.fn; fn != nil { - fn() - r.fn = nil - } -} diff --git a/Godeps/_workspace/src/google.golang.org/api/LICENSE b/Godeps/_workspace/src/google.golang.org/api/LICENSE deleted file mode 100644 index 263aa7a0c..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2011 Google Inc. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Godeps/_workspace/src/google.golang.org/api/admin/directory/v1/admin-api.json b/Godeps/_workspace/src/google.golang.org/api/admin/directory/v1/admin-api.json deleted file mode 100644 index 9cb240fd1..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/admin/directory/v1/admin-api.json +++ /dev/null @@ -1,5585 +0,0 @@ -{ - "kind": "discovery#restDescription", - "etag": "\"ye6orv2F-1npMW3u9suM3a7C5Bo/vE-je_lw5xuMc7X-IbS1gcTrxEY\"", - "discoveryVersion": "v1", - "id": "admin:directory_v1", - "name": "admin", - "canonicalName": "directory", - "version": "directory_v1", - "revision": "20151208", - "title": "Admin Directory API", - "description": "The Admin SDK Directory API lets you view and manage enterprise resources such as users and groups, administrative notifications, security features, and more.", - "ownerDomain": "google.com", - "ownerName": "Google", - "packagePath": "admin", - "icons": { - "x16": "http://www.google.com/images/icons/product/search-16.gif", - "x32": "http://www.google.com/images/icons/product/search-32.gif" - }, - "documentationLink": "https://developers.google.com/admin-sdk/directory/", - "protocol": "rest", - "baseUrl": "https://www.googleapis.com/admin/directory/v1/", - "basePath": "/admin/directory/v1/", - "rootUrl": "https://www.googleapis.com/", - "servicePath": "admin/directory/v1/", - "batchPath": "batch", - "parameters": { - "alt": { - "type": "string", - "description": "Data format for the response.", - "default": "json", - "enum": [ - "json" - ], - "enumDescriptions": [ - "Responses with Content-Type of application/json" - ], - "location": "query" - }, - "fields": { - "type": "string", - "description": "Selector specifying which fields to include in a partial response.", - "location": "query" - }, - "key": { - "type": "string", - "description": "API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.", - "location": "query" - }, - "oauth_token": { - "type": "string", - "description": "OAuth 2.0 token for the current user.", - "location": "query" - }, - "prettyPrint": { - "type": "boolean", - "description": "Returns response with indentations and line breaks.", - "default": "true", - "location": "query" - }, - "quotaUser": { - "type": "string", - "description": "Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.", - "location": "query" - }, - "userIp": { - "type": "string", - "description": "IP address of the site where the request originates. Use this if you want to enforce per-user limits.", - "location": "query" - } - }, - "auth": { - "oauth2": { - "scopes": { - "https://www.googleapis.com/auth/admin.directory.customer": { - "description": "View and manage customer related information" - }, - "https://www.googleapis.com/auth/admin.directory.customer.readonly": { - "description": "View customer related information" - }, - "https://www.googleapis.com/auth/admin.directory.device.chromeos": { - "description": "View and manage your Chrome OS devices' metadata" - }, - "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly": { - "description": "View your Chrome OS devices' metadata" - }, - "https://www.googleapis.com/auth/admin.directory.device.mobile": { - "description": "View and manage your mobile devices' metadata" - }, - "https://www.googleapis.com/auth/admin.directory.device.mobile.action": { - "description": "Manage your mobile devices by performing administrative tasks" - }, - "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly": { - "description": "View your mobile devices' metadata" - }, - "https://www.googleapis.com/auth/admin.directory.domain": { - "description": "View and manage the provisioning of domains for your customers" - }, - "https://www.googleapis.com/auth/admin.directory.domain.readonly": { - "description": "View domains related to your customers" - }, - "https://www.googleapis.com/auth/admin.directory.group": { - "description": "View and manage the provisioning of groups on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.group.member": { - "description": "View and manage group subscriptions on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.group.member.readonly": { - "description": "View group subscriptions on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.group.readonly": { - "description": "View groups on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.notifications": { - "description": "View and manage notifications received on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.orgunit": { - "description": "View and manage organization units on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.orgunit.readonly": { - "description": "View organization units on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.resource.calendar": { - "description": "View and manage the provisioning of calendar resources on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly": { - "description": "View calendar resources on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.rolemanagement": { - "description": "Manage delegated admin roles for your domain" - }, - "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly": { - "description": "View delegated admin roles for your domain" - }, - "https://www.googleapis.com/auth/admin.directory.user": { - "description": "View and manage the provisioning of users on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.user.alias": { - "description": "View and manage user aliases on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.user.alias.readonly": { - "description": "View user aliases on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.user.readonly": { - "description": "View users on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.user.security": { - "description": "Manage data access permissions for users on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.userschema": { - "description": "View and manage the provisioning of user schemas on your domain" - }, - "https://www.googleapis.com/auth/admin.directory.userschema.readonly": { - "description": "View user schemas on your domain" - } - } - } - }, - "schemas": { - "Alias": { - "id": "Alias", - "type": "object", - "description": "JSON template for Alias object in Directory API.", - "properties": { - "alias": { - "type": "string", - "description": "A alias email" - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "id": { - "type": "string", - "description": "Unique id of the group (Read-only) Unique id of the user (Read-only)" - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#alias" - }, - "primaryEmail": { - "type": "string", - "description": "Group's primary email (Read-only) User's primary email (Read-only)" - } - } - }, - "Aliases": { - "id": "Aliases", - "type": "object", - "description": "JSON response template to list aliases in Directory API.", - "properties": { - "aliases": { - "type": "array", - "description": "List of alias objects.", - "items": { - "$ref": "Alias" - } - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#aliases" - } - } - }, - "Asp": { - "id": "Asp", - "type": "object", - "description": "The template that returns individual ASP (Access Code) data.", - "properties": { - "codeId": { - "type": "integer", - "description": "The unique ID of the ASP.", - "format": "int32" - }, - "creationTime": { - "type": "string", - "description": "The time when the ASP was created. Expressed in Unix time format.", - "format": "int64" - }, - "etag": { - "type": "string", - "description": "ETag of the ASP." - }, - "kind": { - "type": "string", - "description": "The type of the API resource. This is always admin#directory#asp.", - "default": "admin#directory#asp" - }, - "lastTimeUsed": { - "type": "string", - "description": "The time when the ASP was last used. Expressed in Unix time format.", - "format": "int64" - }, - "name": { - "type": "string", - "description": "The name of the application that the user, represented by their userId, entered when the ASP was created." - }, - "userKey": { - "type": "string", - "description": "The unique ID of the user who issued the ASP." - } - } - }, - "Asps": { - "id": "Asps", - "type": "object", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "items": { - "type": "array", - "description": "A list of ASP resources.", - "items": { - "$ref": "Asp" - } - }, - "kind": { - "type": "string", - "description": "The type of the API resource. This is always admin#directory#aspList.", - "default": "admin#directory#aspList" - } - } - }, - "CalendarResource": { - "id": "CalendarResource", - "type": "object", - "description": "JSON template for Calendar Resource object in Directory API.", - "properties": { - "etags": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "The type of the resource. For calendar resources, the value is admin#directory#resources#calendars#CalendarResource.", - "default": "admin#directory#resources#calendars#CalendarResource" - }, - "resourceDescription": { - "type": "string", - "description": "The brief description of the calendar resource." - }, - "resourceEmail": { - "type": "string", - "description": "The read-only email ID for the calendar resource. Generated as part of creating a new calendar resource." - }, - "resourceId": { - "type": "string", - "description": "The unique ID for the calendar resource.", - "annotations": { - "required": [ - "directory.resources.calendars.insert" - ] - } - }, - "resourceName": { - "type": "string", - "description": "The name of the calendar resource. For example, Training Room 1A", - "annotations": { - "required": [ - "directory.resources.calendars.insert" - ] - } - }, - "resourceType": { - "type": "string", - "description": "The type of the calendar resource. Used for grouping resources in the calendar user interface." - } - } - }, - "CalendarResources": { - "id": "CalendarResources", - "type": "object", - "description": "JSON template for Calendar Resource List Response object in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "items": { - "type": "array", - "description": "The CalendarResources in this page of results.", - "items": { - "$ref": "CalendarResource" - } - }, - "kind": { - "type": "string", - "description": "Identifies this as a collection of CalendarResources. This is always admin#directory#resources#calendars#calendarResourcesList.", - "default": "admin#directory#resources#calendars#calendarResourcesList" - }, - "nextPageToken": { - "type": "string", - "description": "The continuation token, used to page through large result sets. Provide this value in a subsequent request to return the next page of results." - } - } - }, - "Channel": { - "id": "Channel", - "type": "object", - "description": "An notification channel used to watch for resource changes.", - "properties": { - "address": { - "type": "string", - "description": "The address where notifications are delivered for this channel." - }, - "expiration": { - "type": "string", - "description": "Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds. Optional.", - "format": "int64" - }, - "id": { - "type": "string", - "description": "A UUID or similar unique string that identifies this channel." - }, - "kind": { - "type": "string", - "description": "Identifies this as a notification channel used to watch for changes to a resource. Value: the fixed string \"api#channel\".", - "default": "api#channel" - }, - "params": { - "type": "object", - "description": "Additional parameters controlling delivery channel behavior. Optional.", - "additionalProperties": { - "type": "string", - "description": "Declares a new parameter by name." - } - }, - "payload": { - "type": "boolean", - "description": "A Boolean value to indicate whether payload is wanted. Optional." - }, - "resourceId": { - "type": "string", - "description": "An opaque ID that identifies the resource being watched on this channel. Stable across different API versions." - }, - "resourceUri": { - "type": "string", - "description": "A version-specific identifier for the watched resource." - }, - "token": { - "type": "string", - "description": "An arbitrary string delivered to the target address with each notification delivered over this channel. Optional." - }, - "type": { - "type": "string", - "description": "The type of delivery mechanism used for this channel." - } - } - }, - "ChromeOsDevice": { - "id": "ChromeOsDevice", - "type": "object", - "description": "JSON template for Chrome Os Device resource in Directory API.", - "properties": { - "activeTimeRanges": { - "type": "array", - "description": "List of active time ranges (Read-only)", - "items": { - "type": "object", - "properties": { - "activeTime": { - "type": "integer", - "description": "Duration in milliseconds", - "format": "int32" - }, - "date": { - "type": "string", - "description": "Date of usage", - "format": "date" - } - } - } - }, - "annotatedAssetId": { - "type": "string", - "description": "AssetId specified during enrollment or through later annotation" - }, - "annotatedLocation": { - "type": "string", - "description": "Address or location of the device as noted by the administrator" - }, - "annotatedUser": { - "type": "string", - "description": "User of the device" - }, - "bootMode": { - "type": "string", - "description": "Chromebook boot mode (Read-only)" - }, - "deviceId": { - "type": "string", - "description": "Unique identifier of Chrome OS Device (Read-only)" - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "ethernetMacAddress": { - "type": "string", - "description": "Chromebook Mac Address on ethernet network interface (Read-only)" - }, - "firmwareVersion": { - "type": "string", - "description": "Chromebook firmware version (Read-only)" - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#chromeosdevice" - }, - "lastEnrollmentTime": { - "type": "string", - "description": "Date and time the device was last enrolled (Read-only)", - "format": "date-time" - }, - "lastSync": { - "type": "string", - "description": "Date and time the device was last synchronized with the policy settings in the Google Apps administrator control panel (Read-only)", - "format": "date-time" - }, - "macAddress": { - "type": "string", - "description": "Chromebook Mac Address on wifi network interface (Read-only)" - }, - "meid": { - "type": "string", - "description": "Mobile Equipment identifier for the 3G mobile card in the Chromebook (Read-only)" - }, - "model": { - "type": "string", - "description": "Chromebook Model (Read-only)" - }, - "notes": { - "type": "string", - "description": "Notes added by the administrator" - }, - "orderNumber": { - "type": "string", - "description": "Chromebook order number (Read-only)" - }, - "orgUnitPath": { - "type": "string", - "description": "OrgUnit of the device" - }, - "osVersion": { - "type": "string", - "description": "Chromebook Os Version (Read-only)" - }, - "platformVersion": { - "type": "string", - "description": "Chromebook platform version (Read-only)" - }, - "recentUsers": { - "type": "array", - "description": "List of recent device users, in descending order by last login time (Read-only)", - "items": { - "type": "object", - "properties": { - "email": { - "type": "string", - "description": "Email address of the user. Present only if the user type is managed" - }, - "type": { - "type": "string", - "description": "The type of the user" - } - } - } - }, - "serialNumber": { - "type": "string", - "description": "Chromebook serial number (Read-only)" - }, - "status": { - "type": "string", - "description": "status of the device (Read-only)" - }, - "supportEndDate": { - "type": "string", - "description": "Final date the device will be supported (Read-only)", - "format": "date-time" - }, - "willAutoRenew": { - "type": "boolean", - "description": "Will Chromebook auto renew after support end date (Read-only)" - } - } - }, - "ChromeOsDevices": { - "id": "ChromeOsDevices", - "type": "object", - "description": "JSON response template for List Chrome OS Devices operation in Directory API.", - "properties": { - "chromeosdevices": { - "type": "array", - "description": "List of Chrome OS Device objects.", - "items": { - "$ref": "ChromeOsDevice" - } - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#chromeosdevices" - }, - "nextPageToken": { - "type": "string", - "description": "Token used to access next page of this result." - } - } - }, - "Customer": { - "id": "Customer", - "type": "object", - "description": "JSON template for Customer Resource object in Directory API.", - "properties": { - "alternateEmail": { - "type": "string", - "description": "The customer's secondary contact email address. This email address cannot be on the same domain as the customerDomain" - }, - "customerCreationTime": { - "type": "string", - "description": "The customer's creation time (Readonly)", - "format": "date-time" - }, - "customerDomain": { - "type": "string", - "description": "The customer's primary domain name string. Do not include the www prefix when creating a new customer." - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "id": { - "type": "string", - "description": "The unique ID for the customer's Google account. (Readonly)" - }, - "kind": { - "type": "string", - "description": "Identifies the resource as a customer. Value: admin#directory#customer", - "default": "admin#directory#customer" - }, - "language": { - "type": "string", - "description": "The customer's ISO 639-2 language code. The default value is en-US" - }, - "phoneNumber": { - "type": "string", - "description": "The customer's contact phone number in E.164 format." - }, - "postalAddress": { - "$ref": "CustomerPostalAddress", - "description": "The customer's postal address information." - } - } - }, - "CustomerPostalAddress": { - "id": "CustomerPostalAddress", - "type": "object", - "description": "JSON template for postal address of a customer.", - "properties": { - "addressLine1": { - "type": "string", - "description": "A customer's physical address. The address can be composed of one to three lines." - }, - "addressLine2": { - "type": "string", - "description": "Address line 2 of the address." - }, - "addressLine3": { - "type": "string", - "description": "Address line 3 of the address." - }, - "contactName": { - "type": "string", - "description": "The customer contact's name." - }, - "countryCode": { - "type": "string", - "description": "This is a required property. For countryCode information see the ISO 3166 country code elements." - }, - "locality": { - "type": "string", - "description": "Name of the locality. An example of a locality value is the city of San Francisco." - }, - "organizationName": { - "type": "string", - "description": "The company or company division name." - }, - "postalCode": { - "type": "string", - "description": "The postal code. A postalCode example is a postal zip code such as 10009. This is in accordance with - http://portablecontacts.net/draft-spec.html#address_element." - }, - "region": { - "type": "string", - "description": "Name of the region. An example of a region value is NY for the state of New York." - } - } - }, - "DomainAlias": { - "id": "DomainAlias", - "type": "object", - "description": "JSON template for Domain Alias object in Directory API.", - "properties": { - "creationTime": { - "type": "string", - "description": "The creation time of the domain alias. (Read-only).", - "format": "int64" - }, - "domainAliasName": { - "type": "string", - "description": "The domain alias name." - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#domainAlias" - }, - "parentDomainName": { - "type": "string", - "description": "The parent domain name that the domain alias is associated with. This can either be a primary or secondary domain name within a customer.", - "annotations": { - "required": [ - "directory.domains.insert" - ] - } - }, - "verified": { - "type": "boolean", - "description": "Indicates the verification state of a domain alias. (Read-only)" - } - } - }, - "DomainAliases": { - "id": "DomainAliases", - "type": "object", - "description": "JSON response template to list domain aliases in Directory API.", - "properties": { - "domainAliases": { - "type": "array", - "description": "List of domain alias objects.", - "items": { - "$ref": "DomainAlias" - } - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#domainAliases" - } - } - }, - "Domains": { - "id": "Domains", - "type": "object", - "description": "JSON template for Domain object in Directory API.", - "properties": { - "creationTime": { - "type": "string", - "description": "Creation time of the domain. (Read-only).", - "format": "int64" - }, - "domainAliases": { - "type": "array", - "description": "List of domain alias objects. (Read-only)", - "items": { - "$ref": "DomainAlias" - } - }, - "domainName": { - "type": "string", - "description": "The domain name of the customer.", - "annotations": { - "required": [ - "directory.domains.insert" - ] - } - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "isPrimary": { - "type": "boolean", - "description": "Indicates if the domain is a primary domain (Read-only)." - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#domain" - }, - "verified": { - "type": "boolean", - "description": "Indicates the verification state of a domain. (Read-only)." - } - } - }, - "Domains2": { - "id": "Domains2", - "type": "object", - "description": "JSON response template to list Domains in Directory API.", - "properties": { - "domains": { - "type": "array", - "description": "List of domain objects.", - "items": { - "$ref": "Domains" - } - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#domains" - } - } - }, - "Group": { - "id": "Group", - "type": "object", - "description": "JSON template for Group resource in Directory API.", - "properties": { - "adminCreated": { - "type": "boolean", - "description": "Is the group created by admin (Read-only) *" - }, - "aliases": { - "type": "array", - "description": "List of aliases (Read-only)", - "items": { - "type": "string" - } - }, - "description": { - "type": "string", - "description": "Description of the group" - }, - "directMembersCount": { - "type": "string", - "description": "Group direct members count", - "format": "int64" - }, - "email": { - "type": "string", - "description": "Email of Group", - "annotations": { - "required": [ - "directory.groups.insert" - ] - } - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "id": { - "type": "string", - "description": "Unique identifier of Group (Read-only)" - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#group" - }, - "name": { - "type": "string", - "description": "Group name" - }, - "nonEditableAliases": { - "type": "array", - "description": "List of non editable aliases (Read-only)", - "items": { - "type": "string" - } - } - } - }, - "Groups": { - "id": "Groups", - "type": "object", - "description": "JSON response template for List Groups operation in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "groups": { - "type": "array", - "description": "List of group objects.", - "items": { - "$ref": "Group" - } - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#groups" - }, - "nextPageToken": { - "type": "string", - "description": "Token used to access next page of this result." - } - } - }, - "Member": { - "id": "Member", - "type": "object", - "description": "JSON template for Member resource in Directory API.", - "properties": { - "email": { - "type": "string", - "description": "Email of member (Read-only)" - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "id": { - "type": "string", - "description": "Unique identifier of customer member (Read-only) Unique identifier of group (Read-only) Unique identifier of member (Read-only)" - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#member" - }, - "role": { - "type": "string", - "description": "Role of member" - }, - "type": { - "type": "string", - "description": "Type of member (Immutable)" - } - } - }, - "Members": { - "id": "Members", - "type": "object", - "description": "JSON response template for List Members operation in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#members" - }, - "members": { - "type": "array", - "description": "List of member objects.", - "items": { - "$ref": "Member" - } - }, - "nextPageToken": { - "type": "string", - "description": "Token used to access next page of this result." - } - } - }, - "MobileDevice": { - "id": "MobileDevice", - "type": "object", - "description": "JSON template for Mobile Device resource in Directory API.", - "properties": { - "adbStatus": { - "type": "boolean", - "description": "Adb (USB debugging) enabled or disabled on device (Read-only)" - }, - "applications": { - "type": "array", - "description": "List of applications installed on Mobile Device", - "items": { - "type": "object", - "properties": { - "displayName": { - "type": "string", - "description": "Display name of application" - }, - "packageName": { - "type": "string", - "description": "Package name of application" - }, - "permission": { - "type": "array", - "description": "List of Permissions for application", - "items": { - "type": "string" - } - }, - "versionCode": { - "type": "integer", - "description": "Version code of application", - "format": "int32" - }, - "versionName": { - "type": "string", - "description": "Version name of application" - } - } - } - }, - "basebandVersion": { - "type": "string", - "description": "Mobile Device Baseband version (Read-only)" - }, - "buildNumber": { - "type": "string", - "description": "Mobile Device Build number (Read-only)" - }, - "defaultLanguage": { - "type": "string", - "description": "The default locale used on the Mobile Device (Read-only)" - }, - "developerOptionsStatus": { - "type": "boolean", - "description": "Developer options enabled or disabled on device (Read-only)" - }, - "deviceCompromisedStatus": { - "type": "string", - "description": "Mobile Device compromised status (Read-only)" - }, - "deviceId": { - "type": "string", - "description": "Mobile Device serial number (Read-only)" - }, - "email": { - "type": "array", - "description": "List of owner user's email addresses (Read-only)", - "items": { - "type": "string" - } - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "firstSync": { - "type": "string", - "description": "Date and time the device was first synchronized with the policy settings in the Google Apps administrator control panel (Read-only)", - "format": "date-time" - }, - "hardwareId": { - "type": "string", - "description": "Mobile Device Hardware Id (Read-only)" - }, - "imei": { - "type": "string", - "description": "Mobile Device IMEI number (Read-only)" - }, - "kernelVersion": { - "type": "string", - "description": "Mobile Device Kernel version (Read-only)" - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#mobiledevice" - }, - "lastSync": { - "type": "string", - "description": "Date and time the device was last synchronized with the policy settings in the Google Apps administrator control panel (Read-only)", - "format": "date-time" - }, - "managedAccountIsOnOwnerProfile": { - "type": "boolean", - "description": "Boolean indicating if this account is on owner/primary profile or not (Read-only)" - }, - "meid": { - "type": "string", - "description": "Mobile Device MEID number (Read-only)" - }, - "model": { - "type": "string", - "description": "Name of the model of the device" - }, - "name": { - "type": "array", - "description": "List of owner user's names (Read-only)", - "items": { - "type": "string" - } - }, - "networkOperator": { - "type": "string", - "description": "Mobile Device mobile or network operator (if available) (Read-only)" - }, - "os": { - "type": "string", - "description": "Name of the mobile operating system" - }, - "otherAccountsInfo": { - "type": "array", - "description": "List of accounts added on device (Read-only)", - "items": { - "type": "string" - } - }, - "resourceId": { - "type": "string", - "description": "Unique identifier of Mobile Device (Read-only)" - }, - "serialNumber": { - "type": "string", - "description": "Mobile Device SSN or Serial Number (Read-only)" - }, - "status": { - "type": "string", - "description": "Status of the device (Read-only)" - }, - "supportsWorkProfile": { - "type": "boolean", - "description": "Work profile supported on device (Read-only)" - }, - "type": { - "type": "string", - "description": "The type of device (Read-only)" - }, - "unknownSourcesStatus": { - "type": "boolean", - "description": "Unknown sources enabled or disabled on device (Read-only)" - }, - "userAgent": { - "type": "string", - "description": "Mobile Device user agent" - }, - "wifiMacAddress": { - "type": "string", - "description": "Mobile Device WiFi MAC address (Read-only)" - } - } - }, - "MobileDeviceAction": { - "id": "MobileDeviceAction", - "type": "object", - "description": "JSON request template for firing commands on Mobile Device in Directory Devices API.", - "properties": { - "action": { - "type": "string", - "description": "Action to be taken on the Mobile Device", - "annotations": { - "required": [ - "directory.mobiledevices.action" - ] - } - } - } - }, - "MobileDevices": { - "id": "MobileDevices", - "type": "object", - "description": "JSON response template for List Mobile Devices operation in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#mobiledevices" - }, - "mobiledevices": { - "type": "array", - "description": "List of Mobile Device objects.", - "items": { - "$ref": "MobileDevice" - } - }, - "nextPageToken": { - "type": "string", - "description": "Token used to access next page of this result." - } - } - }, - "Notification": { - "id": "Notification", - "type": "object", - "description": "Template for a notification resource.", - "properties": { - "body": { - "type": "string", - "description": "Body of the notification (Read-only)" - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "fromAddress": { - "type": "string", - "description": "Address from which the notification is received (Read-only)" - }, - "isUnread": { - "type": "boolean", - "description": "Boolean indicating whether the notification is unread or not.", - "annotations": { - "required": [ - "directory.notifications.patch", - "directory.notifications.update" - ] - } - }, - "kind": { - "type": "string", - "description": "The type of the resource.", - "default": "admin#directory#notification" - }, - "notificationId": { - "type": "string" - }, - "sendTime": { - "type": "string", - "description": "Time at which notification was sent (Read-only)", - "format": "date-time" - }, - "subject": { - "type": "string", - "description": "Subject of the notification (Read-only)" - } - } - }, - "Notifications": { - "id": "Notifications", - "type": "object", - "description": "Template for notifications list response.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "items": { - "type": "array", - "description": "List of notifications in this page.", - "items": { - "$ref": "Notification" - } - }, - "kind": { - "type": "string", - "description": "The type of the resource.", - "default": "admin#directory#notifications" - }, - "nextPageToken": { - "type": "string", - "description": "Token for fetching the next page of notifications." - }, - "unreadNotificationsCount": { - "type": "integer", - "description": "Number of unread notification for the domain.", - "format": "int32" - } - } - }, - "OrgUnit": { - "id": "OrgUnit", - "type": "object", - "description": "JSON template for Org Unit resource in Directory API.", - "properties": { - "blockInheritance": { - "type": "boolean", - "description": "Should block inheritance" - }, - "description": { - "type": "string", - "description": "Description of OrgUnit" - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#orgUnit" - }, - "name": { - "type": "string", - "description": "Name of OrgUnit", - "annotations": { - "required": [ - "directory.orgunits.insert" - ] - } - }, - "orgUnitId": { - "type": "string", - "description": "Id of OrgUnit" - }, - "orgUnitPath": { - "type": "string", - "description": "Path of OrgUnit" - }, - "parentOrgUnitId": { - "type": "string", - "description": "Id of parent OrgUnit" - }, - "parentOrgUnitPath": { - "type": "string", - "description": "Path of parent OrgUnit" - } - } - }, - "OrgUnits": { - "id": "OrgUnits", - "type": "object", - "description": "JSON response template for List Organization Units operation in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#orgUnits" - }, - "organizationUnits": { - "type": "array", - "description": "List of user objects.", - "items": { - "$ref": "OrgUnit" - } - } - } - }, - "Privilege": { - "id": "Privilege", - "type": "object", - "description": "JSON template for privilege resource in Directory API.", - "properties": { - "childPrivileges": { - "type": "array", - "description": "A list of child privileges. Privileges for a service form a tree. Each privilege can have a list of child privileges; this list is empty for a leaf privilege.", - "items": { - "$ref": "Privilege" - } - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "isOuScopable": { - "type": "boolean", - "description": "If the privilege can be restricted to an organization unit." - }, - "kind": { - "type": "string", - "description": "The type of the API resource. This is always admin#directory#privilege.", - "default": "admin#directory#privilege" - }, - "privilegeName": { - "type": "string", - "description": "The name of the privilege." - }, - "serviceId": { - "type": "string", - "description": "The obfuscated ID of the service this privilege is for." - }, - "serviceName": { - "type": "string", - "description": "The name of the service this privilege is for." - } - } - }, - "Privileges": { - "id": "Privileges", - "type": "object", - "description": "JSON response template for List privileges operation in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "items": { - "type": "array", - "description": "A list of Privilege resources.", - "items": { - "$ref": "Privilege" - } - }, - "kind": { - "type": "string", - "description": "The type of the API resource. This is always admin#directory#privileges.", - "default": "admin#directory#privileges" - } - } - }, - "Role": { - "id": "Role", - "type": "object", - "description": "JSON template for role resource in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "isSuperAdminRole": { - "type": "boolean", - "description": "Returns true if the role is a super admin role." - }, - "isSystemRole": { - "type": "boolean", - "description": "Returns true if this is a pre-defined system role." - }, - "kind": { - "type": "string", - "description": "The type of the API resource. This is always admin#directory#role.", - "default": "admin#directory#role" - }, - "roleDescription": { - "type": "string", - "description": "A short description of the role." - }, - "roleId": { - "type": "string", - "description": "ID of the role.", - "format": "int64" - }, - "roleName": { - "type": "string", - "description": "Name of the role.", - "annotations": { - "required": [ - "directory.roles.insert" - ] - } - }, - "rolePrivileges": { - "type": "array", - "description": "The set of privileges that are granted to this role.", - "items": { - "type": "object", - "properties": { - "privilegeName": { - "type": "string", - "description": "The name of the privilege." - }, - "serviceId": { - "type": "string", - "description": "The obfuscated ID of the service this privilege is for." - } - } - }, - "annotations": { - "required": [ - "directory.roles.insert" - ] - } - } - } - }, - "RoleAssignment": { - "id": "RoleAssignment", - "type": "object", - "description": "JSON template for roleAssignment resource in Directory API.", - "properties": { - "assignedTo": { - "type": "string", - "description": "The unique ID of the user this role is assigned to." - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "The type of the API resource. This is always admin#directory#roleAssignment.", - "default": "admin#directory#roleAssignment" - }, - "orgUnitId": { - "type": "string", - "description": "If the role is restricted to an organization unit, this contains the ID for the organization unit the exercise of this role is restricted to." - }, - "roleAssignmentId": { - "type": "string", - "description": "ID of this roleAssignment.", - "format": "int64" - }, - "roleId": { - "type": "string", - "description": "The ID of the role that is assigned.", - "format": "int64" - }, - "scopeType": { - "type": "string", - "description": "The scope in which this role is assigned. Possible values are: \n- CUSTOMER\n- ORG_UNIT" - } - } - }, - "RoleAssignments": { - "id": "RoleAssignments", - "type": "object", - "description": "JSON response template for List roleAssignments operation in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "items": { - "type": "array", - "description": "A list of RoleAssignment resources.", - "items": { - "$ref": "RoleAssignment" - } - }, - "kind": { - "type": "string", - "description": "The type of the API resource. This is always admin#directory#roleAssignments.", - "default": "admin#directory#roleAssignments" - }, - "nextPageToken": { - "type": "string" - } - } - }, - "Roles": { - "id": "Roles", - "type": "object", - "description": "JSON response template for List roles operation in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "items": { - "type": "array", - "description": "A list of Role resources.", - "items": { - "$ref": "Role" - } - }, - "kind": { - "type": "string", - "description": "The type of the API resource. This is always admin#directory#roles.", - "default": "admin#directory#roles" - }, - "nextPageToken": { - "type": "string" - } - } - }, - "Schema": { - "id": "Schema", - "type": "object", - "description": "JSON template for Schema resource in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "fields": { - "type": "array", - "description": "Fields of Schema", - "items": { - "$ref": "SchemaFieldSpec" - }, - "annotations": { - "required": [ - "directory.schemas.insert", - "directory.schemas.update" - ] - } - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#schema" - }, - "schemaId": { - "type": "string", - "description": "Unique identifier of Schema (Read-only)" - }, - "schemaName": { - "type": "string", - "description": "Schema name", - "annotations": { - "required": [ - "directory.schemas.insert" - ] - } - } - } - }, - "SchemaFieldSpec": { - "id": "SchemaFieldSpec", - "type": "object", - "description": "JSON template for FieldSpec resource for Schemas in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "fieldId": { - "type": "string", - "description": "Unique identifier of Field (Read-only)" - }, - "fieldName": { - "type": "string", - "description": "Name of the field.", - "annotations": { - "required": [ - "directory.schemas.insert", - "directory.schemas.update" - ] - } - }, - "fieldType": { - "type": "string", - "description": "Type of the field.", - "annotations": { - "required": [ - "directory.schemas.insert", - "directory.schemas.update" - ] - } - }, - "indexed": { - "type": "boolean", - "description": "Boolean specifying whether the field is indexed or not.", - "default": "true" - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#schema#fieldspec" - }, - "multiValued": { - "type": "boolean", - "description": "Boolean specifying whether this is a multi-valued field or not." - }, - "numericIndexingSpec": { - "type": "object", - "description": "Indexing spec for a numeric field. By default, only exact match queries will be supported for numeric fields. Setting the numericIndexingSpec allows range queries to be supported.", - "properties": { - "maxValue": { - "type": "number", - "description": "Maximum value of this field. This is meant to be indicative rather than enforced. Values outside this range will still be indexed, but search may not be as performant.", - "format": "double" - }, - "minValue": { - "type": "number", - "description": "Minimum value of this field. This is meant to be indicative rather than enforced. Values outside this range will still be indexed, but search may not be as performant.", - "format": "double" - } - } - }, - "readAccessType": { - "type": "string", - "description": "Read ACLs on the field specifying who can view values of this field. Valid values are \"ALL_DOMAIN_USERS\" and \"ADMINS_AND_SELF\".", - "default": "ALL_DOMAIN_USERS" - } - } - }, - "Schemas": { - "id": "Schemas", - "type": "object", - "description": "JSON response template for List Schema operation in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#schemas" - }, - "schemas": { - "type": "array", - "description": "List of UserSchema objects.", - "items": { - "$ref": "Schema" - } - } - } - }, - "Token": { - "id": "Token", - "type": "object", - "description": "JSON template for token resource in Directory API.", - "properties": { - "anonymous": { - "type": "boolean", - "description": "Whether the application is registered with Google. The value is true if the application has an anonymous Client ID." - }, - "clientId": { - "type": "string", - "description": "The Client ID of the application the token is issued to." - }, - "displayText": { - "type": "string", - "description": "The displayable name of the application the token is issued to." - }, - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "The type of the API resource. This is always admin#directory#token.", - "default": "admin#directory#token" - }, - "nativeApp": { - "type": "boolean", - "description": "Whether the token is issued to an installed application. The value is true if the application is installed to a desktop or mobile device." - }, - "scopes": { - "type": "array", - "description": "A list of authorization scopes the application is granted.", - "items": { - "type": "string" - } - }, - "userKey": { - "type": "string", - "description": "The unique ID of the user that issued the token." - } - } - }, - "Tokens": { - "id": "Tokens", - "type": "object", - "description": "JSON response template for List tokens operation in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "items": { - "type": "array", - "description": "A list of Token resources.", - "items": { - "$ref": "Token" - } - }, - "kind": { - "type": "string", - "description": "The type of the API resource. This is always admin#directory#tokenList.", - "default": "admin#directory#tokenList" - } - } - }, - "User": { - "id": "User", - "type": "object", - "description": "JSON template for User object in Directory API.", - "properties": { - "addresses": { - "type": "any" - }, - "agreedToTerms": { - "type": "boolean", - "description": "Indicates if user has agreed to terms (Read-only)", - "readOnly": true - }, - "aliases": { - "type": "array", - "description": "List of aliases (Read-only)", - "readOnly": true, - "items": { - "type": "string" - } - }, - "changePasswordAtNextLogin": { - "type": "boolean", - "description": "Boolean indicating if the user should change password in next login" - }, - "creationTime": { - "type": "string", - "description": "User's Google account creation time. (Read-only)", - "format": "date-time", - "readOnly": true - }, - "customSchemas": { - "type": "object", - "description": "Custom fields of the user.", - "additionalProperties": { - "$ref": "UserCustomProperties" - } - }, - "customerId": { - "type": "string", - "description": "CustomerId of User (Read-only)", - "readOnly": true - }, - "deletionTime": { - "type": "string", - "format": "date-time", - "readOnly": true - }, - "emails": { - "type": "any" - }, - "etag": { - "type": "string", - "description": "ETag of the resource.", - "readOnly": true - }, - "externalIds": { - "type": "any" - }, - "hashFunction": { - "type": "string", - "description": "Hash function name for password. Supported are MD5, SHA-1 and crypt" - }, - "id": { - "type": "string", - "description": "Unique identifier of User (Read-only)" - }, - "ims": { - "type": "any" - }, - "includeInGlobalAddressList": { - "type": "boolean", - "description": "Boolean indicating if user is included in Global Address List" - }, - "ipWhitelisted": { - "type": "boolean", - "description": "Boolean indicating if ip is whitelisted" - }, - "isAdmin": { - "type": "boolean", - "description": "Boolean indicating if the user is admin (Read-only)", - "readOnly": true - }, - "isDelegatedAdmin": { - "type": "boolean", - "description": "Boolean indicating if the user is delegated admin (Read-only)", - "readOnly": true - }, - "isMailboxSetup": { - "type": "boolean", - "description": "Is mailbox setup (Read-only)", - "readOnly": true - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#user", - "readOnly": true - }, - "lastLoginTime": { - "type": "string", - "description": "User's last login time. (Read-only)", - "format": "date-time", - "readOnly": true - }, - "name": { - "$ref": "UserName", - "description": "User's name", - "annotations": { - "required": [ - "directory.users.insert" - ] - } - }, - "nonEditableAliases": { - "type": "array", - "description": "List of non editable aliases (Read-only)", - "readOnly": true, - "items": { - "type": "string" - } - }, - "notes": { - "type": "any" - }, - "orgUnitPath": { - "type": "string", - "description": "OrgUnit of User" - }, - "organizations": { - "type": "any" - }, - "password": { - "type": "string", - "description": "User's password", - "annotations": { - "required": [ - "directory.users.insert" - ] - } - }, - "phones": { - "type": "any" - }, - "primaryEmail": { - "type": "string", - "description": "username of User", - "annotations": { - "required": [ - "directory.users.insert" - ] - } - }, - "relations": { - "type": "any" - }, - "suspended": { - "type": "boolean", - "description": "Indicates if user is suspended" - }, - "suspensionReason": { - "type": "string", - "description": "Suspension reason if user is suspended (Read-only)", - "readOnly": true - }, - "thumbnailPhotoEtag": { - "type": "string", - "description": "ETag of the user's photo (Read-only)", - "readOnly": true - }, - "thumbnailPhotoUrl": { - "type": "string", - "description": "Photo Url of the user (Read-only)", - "readOnly": true - }, - "websites": { - "type": "any" - } - } - }, - "UserAbout": { - "id": "UserAbout", - "type": "object", - "description": "JSON template for About (notes) of a user in Directory API.", - "properties": { - "contentType": { - "type": "string", - "description": "About entry can have a type which indicates the content type. It can either be plain or html. By default, notes contents are assumed to contain plain text." - }, - "value": { - "type": "string", - "description": "Actual value of notes." - } - } - }, - "UserAddress": { - "id": "UserAddress", - "type": "object", - "description": "JSON template for address.", - "properties": { - "country": { - "type": "string", - "description": "Country." - }, - "countryCode": { - "type": "string", - "description": "Country code." - }, - "customType": { - "type": "string", - "description": "Custom type." - }, - "extendedAddress": { - "type": "string", - "description": "Extended Address." - }, - "formatted": { - "type": "string", - "description": "Formatted address." - }, - "locality": { - "type": "string", - "description": "Locality." - }, - "poBox": { - "type": "string", - "description": "Other parts of address." - }, - "postalCode": { - "type": "string", - "description": "Postal code." - }, - "primary": { - "type": "boolean", - "description": "If this is user's primary address. Only one entry could be marked as primary." - }, - "region": { - "type": "string", - "description": "Region." - }, - "sourceIsStructured": { - "type": "boolean", - "description": "User supplied address was structured. Structured addresses are NOT supported at this time. You might be able to write structured addresses, but any values will eventually be clobbered." - }, - "streetAddress": { - "type": "string", - "description": "Street." - }, - "type": { - "type": "string", - "description": "Each entry can have a type which indicates standard values of that entry. For example address could be of home, work etc. In addition to the standard type, an entry can have a custom type and can take any value. Such type should have the CUSTOM value as type and also have a customType value." - } - } - }, - "UserCustomProperties": { - "id": "UserCustomProperties", - "type": "object", - "description": "JSON template for a set of custom properties (i.e. all fields in a particular schema)", - "additionalProperties": { - "type": "any" - } - }, - "UserEmail": { - "id": "UserEmail", - "type": "object", - "description": "JSON template for an email.", - "properties": { - "address": { - "type": "string", - "description": "Email id of the user." - }, - "customType": { - "type": "string", - "description": "Custom Type." - }, - "primary": { - "type": "boolean", - "description": "If this is user's primary email. Only one entry could be marked as primary." - }, - "type": { - "type": "string", - "description": "Each entry can have a type which indicates standard types of that entry. For example email could be of home, work etc. In addition to the standard type, an entry can have a custom type and can take any value Such types should have the CUSTOM value as type and also have a customType value." - } - } - }, - "UserExternalId": { - "id": "UserExternalId", - "type": "object", - "description": "JSON template for an externalId entry.", - "properties": { - "customType": { - "type": "string", - "description": "Custom type." - }, - "type": { - "type": "string", - "description": "The type of the Id." - }, - "value": { - "type": "string", - "description": "The value of the id." - } - } - }, - "UserIm": { - "id": "UserIm", - "type": "object", - "description": "JSON template for instant messenger of an user.", - "properties": { - "customProtocol": { - "type": "string", - "description": "Custom protocol." - }, - "customType": { - "type": "string", - "description": "Custom type." - }, - "im": { - "type": "string", - "description": "Instant messenger id." - }, - "primary": { - "type": "boolean", - "description": "If this is user's primary im. Only one entry could be marked as primary." - }, - "protocol": { - "type": "string", - "description": "Protocol used in the instant messenger. It should be one of the values from ImProtocolTypes map. Similar to type, it can take a CUSTOM value and specify the custom name in customProtocol field." - }, - "type": { - "type": "string", - "description": "Each entry can have a type which indicates standard types of that entry. For example instant messengers could be of home, work etc. In addition to the standard type, an entry can have a custom type and can take any value. Such types should have the CUSTOM value as type and also have a customType value." - } - } - }, - "UserMakeAdmin": { - "id": "UserMakeAdmin", - "type": "object", - "description": "JSON request template for setting/revoking admin status of a user in Directory API.", - "properties": { - "status": { - "type": "boolean", - "description": "Boolean indicating new admin status of the user", - "annotations": { - "required": [ - "directory.users.makeAdmin" - ] - } - } - } - }, - "UserName": { - "id": "UserName", - "type": "object", - "description": "JSON template for name of a user in Directory API.", - "properties": { - "familyName": { - "type": "string", - "description": "Last Name", - "annotations": { - "required": [ - "directory.users.insert" - ] - } - }, - "fullName": { - "type": "string", - "description": "Full Name" - }, - "givenName": { - "type": "string", - "description": "First Name", - "annotations": { - "required": [ - "directory.users.insert" - ] - } - } - } - }, - "UserOrganization": { - "id": "UserOrganization", - "type": "object", - "description": "JSON template for an organization entry.", - "properties": { - "costCenter": { - "type": "string", - "description": "The cost center of the users department." - }, - "customType": { - "type": "string", - "description": "Custom type." - }, - "department": { - "type": "string", - "description": "Department within the organization." - }, - "description": { - "type": "string", - "description": "Description of the organization." - }, - "domain": { - "type": "string", - "description": "The domain to which the organization belongs to." - }, - "location": { - "type": "string", - "description": "Location of the organization. This need not be fully qualified address." - }, - "name": { - "type": "string", - "description": "Name of the organization" - }, - "primary": { - "type": "boolean", - "description": "If it user's primary organization." - }, - "symbol": { - "type": "string", - "description": "Symbol of the organization." - }, - "title": { - "type": "string", - "description": "Title (designation) of the user in the organization." - }, - "type": { - "type": "string", - "description": "Each entry can have a type which indicates standard types of that entry. For example organization could be of school, work etc. In addition to the standard type, an entry can have a custom type and can give it any name. Such types should have the CUSTOM value as type and also have a CustomType value." - } - } - }, - "UserPhone": { - "id": "UserPhone", - "type": "object", - "description": "JSON template for a phone entry.", - "properties": { - "customType": { - "type": "string", - "description": "Custom Type." - }, - "primary": { - "type": "boolean", - "description": "If this is user's primary phone or not." - }, - "type": { - "type": "string", - "description": "Each entry can have a type which indicates standard types of that entry. For example phone could be of home_fax, work, mobile etc. In addition to the standard type, an entry can have a custom type and can give it any name. Such types should have the CUSTOM value as type and also have a customType value." - }, - "value": { - "type": "string", - "description": "Phone number." - } - } - }, - "UserPhoto": { - "id": "UserPhoto", - "type": "object", - "description": "JSON template for Photo object in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "height": { - "type": "integer", - "description": "Height in pixels of the photo", - "format": "int32" - }, - "id": { - "type": "string", - "description": "Unique identifier of User (Read-only)" - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#user#photo" - }, - "mimeType": { - "type": "string", - "description": "Mime Type of the photo" - }, - "photoData": { - "type": "string", - "description": "Base64 encoded photo data", - "format": "byte", - "annotations": { - "required": [ - "directory.users.photos.update" - ] - } - }, - "primaryEmail": { - "type": "string", - "description": "Primary email of User (Read-only)" - }, - "width": { - "type": "integer", - "description": "Width in pixels of the photo", - "format": "int32" - } - } - }, - "UserRelation": { - "id": "UserRelation", - "type": "object", - "description": "JSON template for a relation entry.", - "properties": { - "customType": { - "type": "string", - "description": "Custom Type." - }, - "type": { - "type": "string", - "description": "The relation of the user. Some of the possible values are mother, father, sister, brother, manager, assistant, partner." - }, - "value": { - "type": "string", - "description": "The name of the relation." - } - } - }, - "UserUndelete": { - "id": "UserUndelete", - "type": "object", - "description": "JSON request template to undelete a user in Directory API.", - "properties": { - "orgUnitPath": { - "type": "string", - "description": "OrgUnit of User" - } - } - }, - "UserWebsite": { - "id": "UserWebsite", - "type": "object", - "description": "JSON template for a website entry.", - "properties": { - "customType": { - "type": "string", - "description": "Custom Type." - }, - "primary": { - "type": "boolean", - "description": "If this is user's primary website or not." - }, - "type": { - "type": "string", - "description": "Each entry can have a type which indicates standard types of that entry. For example website could be of home, work, blog etc. In addition to the standard type, an entry can have a custom type and can give it any name. Such types should have the CUSTOM value as type and also have a customType value." - }, - "value": { - "type": "string", - "description": "Website." - } - } - }, - "Users": { - "id": "Users", - "type": "object", - "description": "JSON response template for List Users operation in Apps Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "Kind of resource this is.", - "default": "admin#directory#users" - }, - "nextPageToken": { - "type": "string", - "description": "Token used to access next page of this result." - }, - "trigger_event": { - "type": "string", - "description": "Event that triggered this response (only used in case of Push Response)" - }, - "users": { - "type": "array", - "description": "List of user objects.", - "items": { - "$ref": "User" - } - } - } - }, - "VerificationCode": { - "id": "VerificationCode", - "type": "object", - "description": "JSON template for verification codes in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "kind": { - "type": "string", - "description": "The type of the resource. This is always admin#directory#verificationCode.", - "default": "admin#directory#verificationCode" - }, - "userId": { - "type": "string", - "description": "The obfuscated unique ID of the user." - }, - "verificationCode": { - "type": "string", - "description": "A current verification code for the user. Invalidated or used verification codes are not returned as part of the result." - } - } - }, - "VerificationCodes": { - "id": "VerificationCodes", - "type": "object", - "description": "JSON response template for List verification codes operation in Directory API.", - "properties": { - "etag": { - "type": "string", - "description": "ETag of the resource." - }, - "items": { - "type": "array", - "description": "A list of verification code resources.", - "items": { - "$ref": "VerificationCode" - } - }, - "kind": { - "type": "string", - "description": "The type of the resource. This is always admin#directory#verificationCodesList.", - "default": "admin#directory#verificationCodesList" - } - } - } - }, - "resources": { - "asps": { - "methods": { - "delete": { - "id": "directory.asps.delete", - "path": "users/{userKey}/asps/{codeId}", - "httpMethod": "DELETE", - "description": "Delete an ASP issued by a user.", - "parameters": { - "codeId": { - "type": "integer", - "description": "The unique ID of the ASP to be deleted.", - "required": true, - "format": "int32", - "location": "path" - }, - "userKey": { - "type": "string", - "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey", - "codeId" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user.security" - ] - }, - "get": { - "id": "directory.asps.get", - "path": "users/{userKey}/asps/{codeId}", - "httpMethod": "GET", - "description": "Get information about an ASP issued by a user.", - "parameters": { - "codeId": { - "type": "integer", - "description": "The unique ID of the ASP.", - "required": true, - "format": "int32", - "location": "path" - }, - "userKey": { - "type": "string", - "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey", - "codeId" - ], - "response": { - "$ref": "Asp" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user.security" - ] - }, - "list": { - "id": "directory.asps.list", - "path": "users/{userKey}/asps", - "httpMethod": "GET", - "description": "List the ASPs issued by a user.", - "parameters": { - "userKey": { - "type": "string", - "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "response": { - "$ref": "Asps" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user.security" - ] - } - } - }, - "channels": { - "methods": { - "stop": { - "id": "admin.channels.stop", - "path": "/admin/directory_v1/channels/stop", - "httpMethod": "POST", - "description": "Stop watching resources through this channel", - "request": { - "$ref": "Channel", - "parameterName": "resource" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user", - "https://www.googleapis.com/auth/admin.directory.user.alias", - "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", - "https://www.googleapis.com/auth/admin.directory.user.readonly" - ] - } - } - }, - "chromeosdevices": { - "methods": { - "get": { - "id": "directory.chromeosdevices.get", - "path": "customer/{customerId}/devices/chromeos/{deviceId}", - "httpMethod": "GET", - "description": "Retrieve Chrome OS Device", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "deviceId": { - "type": "string", - "description": "Immutable id of Chrome OS Device", - "required": true, - "location": "path" - }, - "projection": { - "type": "string", - "description": "Restrict information returned to a set of selected fields.", - "enum": [ - "BASIC", - "FULL" - ], - "enumDescriptions": [ - "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", - "Includes all metadata fields" - ], - "location": "query" - } - }, - "parameterOrder": [ - "customerId", - "deviceId" - ], - "response": { - "$ref": "ChromeOsDevice" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.device.chromeos", - "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly" - ] - }, - "list": { - "id": "directory.chromeosdevices.list", - "path": "customer/{customerId}/devices/chromeos", - "httpMethod": "GET", - "description": "Retrieve all Chrome OS Devices of a customer (paginated)", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "maxResults": { - "type": "integer", - "description": "Maximum number of results to return. Default is 100", - "format": "int32", - "minimum": "1", - "location": "query" - }, - "orderBy": { - "type": "string", - "description": "Column to use for sorting results", - "enum": [ - "annotatedLocation", - "annotatedUser", - "lastSync", - "notes", - "serialNumber", - "status", - "supportEndDate" - ], - "enumDescriptions": [ - "Chromebook location as annotated by the administrator.", - "Chromebook user as annotated by administrator.", - "Chromebook last sync.", - "Chromebook notes as annotated by the administrator.", - "Chromebook Serial Number.", - "Chromebook status.", - "Chromebook support end date." - ], - "location": "query" - }, - "pageToken": { - "type": "string", - "description": "Token to specify next page in the list", - "location": "query" - }, - "projection": { - "type": "string", - "description": "Restrict information returned to a set of selected fields.", - "enum": [ - "BASIC", - "FULL" - ], - "enumDescriptions": [ - "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", - "Includes all metadata fields" - ], - "location": "query" - }, - "query": { - "type": "string", - "description": "Search string in the format given at http://support.google.com/chromeos/a/bin/answer.py?hl=en&answer=1698333", - "location": "query" - }, - "sortOrder": { - "type": "string", - "description": "Whether to return results in ascending or descending order. Only of use when orderBy is also used", - "enum": [ - "ASCENDING", - "DESCENDING" - ], - "enumDescriptions": [ - "Ascending order.", - "Descending order." - ], - "location": "query" - } - }, - "parameterOrder": [ - "customerId" - ], - "response": { - "$ref": "ChromeOsDevices" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.device.chromeos", - "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly" - ] - }, - "patch": { - "id": "directory.chromeosdevices.patch", - "path": "customer/{customerId}/devices/chromeos/{deviceId}", - "httpMethod": "PATCH", - "description": "Update Chrome OS Device. This method supports patch semantics.", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "deviceId": { - "type": "string", - "description": "Immutable id of Chrome OS Device", - "required": true, - "location": "path" - }, - "projection": { - "type": "string", - "description": "Restrict information returned to a set of selected fields.", - "enum": [ - "BASIC", - "FULL" - ], - "enumDescriptions": [ - "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", - "Includes all metadata fields" - ], - "location": "query" - } - }, - "parameterOrder": [ - "customerId", - "deviceId" - ], - "request": { - "$ref": "ChromeOsDevice" - }, - "response": { - "$ref": "ChromeOsDevice" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.device.chromeos" - ] - }, - "update": { - "id": "directory.chromeosdevices.update", - "path": "customer/{customerId}/devices/chromeos/{deviceId}", - "httpMethod": "PUT", - "description": "Update Chrome OS Device", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "deviceId": { - "type": "string", - "description": "Immutable id of Chrome OS Device", - "required": true, - "location": "path" - }, - "projection": { - "type": "string", - "description": "Restrict information returned to a set of selected fields.", - "enum": [ - "BASIC", - "FULL" - ], - "enumDescriptions": [ - "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", - "Includes all metadata fields" - ], - "location": "query" - } - }, - "parameterOrder": [ - "customerId", - "deviceId" - ], - "request": { - "$ref": "ChromeOsDevice" - }, - "response": { - "$ref": "ChromeOsDevice" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.device.chromeos" - ] - } - } - }, - "customers": { - "methods": { - "get": { - "id": "directory.customers.get", - "path": "customers/{customerKey}", - "httpMethod": "GET", - "description": "Retrives a customer.", - "parameters": { - "customerKey": { - "type": "string", - "description": "Id of the customer to be retrieved", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerKey" - ], - "response": { - "$ref": "Customer" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.customer", - "https://www.googleapis.com/auth/admin.directory.customer.readonly" - ] - }, - "patch": { - "id": "directory.customers.patch", - "path": "customers/{customerKey}", - "httpMethod": "PATCH", - "description": "Updates a customer. This method supports patch semantics.", - "parameters": { - "customerKey": { - "type": "string", - "description": "Id of the customer to be updated", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerKey" - ], - "request": { - "$ref": "Customer" - }, - "response": { - "$ref": "Customer" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.customer" - ] - }, - "update": { - "id": "directory.customers.update", - "path": "customers/{customerKey}", - "httpMethod": "PUT", - "description": "Updates a customer.", - "parameters": { - "customerKey": { - "type": "string", - "description": "Id of the customer to be updated", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerKey" - ], - "request": { - "$ref": "Customer" - }, - "response": { - "$ref": "Customer" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.customer" - ] - } - } - }, - "domainAliases": { - "methods": { - "delete": { - "id": "directory.domainAliases.delete", - "path": "customer/{customer}/domainaliases/{domainAliasName}", - "httpMethod": "DELETE", - "description": "Deletes a Domain Alias of the customer.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable id of the Google Apps account.", - "required": true, - "location": "path" - }, - "domainAliasName": { - "type": "string", - "description": "Name of domain alias to be retrieved.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "domainAliasName" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.domain" - ] - }, - "get": { - "id": "directory.domainAliases.get", - "path": "customer/{customer}/domainaliases/{domainAliasName}", - "httpMethod": "GET", - "description": "Retrieves a domain alias of the customer.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable id of the Google Apps account.", - "required": true, - "location": "path" - }, - "domainAliasName": { - "type": "string", - "description": "Name of domain alias to be retrieved.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "domainAliasName" - ], - "response": { - "$ref": "DomainAlias" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.domain", - "https://www.googleapis.com/auth/admin.directory.domain.readonly" - ] - }, - "insert": { - "id": "directory.domainAliases.insert", - "path": "customer/{customer}/domainaliases", - "httpMethod": "POST", - "description": "Inserts a Domain alias of the customer.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable id of the Google Apps account.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer" - ], - "request": { - "$ref": "DomainAlias" - }, - "response": { - "$ref": "DomainAlias" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.domain" - ] - }, - "list": { - "id": "directory.domainAliases.list", - "path": "customer/{customer}/domainaliases", - "httpMethod": "GET", - "description": "Lists the domain aliases of the customer.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable id of the Google Apps account.", - "required": true, - "location": "path" - }, - "parentDomainName": { - "type": "string", - "description": "Name of the parent domain for which domain aliases are to be fetched.", - "location": "query" - } - }, - "parameterOrder": [ - "customer" - ], - "response": { - "$ref": "DomainAliases" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.domain", - "https://www.googleapis.com/auth/admin.directory.domain.readonly" - ] - } - } - }, - "domains": { - "methods": { - "delete": { - "id": "directory.domains.delete", - "path": "customer/{customer}/domains/{domainName}", - "httpMethod": "DELETE", - "description": "Deletes a domain of the customer.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable id of the Google Apps account.", - "required": true, - "location": "path" - }, - "domainName": { - "type": "string", - "description": "Name of domain to be deleted", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "domainName" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.domain" - ] - }, - "get": { - "id": "directory.domains.get", - "path": "customer/{customer}/domains/{domainName}", - "httpMethod": "GET", - "description": "Retrives a domain of the customer.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable id of the Google Apps account.", - "required": true, - "location": "path" - }, - "domainName": { - "type": "string", - "description": "Name of domain to be retrieved", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "domainName" - ], - "response": { - "$ref": "Domains" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.domain", - "https://www.googleapis.com/auth/admin.directory.domain.readonly" - ] - }, - "insert": { - "id": "directory.domains.insert", - "path": "customer/{customer}/domains", - "httpMethod": "POST", - "description": "Inserts a domain of the customer.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable id of the Google Apps account.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer" - ], - "request": { - "$ref": "Domains" - }, - "response": { - "$ref": "Domains" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.domain" - ] - }, - "list": { - "id": "directory.domains.list", - "path": "customer/{customer}/domains", - "httpMethod": "GET", - "description": "Lists the domains of the customer.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable id of the Google Apps account.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer" - ], - "response": { - "$ref": "Domains2" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.domain", - "https://www.googleapis.com/auth/admin.directory.domain.readonly" - ] - } - } - }, - "groups": { - "methods": { - "delete": { - "id": "directory.groups.delete", - "path": "groups/{groupKey}", - "httpMethod": "DELETE", - "description": "Delete Group", - "parameters": { - "groupKey": { - "type": "string", - "description": "Email or immutable Id of the group", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "groupKey" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group" - ] - }, - "get": { - "id": "directory.groups.get", - "path": "groups/{groupKey}", - "httpMethod": "GET", - "description": "Retrieve Group", - "parameters": { - "groupKey": { - "type": "string", - "description": "Email or immutable Id of the group", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "groupKey" - ], - "response": { - "$ref": "Group" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group", - "https://www.googleapis.com/auth/admin.directory.group.readonly" - ] - }, - "insert": { - "id": "directory.groups.insert", - "path": "groups", - "httpMethod": "POST", - "description": "Create Group", - "request": { - "$ref": "Group" - }, - "response": { - "$ref": "Group" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group" - ] - }, - "list": { - "id": "directory.groups.list", - "path": "groups", - "httpMethod": "GET", - "description": "Retrieve all groups in a domain (paginated)", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable id of the Google Apps account. In case of multi-domain, to fetch all groups for a customer, fill this field instead of domain.", - "location": "query" - }, - "domain": { - "type": "string", - "description": "Name of the domain. Fill this field to get groups from only this domain. To return all groups in a multi-domain fill customer field instead.", - "location": "query" - }, - "maxResults": { - "type": "integer", - "description": "Maximum number of results to return. Default is 200", - "format": "int32", - "minimum": "1", - "location": "query" - }, - "pageToken": { - "type": "string", - "description": "Token to specify next page in the list", - "location": "query" - }, - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user if only those groups are to be listed, the given user is a member of. If Id, it should match with id of user object", - "location": "query" - } - }, - "response": { - "$ref": "Groups" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group", - "https://www.googleapis.com/auth/admin.directory.group.readonly" - ] - }, - "patch": { - "id": "directory.groups.patch", - "path": "groups/{groupKey}", - "httpMethod": "PATCH", - "description": "Update Group. This method supports patch semantics.", - "parameters": { - "groupKey": { - "type": "string", - "description": "Email or immutable Id of the group. If Id, it should match with id of group object", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "groupKey" - ], - "request": { - "$ref": "Group" - }, - "response": { - "$ref": "Group" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group" - ] - }, - "update": { - "id": "directory.groups.update", - "path": "groups/{groupKey}", - "httpMethod": "PUT", - "description": "Update Group", - "parameters": { - "groupKey": { - "type": "string", - "description": "Email or immutable Id of the group. If Id, it should match with id of group object", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "groupKey" - ], - "request": { - "$ref": "Group" - }, - "response": { - "$ref": "Group" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group" - ] - } - }, - "resources": { - "aliases": { - "methods": { - "delete": { - "id": "directory.groups.aliases.delete", - "path": "groups/{groupKey}/aliases/{alias}", - "httpMethod": "DELETE", - "description": "Remove a alias for the group", - "parameters": { - "alias": { - "type": "string", - "description": "The alias to be removed", - "required": true, - "location": "path" - }, - "groupKey": { - "type": "string", - "description": "Email or immutable Id of the group", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "groupKey", - "alias" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group" - ] - }, - "insert": { - "id": "directory.groups.aliases.insert", - "path": "groups/{groupKey}/aliases", - "httpMethod": "POST", - "description": "Add a alias for the group", - "parameters": { - "groupKey": { - "type": "string", - "description": "Email or immutable Id of the group", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "groupKey" - ], - "request": { - "$ref": "Alias" - }, - "response": { - "$ref": "Alias" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group" - ] - }, - "list": { - "id": "directory.groups.aliases.list", - "path": "groups/{groupKey}/aliases", - "httpMethod": "GET", - "description": "List all aliases for a group", - "parameters": { - "groupKey": { - "type": "string", - "description": "Email or immutable Id of the group", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "groupKey" - ], - "response": { - "$ref": "Aliases" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group", - "https://www.googleapis.com/auth/admin.directory.group.readonly" - ], - "supportsSubscription": true - } - } - } - } - }, - "members": { - "methods": { - "delete": { - "id": "directory.members.delete", - "path": "groups/{groupKey}/members/{memberKey}", - "httpMethod": "DELETE", - "description": "Remove membership.", - "parameters": { - "groupKey": { - "type": "string", - "description": "Email or immutable Id of the group", - "required": true, - "location": "path" - }, - "memberKey": { - "type": "string", - "description": "Email or immutable Id of the member", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "groupKey", - "memberKey" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group", - "https://www.googleapis.com/auth/admin.directory.group.member" - ] - }, - "get": { - "id": "directory.members.get", - "path": "groups/{groupKey}/members/{memberKey}", - "httpMethod": "GET", - "description": "Retrieve Group Member", - "parameters": { - "groupKey": { - "type": "string", - "description": "Email or immutable Id of the group", - "required": true, - "location": "path" - }, - "memberKey": { - "type": "string", - "description": "Email or immutable Id of the member", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "groupKey", - "memberKey" - ], - "response": { - "$ref": "Member" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group", - "https://www.googleapis.com/auth/admin.directory.group.member", - "https://www.googleapis.com/auth/admin.directory.group.member.readonly", - "https://www.googleapis.com/auth/admin.directory.group.readonly" - ] - }, - "insert": { - "id": "directory.members.insert", - "path": "groups/{groupKey}/members", - "httpMethod": "POST", - "description": "Add user to the specified group.", - "parameters": { - "groupKey": { - "type": "string", - "description": "Email or immutable Id of the group", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "groupKey" - ], - "request": { - "$ref": "Member" - }, - "response": { - "$ref": "Member" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group", - "https://www.googleapis.com/auth/admin.directory.group.member" - ] - }, - "list": { - "id": "directory.members.list", - "path": "groups/{groupKey}/members", - "httpMethod": "GET", - "description": "Retrieve all members in a group (paginated)", - "parameters": { - "groupKey": { - "type": "string", - "description": "Email or immutable Id of the group", - "required": true, - "location": "path" - }, - "maxResults": { - "type": "integer", - "description": "Maximum number of results to return. Default is 200", - "format": "int32", - "minimum": "1", - "location": "query" - }, - "pageToken": { - "type": "string", - "description": "Token to specify next page in the list", - "location": "query" - }, - "roles": { - "type": "string", - "description": "Comma separated role values to filter list results on.", - "location": "query" - } - }, - "parameterOrder": [ - "groupKey" - ], - "response": { - "$ref": "Members" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group", - "https://www.googleapis.com/auth/admin.directory.group.member", - "https://www.googleapis.com/auth/admin.directory.group.member.readonly", - "https://www.googleapis.com/auth/admin.directory.group.readonly" - ] - }, - "patch": { - "id": "directory.members.patch", - "path": "groups/{groupKey}/members/{memberKey}", - "httpMethod": "PATCH", - "description": "Update membership of a user in the specified group. This method supports patch semantics.", - "parameters": { - "groupKey": { - "type": "string", - "description": "Email or immutable Id of the group. If Id, it should match with id of group object", - "required": true, - "location": "path" - }, - "memberKey": { - "type": "string", - "description": "Email or immutable Id of the user. If Id, it should match with id of member object", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "groupKey", - "memberKey" - ], - "request": { - "$ref": "Member" - }, - "response": { - "$ref": "Member" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group", - "https://www.googleapis.com/auth/admin.directory.group.member" - ] - }, - "update": { - "id": "directory.members.update", - "path": "groups/{groupKey}/members/{memberKey}", - "httpMethod": "PUT", - "description": "Update membership of a user in the specified group.", - "parameters": { - "groupKey": { - "type": "string", - "description": "Email or immutable Id of the group. If Id, it should match with id of group object", - "required": true, - "location": "path" - }, - "memberKey": { - "type": "string", - "description": "Email or immutable Id of the user. If Id, it should match with id of member object", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "groupKey", - "memberKey" - ], - "request": { - "$ref": "Member" - }, - "response": { - "$ref": "Member" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.group", - "https://www.googleapis.com/auth/admin.directory.group.member" - ] - } - } - }, - "mobiledevices": { - "methods": { - "action": { - "id": "directory.mobiledevices.action", - "path": "customer/{customerId}/devices/mobile/{resourceId}/action", - "httpMethod": "POST", - "description": "Take action on Mobile Device", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "resourceId": { - "type": "string", - "description": "Immutable id of Mobile Device", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId", - "resourceId" - ], - "request": { - "$ref": "MobileDeviceAction" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.device.mobile", - "https://www.googleapis.com/auth/admin.directory.device.mobile.action" - ] - }, - "delete": { - "id": "directory.mobiledevices.delete", - "path": "customer/{customerId}/devices/mobile/{resourceId}", - "httpMethod": "DELETE", - "description": "Delete Mobile Device", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "resourceId": { - "type": "string", - "description": "Immutable id of Mobile Device", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId", - "resourceId" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.device.mobile" - ] - }, - "get": { - "id": "directory.mobiledevices.get", - "path": "customer/{customerId}/devices/mobile/{resourceId}", - "httpMethod": "GET", - "description": "Retrieve Mobile Device", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "projection": { - "type": "string", - "description": "Restrict information returned to a set of selected fields.", - "enum": [ - "BASIC", - "FULL" - ], - "enumDescriptions": [ - "Includes only the basic metadata fields (e.g., deviceId, model, status, type, and status)", - "Includes all metadata fields" - ], - "location": "query" - }, - "resourceId": { - "type": "string", - "description": "Immutable id of Mobile Device", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId", - "resourceId" - ], - "response": { - "$ref": "MobileDevice" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.device.mobile", - "https://www.googleapis.com/auth/admin.directory.device.mobile.action", - "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly" - ] - }, - "list": { - "id": "directory.mobiledevices.list", - "path": "customer/{customerId}/devices/mobile", - "httpMethod": "GET", - "description": "Retrieve all Mobile Devices of a customer (paginated)", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "maxResults": { - "type": "integer", - "description": "Maximum number of results to return. Default is 100", - "format": "int32", - "minimum": "1", - "location": "query" - }, - "orderBy": { - "type": "string", - "description": "Column to use for sorting results", - "enum": [ - "deviceId", - "email", - "lastSync", - "model", - "name", - "os", - "status", - "type" - ], - "enumDescriptions": [ - "Mobile Device serial number.", - "Owner user email.", - "Last policy settings sync date time of the device.", - "Mobile Device model.", - "Owner user name.", - "Mobile operating system.", - "Status of the device.", - "Type of the device." - ], - "location": "query" - }, - "pageToken": { - "type": "string", - "description": "Token to specify next page in the list", - "location": "query" - }, - "projection": { - "type": "string", - "description": "Restrict information returned to a set of selected fields.", - "enum": [ - "BASIC", - "FULL" - ], - "enumDescriptions": [ - "Includes only the basic metadata fields (e.g., deviceId, model, status, type, and status)", - "Includes all metadata fields" - ], - "location": "query" - }, - "query": { - "type": "string", - "description": "Search string in the format given at http://support.google.com/a/bin/answer.py?hl=en&answer=1408863#search", - "location": "query" - }, - "sortOrder": { - "type": "string", - "description": "Whether to return results in ascending or descending order. Only of use when orderBy is also used", - "enum": [ - "ASCENDING", - "DESCENDING" - ], - "enumDescriptions": [ - "Ascending order.", - "Descending order." - ], - "location": "query" - } - }, - "parameterOrder": [ - "customerId" - ], - "response": { - "$ref": "MobileDevices" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.device.mobile", - "https://www.googleapis.com/auth/admin.directory.device.mobile.action", - "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly" - ] - } - } - }, - "notifications": { - "methods": { - "delete": { - "id": "directory.notifications.delete", - "path": "customer/{customer}/notifications/{notificationId}", - "httpMethod": "DELETE", - "description": "Deletes a notification", - "parameters": { - "customer": { - "type": "string", - "description": "The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource.", - "required": true, - "location": "path" - }, - "notificationId": { - "type": "string", - "description": "The unique ID of the notification.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "notificationId" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.notifications" - ] - }, - "get": { - "id": "directory.notifications.get", - "path": "customer/{customer}/notifications/{notificationId}", - "httpMethod": "GET", - "description": "Retrieves a notification.", - "parameters": { - "customer": { - "type": "string", - "description": "The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource.", - "required": true, - "location": "path" - }, - "notificationId": { - "type": "string", - "description": "The unique ID of the notification.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "notificationId" - ], - "response": { - "$ref": "Notification" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.notifications" - ] - }, - "list": { - "id": "directory.notifications.list", - "path": "customer/{customer}/notifications", - "httpMethod": "GET", - "description": "Retrieves a list of notifications.", - "parameters": { - "customer": { - "type": "string", - "description": "The unique ID for the customer's Google account.", - "required": true, - "location": "path" - }, - "language": { - "type": "string", - "description": "The ISO 639-1 code of the language notifications are returned in. The default is English (en).", - "location": "query" - }, - "maxResults": { - "type": "integer", - "description": "Maximum number of notifications to return per page. The default is 100.", - "format": "uint32", - "location": "query" - }, - "pageToken": { - "type": "string", - "description": "The token to specify the page of results to retrieve.", - "location": "query" - } - }, - "parameterOrder": [ - "customer" - ], - "response": { - "$ref": "Notifications" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.notifications" - ] - }, - "patch": { - "id": "directory.notifications.patch", - "path": "customer/{customer}/notifications/{notificationId}", - "httpMethod": "PATCH", - "description": "Updates a notification. This method supports patch semantics.", - "parameters": { - "customer": { - "type": "string", - "description": "The unique ID for the customer's Google account.", - "required": true, - "location": "path" - }, - "notificationId": { - "type": "string", - "description": "The unique ID of the notification.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "notificationId" - ], - "request": { - "$ref": "Notification" - }, - "response": { - "$ref": "Notification" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.notifications" - ] - }, - "update": { - "id": "directory.notifications.update", - "path": "customer/{customer}/notifications/{notificationId}", - "httpMethod": "PUT", - "description": "Updates a notification.", - "parameters": { - "customer": { - "type": "string", - "description": "The unique ID for the customer's Google account.", - "required": true, - "location": "path" - }, - "notificationId": { - "type": "string", - "description": "The unique ID of the notification.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "notificationId" - ], - "request": { - "$ref": "Notification" - }, - "response": { - "$ref": "Notification" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.notifications" - ] - } - } - }, - "orgunits": { - "methods": { - "delete": { - "id": "directory.orgunits.delete", - "path": "customer/{customerId}/orgunits{/orgUnitPath*}", - "httpMethod": "DELETE", - "description": "Remove Organization Unit", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "orgUnitPath": { - "type": "string", - "description": "Full path of the organization unit or its Id", - "required": true, - "repeated": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId", - "orgUnitPath" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.orgunit" - ] - }, - "get": { - "id": "directory.orgunits.get", - "path": "customer/{customerId}/orgunits{/orgUnitPath*}", - "httpMethod": "GET", - "description": "Retrieve Organization Unit", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "orgUnitPath": { - "type": "string", - "description": "Full path of the organization unit or its Id", - "required": true, - "repeated": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId", - "orgUnitPath" - ], - "response": { - "$ref": "OrgUnit" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.orgunit", - "https://www.googleapis.com/auth/admin.directory.orgunit.readonly" - ] - }, - "insert": { - "id": "directory.orgunits.insert", - "path": "customer/{customerId}/orgunits", - "httpMethod": "POST", - "description": "Add Organization Unit", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId" - ], - "request": { - "$ref": "OrgUnit" - }, - "response": { - "$ref": "OrgUnit" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.orgunit" - ] - }, - "list": { - "id": "directory.orgunits.list", - "path": "customer/{customerId}/orgunits", - "httpMethod": "GET", - "description": "Retrieve all Organization Units", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "orgUnitPath": { - "type": "string", - "description": "the URL-encoded organization unit's path or its Id", - "default": "", - "location": "query" - }, - "type": { - "type": "string", - "description": "Whether to return all sub-organizations or just immediate children", - "enum": [ - "all", - "children" - ], - "enumDescriptions": [ - "All sub-organization units.", - "Immediate children only (default)." - ], - "location": "query" - } - }, - "parameterOrder": [ - "customerId" - ], - "response": { - "$ref": "OrgUnits" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.orgunit", - "https://www.googleapis.com/auth/admin.directory.orgunit.readonly" - ] - }, - "patch": { - "id": "directory.orgunits.patch", - "path": "customer/{customerId}/orgunits{/orgUnitPath*}", - "httpMethod": "PATCH", - "description": "Update Organization Unit. This method supports patch semantics.", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "orgUnitPath": { - "type": "string", - "description": "Full path of the organization unit or its Id", - "required": true, - "repeated": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId", - "orgUnitPath" - ], - "request": { - "$ref": "OrgUnit" - }, - "response": { - "$ref": "OrgUnit" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.orgunit" - ] - }, - "update": { - "id": "directory.orgunits.update", - "path": "customer/{customerId}/orgunits{/orgUnitPath*}", - "httpMethod": "PUT", - "description": "Update Organization Unit", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "orgUnitPath": { - "type": "string", - "description": "Full path of the organization unit or its Id", - "required": true, - "repeated": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId", - "orgUnitPath" - ], - "request": { - "$ref": "OrgUnit" - }, - "response": { - "$ref": "OrgUnit" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.orgunit" - ] - } - } - }, - "privileges": { - "methods": { - "list": { - "id": "directory.privileges.list", - "path": "customer/{customer}/roles/ALL/privileges", - "httpMethod": "GET", - "description": "Retrieves a paginated list of all privileges for a customer.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable ID of the Google Apps account.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer" - ], - "response": { - "$ref": "Privileges" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.rolemanagement", - "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" - ] - } - } - }, - "resources": { - "resources": { - "calendars": { - "methods": { - "delete": { - "id": "directory.resources.calendars.delete", - "path": "customer/{customer}/resources/calendars/{calendarResourceId}", - "httpMethod": "DELETE", - "description": "Deletes a calendar resource.", - "parameters": { - "calendarResourceId": { - "type": "string", - "description": "The unique ID of the calendar resource to delete.", - "required": true, - "location": "path" - }, - "customer": { - "type": "string", - "description": "The unique ID for the customer's Google account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "calendarResourceId" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.resource.calendar" - ] - }, - "get": { - "id": "directory.resources.calendars.get", - "path": "customer/{customer}/resources/calendars/{calendarResourceId}", - "httpMethod": "GET", - "description": "Retrieves a calendar resource.", - "parameters": { - "calendarResourceId": { - "type": "string", - "description": "The unique ID of the calendar resource to retrieve.", - "required": true, - "location": "path" - }, - "customer": { - "type": "string", - "description": "The unique ID for the customer's Google account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "calendarResourceId" - ], - "response": { - "$ref": "CalendarResource" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.resource.calendar", - "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" - ] - }, - "insert": { - "id": "directory.resources.calendars.insert", - "path": "customer/{customer}/resources/calendars", - "httpMethod": "POST", - "description": "Inserts a calendar resource.", - "parameters": { - "customer": { - "type": "string", - "description": "The unique ID for the customer's Google account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer" - ], - "request": { - "$ref": "CalendarResource" - }, - "response": { - "$ref": "CalendarResource" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.resource.calendar" - ] - }, - "list": { - "id": "directory.resources.calendars.list", - "path": "customer/{customer}/resources/calendars", - "httpMethod": "GET", - "description": "Retrieves a list of calendar resources for an account.", - "parameters": { - "customer": { - "type": "string", - "description": "The unique ID for the customer's Google account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", - "required": true, - "location": "path" - }, - "maxResults": { - "type": "integer", - "description": "Maximum number of results to return.", - "format": "int32", - "minimum": "1", - "maximum": "500", - "location": "query" - }, - "pageToken": { - "type": "string", - "description": "Token to specify the next page in the list.", - "location": "query" - } - }, - "parameterOrder": [ - "customer" - ], - "response": { - "$ref": "CalendarResources" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.resource.calendar", - "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" - ] - }, - "patch": { - "id": "directory.resources.calendars.patch", - "path": "customer/{customer}/resources/calendars/{calendarResourceId}", - "httpMethod": "PATCH", - "description": "Updates a calendar resource. This method supports patch semantics.", - "parameters": { - "calendarResourceId": { - "type": "string", - "description": "The unique ID of the calendar resource to update.", - "required": true, - "location": "path" - }, - "customer": { - "type": "string", - "description": "The unique ID for the customer's Google account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "calendarResourceId" - ], - "request": { - "$ref": "CalendarResource" - }, - "response": { - "$ref": "CalendarResource" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.resource.calendar" - ] - }, - "update": { - "id": "directory.resources.calendars.update", - "path": "customer/{customer}/resources/calendars/{calendarResourceId}", - "httpMethod": "PUT", - "description": "Updates a calendar resource.", - "parameters": { - "calendarResourceId": { - "type": "string", - "description": "The unique ID of the calendar resource to update.", - "required": true, - "location": "path" - }, - "customer": { - "type": "string", - "description": "The unique ID for the customer's Google account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "calendarResourceId" - ], - "request": { - "$ref": "CalendarResource" - }, - "response": { - "$ref": "CalendarResource" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.resource.calendar" - ] - } - } - } - } - }, - "roleAssignments": { - "methods": { - "delete": { - "id": "directory.roleAssignments.delete", - "path": "customer/{customer}/roleassignments/{roleAssignmentId}", - "httpMethod": "DELETE", - "description": "Deletes a role assignment.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable ID of the Google Apps account.", - "required": true, - "location": "path" - }, - "roleAssignmentId": { - "type": "string", - "description": "Immutable ID of the role assignment.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "roleAssignmentId" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.rolemanagement" - ] - }, - "get": { - "id": "directory.roleAssignments.get", - "path": "customer/{customer}/roleassignments/{roleAssignmentId}", - "httpMethod": "GET", - "description": "Retrieve a role assignment.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable ID of the Google Apps account.", - "required": true, - "location": "path" - }, - "roleAssignmentId": { - "type": "string", - "description": "Immutable ID of the role assignment.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "roleAssignmentId" - ], - "response": { - "$ref": "RoleAssignment" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.rolemanagement", - "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" - ] - }, - "insert": { - "id": "directory.roleAssignments.insert", - "path": "customer/{customer}/roleassignments", - "httpMethod": "POST", - "description": "Creates a role assignment.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable ID of the Google Apps account.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer" - ], - "request": { - "$ref": "RoleAssignment" - }, - "response": { - "$ref": "RoleAssignment" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.rolemanagement" - ] - }, - "list": { - "id": "directory.roleAssignments.list", - "path": "customer/{customer}/roleassignments", - "httpMethod": "GET", - "description": "Retrieves a paginated list of all roleAssignments.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable ID of the Google Apps account.", - "required": true, - "location": "path" - }, - "maxResults": { - "type": "integer", - "description": "Maximum number of results to return.", - "format": "int32", - "minimum": "1", - "maximum": "200", - "location": "query" - }, - "pageToken": { - "type": "string", - "description": "Token to specify the next page in the list.", - "location": "query" - }, - "roleId": { - "type": "string", - "description": "Immutable ID of a role. If included in the request, returns only role assignments containing this role ID.", - "location": "query" - }, - "userKey": { - "type": "string", - "description": "The user's primary email address, alias email address, or unique user ID. If included in the request, returns role assignments only for this user.", - "location": "query" - } - }, - "parameterOrder": [ - "customer" - ], - "response": { - "$ref": "RoleAssignments" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.rolemanagement", - "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" - ] - } - } - }, - "roles": { - "methods": { - "delete": { - "id": "directory.roles.delete", - "path": "customer/{customer}/roles/{roleId}", - "httpMethod": "DELETE", - "description": "Deletes a role.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable ID of the Google Apps account.", - "required": true, - "location": "path" - }, - "roleId": { - "type": "string", - "description": "Immutable ID of the role.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "roleId" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.rolemanagement" - ] - }, - "get": { - "id": "directory.roles.get", - "path": "customer/{customer}/roles/{roleId}", - "httpMethod": "GET", - "description": "Retrieves a role.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable ID of the Google Apps account.", - "required": true, - "location": "path" - }, - "roleId": { - "type": "string", - "description": "Immutable ID of the role.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "roleId" - ], - "response": { - "$ref": "Role" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.rolemanagement", - "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" - ] - }, - "insert": { - "id": "directory.roles.insert", - "path": "customer/{customer}/roles", - "httpMethod": "POST", - "description": "Creates a role.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable ID of the Google Apps account.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer" - ], - "request": { - "$ref": "Role" - }, - "response": { - "$ref": "Role" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.rolemanagement" - ] - }, - "list": { - "id": "directory.roles.list", - "path": "customer/{customer}/roles", - "httpMethod": "GET", - "description": "Retrieves a paginated list of all the roles in a domain.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable id of the Google Apps account.", - "required": true, - "location": "path" - }, - "maxResults": { - "type": "integer", - "description": "Maximum number of results to return.", - "format": "int32", - "minimum": "1", - "maximum": "100", - "location": "query" - }, - "pageToken": { - "type": "string", - "description": "Token to specify the next page in the list.", - "location": "query" - } - }, - "parameterOrder": [ - "customer" - ], - "response": { - "$ref": "Roles" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.rolemanagement", - "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" - ] - }, - "patch": { - "id": "directory.roles.patch", - "path": "customer/{customer}/roles/{roleId}", - "httpMethod": "PATCH", - "description": "Updates a role. This method supports patch semantics.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable ID of the Google Apps account.", - "required": true, - "location": "path" - }, - "roleId": { - "type": "string", - "description": "Immutable ID of the role.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "roleId" - ], - "request": { - "$ref": "Role" - }, - "response": { - "$ref": "Role" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.rolemanagement" - ] - }, - "update": { - "id": "directory.roles.update", - "path": "customer/{customer}/roles/{roleId}", - "httpMethod": "PUT", - "description": "Updates a role.", - "parameters": { - "customer": { - "type": "string", - "description": "Immutable ID of the Google Apps account.", - "required": true, - "location": "path" - }, - "roleId": { - "type": "string", - "description": "Immutable ID of the role.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customer", - "roleId" - ], - "request": { - "$ref": "Role" - }, - "response": { - "$ref": "Role" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.rolemanagement" - ] - } - } - }, - "schemas": { - "methods": { - "delete": { - "id": "directory.schemas.delete", - "path": "customer/{customerId}/schemas/{schemaKey}", - "httpMethod": "DELETE", - "description": "Delete schema", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "schemaKey": { - "type": "string", - "description": "Name or immutable Id of the schema", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId", - "schemaKey" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.userschema" - ] - }, - "get": { - "id": "directory.schemas.get", - "path": "customer/{customerId}/schemas/{schemaKey}", - "httpMethod": "GET", - "description": "Retrieve schema", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "schemaKey": { - "type": "string", - "description": "Name or immutable Id of the schema", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId", - "schemaKey" - ], - "response": { - "$ref": "Schema" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.userschema", - "https://www.googleapis.com/auth/admin.directory.userschema.readonly" - ] - }, - "insert": { - "id": "directory.schemas.insert", - "path": "customer/{customerId}/schemas", - "httpMethod": "POST", - "description": "Create schema.", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId" - ], - "request": { - "$ref": "Schema" - }, - "response": { - "$ref": "Schema" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.userschema" - ] - }, - "list": { - "id": "directory.schemas.list", - "path": "customer/{customerId}/schemas", - "httpMethod": "GET", - "description": "Retrieve all schemas for a customer", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId" - ], - "response": { - "$ref": "Schemas" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.userschema", - "https://www.googleapis.com/auth/admin.directory.userschema.readonly" - ] - }, - "patch": { - "id": "directory.schemas.patch", - "path": "customer/{customerId}/schemas/{schemaKey}", - "httpMethod": "PATCH", - "description": "Update schema. This method supports patch semantics.", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "schemaKey": { - "type": "string", - "description": "Name or immutable Id of the schema.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId", - "schemaKey" - ], - "request": { - "$ref": "Schema" - }, - "response": { - "$ref": "Schema" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.userschema" - ] - }, - "update": { - "id": "directory.schemas.update", - "path": "customer/{customerId}/schemas/{schemaKey}", - "httpMethod": "PUT", - "description": "Update schema", - "parameters": { - "customerId": { - "type": "string", - "description": "Immutable id of the Google Apps account", - "required": true, - "location": "path" - }, - "schemaKey": { - "type": "string", - "description": "Name or immutable Id of the schema.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "customerId", - "schemaKey" - ], - "request": { - "$ref": "Schema" - }, - "response": { - "$ref": "Schema" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.userschema" - ] - } - } - }, - "tokens": { - "methods": { - "delete": { - "id": "directory.tokens.delete", - "path": "users/{userKey}/tokens/{clientId}", - "httpMethod": "DELETE", - "description": "Delete all access tokens issued by a user for an application.", - "parameters": { - "clientId": { - "type": "string", - "description": "The Client ID of the application the token is issued to.", - "required": true, - "location": "path" - }, - "userKey": { - "type": "string", - "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey", - "clientId" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user.security" - ] - }, - "get": { - "id": "directory.tokens.get", - "path": "users/{userKey}/tokens/{clientId}", - "httpMethod": "GET", - "description": "Get information about an access token issued by a user.", - "parameters": { - "clientId": { - "type": "string", - "description": "The Client ID of the application the token is issued to.", - "required": true, - "location": "path" - }, - "userKey": { - "type": "string", - "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey", - "clientId" - ], - "response": { - "$ref": "Token" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user.security" - ] - }, - "list": { - "id": "directory.tokens.list", - "path": "users/{userKey}/tokens", - "httpMethod": "GET", - "description": "Returns the set of tokens specified user has issued to 3rd party applications.", - "parameters": { - "userKey": { - "type": "string", - "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "response": { - "$ref": "Tokens" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user.security" - ] - } - } - }, - "users": { - "methods": { - "delete": { - "id": "directory.users.delete", - "path": "users/{userKey}", - "httpMethod": "DELETE", - "description": "Delete user", - "parameters": { - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user" - ] - }, - "get": { - "id": "directory.users.get", - "path": "users/{userKey}", - "httpMethod": "GET", - "description": "retrieve user", - "parameters": { - "customFieldMask": { - "type": "string", - "description": "Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.", - "location": "query" - }, - "projection": { - "type": "string", - "description": "What subset of fields to fetch for this user.", - "default": "basic", - "enum": [ - "basic", - "custom", - "full" - ], - "enumDescriptions": [ - "Do not include any custom fields for the user.", - "Include custom fields from schemas mentioned in customFieldMask.", - "Include all fields associated with this user." - ], - "location": "query" - }, - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user", - "required": true, - "location": "path" - }, - "viewType": { - "type": "string", - "description": "Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.", - "default": "admin_view", - "enum": [ - "admin_view", - "domain_public" - ], - "enumDescriptions": [ - "Fetches the ADMIN_VIEW of the user.", - "Fetches the DOMAIN_PUBLIC view of the user." - ], - "location": "query" - } - }, - "parameterOrder": [ - "userKey" - ], - "response": { - "$ref": "User" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user", - "https://www.googleapis.com/auth/admin.directory.user.readonly" - ] - }, - "insert": { - "id": "directory.users.insert", - "path": "users", - "httpMethod": "POST", - "description": "create user.", - "request": { - "$ref": "User" - }, - "response": { - "$ref": "User" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user" - ] - }, - "list": { - "id": "directory.users.list", - "path": "users", - "httpMethod": "GET", - "description": "Retrieve either deleted users or all users in a domain (paginated)", - "parameters": { - "customFieldMask": { - "type": "string", - "description": "Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.", - "location": "query" - }, - "customer": { - "type": "string", - "description": "Immutable id of the Google Apps account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain.", - "location": "query" - }, - "domain": { - "type": "string", - "description": "Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead.", - "location": "query" - }, - "event": { - "type": "string", - "description": "Event on which subscription is intended (if subscribing)", - "enum": [ - "add", - "delete", - "makeAdmin", - "undelete", - "update" - ], - "enumDescriptions": [ - "User Created Event", - "User Deleted Event", - "User Admin Status Change Event", - "User Undeleted Event", - "User Updated Event" - ], - "location": "query" - }, - "maxResults": { - "type": "integer", - "description": "Maximum number of results to return. Default is 100. Max allowed is 500", - "format": "int32", - "minimum": "1", - "maximum": "500", - "location": "query" - }, - "orderBy": { - "type": "string", - "description": "Column to use for sorting results", - "enum": [ - "email", - "familyName", - "givenName" - ], - "enumDescriptions": [ - "Primary email of the user.", - "User's family name.", - "User's given name." - ], - "location": "query" - }, - "pageToken": { - "type": "string", - "description": "Token to specify next page in the list", - "location": "query" - }, - "projection": { - "type": "string", - "description": "What subset of fields to fetch for this user.", - "default": "basic", - "enum": [ - "basic", - "custom", - "full" - ], - "enumDescriptions": [ - "Do not include any custom fields for the user.", - "Include custom fields from schemas mentioned in customFieldMask.", - "Include all fields associated with this user." - ], - "location": "query" - }, - "query": { - "type": "string", - "description": "Query string search. Should be of the form \"\". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users", - "location": "query" - }, - "showDeleted": { - "type": "string", - "description": "If set to true retrieves the list of deleted users. Default is false", - "location": "query" - }, - "sortOrder": { - "type": "string", - "description": "Whether to return results in ascending or descending order.", - "enum": [ - "ASCENDING", - "DESCENDING" - ], - "enumDescriptions": [ - "Ascending order.", - "Descending order." - ], - "location": "query" - }, - "viewType": { - "type": "string", - "description": "Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.", - "default": "admin_view", - "enum": [ - "admin_view", - "domain_public" - ], - "enumDescriptions": [ - "Fetches the ADMIN_VIEW of the user.", - "Fetches the DOMAIN_PUBLIC view of the user." - ], - "location": "query" - } - }, - "response": { - "$ref": "Users" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user", - "https://www.googleapis.com/auth/admin.directory.user.readonly" - ], - "supportsSubscription": true - }, - "makeAdmin": { - "id": "directory.users.makeAdmin", - "path": "users/{userKey}/makeAdmin", - "httpMethod": "POST", - "description": "change admin status of a user", - "parameters": { - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user as admin", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "request": { - "$ref": "UserMakeAdmin" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user" - ] - }, - "patch": { - "id": "directory.users.patch", - "path": "users/{userKey}", - "httpMethod": "PATCH", - "description": "update user. This method supports patch semantics.", - "parameters": { - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user. If Id, it should match with id of user object", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "request": { - "$ref": "User" - }, - "response": { - "$ref": "User" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user" - ] - }, - "undelete": { - "id": "directory.users.undelete", - "path": "users/{userKey}/undelete", - "httpMethod": "POST", - "description": "Undelete a deleted user", - "parameters": { - "userKey": { - "type": "string", - "description": "The immutable id of the user", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "request": { - "$ref": "UserUndelete" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user" - ] - }, - "update": { - "id": "directory.users.update", - "path": "users/{userKey}", - "httpMethod": "PUT", - "description": "update user", - "parameters": { - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user. If Id, it should match with id of user object", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "request": { - "$ref": "User" - }, - "response": { - "$ref": "User" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user" - ] - }, - "watch": { - "id": "directory.users.watch", - "path": "users/watch", - "httpMethod": "POST", - "description": "Watch for changes in users list", - "parameters": { - "customFieldMask": { - "type": "string", - "description": "Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.", - "location": "query" - }, - "customer": { - "type": "string", - "description": "Immutable id of the Google Apps account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain.", - "location": "query" - }, - "domain": { - "type": "string", - "description": "Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead.", - "location": "query" - }, - "event": { - "type": "string", - "description": "Event on which subscription is intended (if subscribing)", - "enum": [ - "add", - "delete", - "makeAdmin", - "undelete", - "update" - ], - "enumDescriptions": [ - "User Created Event", - "User Deleted Event", - "User Admin Status Change Event", - "User Undeleted Event", - "User Updated Event" - ], - "location": "query" - }, - "maxResults": { - "type": "integer", - "description": "Maximum number of results to return. Default is 100. Max allowed is 500", - "format": "int32", - "minimum": "1", - "maximum": "500", - "location": "query" - }, - "orderBy": { - "type": "string", - "description": "Column to use for sorting results", - "enum": [ - "email", - "familyName", - "givenName" - ], - "enumDescriptions": [ - "Primary email of the user.", - "User's family name.", - "User's given name." - ], - "location": "query" - }, - "pageToken": { - "type": "string", - "description": "Token to specify next page in the list", - "location": "query" - }, - "projection": { - "type": "string", - "description": "What subset of fields to fetch for this user.", - "default": "basic", - "enum": [ - "basic", - "custom", - "full" - ], - "enumDescriptions": [ - "Do not include any custom fields for the user.", - "Include custom fields from schemas mentioned in customFieldMask.", - "Include all fields associated with this user." - ], - "location": "query" - }, - "query": { - "type": "string", - "description": "Query string search. Should be of the form \"\". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users", - "location": "query" - }, - "showDeleted": { - "type": "string", - "description": "If set to true retrieves the list of deleted users. Default is false", - "location": "query" - }, - "sortOrder": { - "type": "string", - "description": "Whether to return results in ascending or descending order.", - "enum": [ - "ASCENDING", - "DESCENDING" - ], - "enumDescriptions": [ - "Ascending order.", - "Descending order." - ], - "location": "query" - }, - "viewType": { - "type": "string", - "description": "Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.", - "default": "admin_view", - "enum": [ - "admin_view", - "domain_public" - ], - "enumDescriptions": [ - "Fetches the ADMIN_VIEW of the user.", - "Fetches the DOMAIN_PUBLIC view of the user." - ], - "location": "query" - } - }, - "request": { - "$ref": "Channel", - "parameterName": "resource" - }, - "response": { - "$ref": "Channel" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user", - "https://www.googleapis.com/auth/admin.directory.user.readonly" - ], - "supportsSubscription": true - } - }, - "resources": { - "aliases": { - "methods": { - "delete": { - "id": "directory.users.aliases.delete", - "path": "users/{userKey}/aliases/{alias}", - "httpMethod": "DELETE", - "description": "Remove a alias for the user", - "parameters": { - "alias": { - "type": "string", - "description": "The alias to be removed", - "required": true, - "location": "path" - }, - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey", - "alias" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user", - "https://www.googleapis.com/auth/admin.directory.user.alias" - ] - }, - "insert": { - "id": "directory.users.aliases.insert", - "path": "users/{userKey}/aliases", - "httpMethod": "POST", - "description": "Add a alias for the user", - "parameters": { - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "request": { - "$ref": "Alias" - }, - "response": { - "$ref": "Alias" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user", - "https://www.googleapis.com/auth/admin.directory.user.alias" - ] - }, - "list": { - "id": "directory.users.aliases.list", - "path": "users/{userKey}/aliases", - "httpMethod": "GET", - "description": "List all aliases for a user", - "parameters": { - "event": { - "type": "string", - "description": "Event on which subscription is intended (if subscribing)", - "enum": [ - "add", - "delete" - ], - "enumDescriptions": [ - "Alias Created Event", - "Alias Deleted Event" - ], - "location": "query" - }, - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "response": { - "$ref": "Aliases" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user", - "https://www.googleapis.com/auth/admin.directory.user.alias", - "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", - "https://www.googleapis.com/auth/admin.directory.user.readonly" - ], - "supportsSubscription": true - }, - "watch": { - "id": "directory.users.aliases.watch", - "path": "users/{userKey}/aliases/watch", - "httpMethod": "POST", - "description": "Watch for changes in user aliases list", - "parameters": { - "event": { - "type": "string", - "description": "Event on which subscription is intended (if subscribing)", - "enum": [ - "add", - "delete" - ], - "enumDescriptions": [ - "Alias Created Event", - "Alias Deleted Event" - ], - "location": "query" - }, - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "request": { - "$ref": "Channel", - "parameterName": "resource" - }, - "response": { - "$ref": "Channel" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user", - "https://www.googleapis.com/auth/admin.directory.user.alias", - "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", - "https://www.googleapis.com/auth/admin.directory.user.readonly" - ], - "supportsSubscription": true - } - } - }, - "photos": { - "methods": { - "delete": { - "id": "directory.users.photos.delete", - "path": "users/{userKey}/photos/thumbnail", - "httpMethod": "DELETE", - "description": "Remove photos for the user", - "parameters": { - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user" - ] - }, - "get": { - "id": "directory.users.photos.get", - "path": "users/{userKey}/photos/thumbnail", - "httpMethod": "GET", - "description": "Retrieve photo of a user", - "parameters": { - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "response": { - "$ref": "UserPhoto" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user", - "https://www.googleapis.com/auth/admin.directory.user.readonly" - ] - }, - "patch": { - "id": "directory.users.photos.patch", - "path": "users/{userKey}/photos/thumbnail", - "httpMethod": "PATCH", - "description": "Add a photo for the user. This method supports patch semantics.", - "parameters": { - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "request": { - "$ref": "UserPhoto" - }, - "response": { - "$ref": "UserPhoto" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user" - ] - }, - "update": { - "id": "directory.users.photos.update", - "path": "users/{userKey}/photos/thumbnail", - "httpMethod": "PUT", - "description": "Add a photo for the user", - "parameters": { - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "request": { - "$ref": "UserPhoto" - }, - "response": { - "$ref": "UserPhoto" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user" - ] - } - } - } - } - }, - "verificationCodes": { - "methods": { - "generate": { - "id": "directory.verificationCodes.generate", - "path": "users/{userKey}/verificationCodes/generate", - "httpMethod": "POST", - "description": "Generate new backup verification codes for the user.", - "parameters": { - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user.security" - ] - }, - "invalidate": { - "id": "directory.verificationCodes.invalidate", - "path": "users/{userKey}/verificationCodes/invalidate", - "httpMethod": "POST", - "description": "Invalidate the current backup verification codes for the user.", - "parameters": { - "userKey": { - "type": "string", - "description": "Email or immutable Id of the user", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user.security" - ] - }, - "list": { - "id": "directory.verificationCodes.list", - "path": "users/{userKey}/verificationCodes", - "httpMethod": "GET", - "description": "Returns the current set of valid backup verification codes for the specified user.", - "parameters": { - "userKey": { - "type": "string", - "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - "required": true, - "location": "path" - } - }, - "parameterOrder": [ - "userKey" - ], - "response": { - "$ref": "VerificationCodes" - }, - "scopes": [ - "https://www.googleapis.com/auth/admin.directory.user.security" - ] - } - } - } - } -} diff --git a/Godeps/_workspace/src/google.golang.org/api/admin/directory/v1/admin-gen.go b/Godeps/_workspace/src/google.golang.org/api/admin/directory/v1/admin-gen.go deleted file mode 100644 index d585e0c0a..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/admin/directory/v1/admin-gen.go +++ /dev/null @@ -1,15449 +0,0 @@ -// Package admin provides access to the Admin Directory API. -// -// See https://developers.google.com/admin-sdk/directory/ -// -// Usage example: -// -// import "google.golang.org/api/admin/directory/v1" -// ... -// adminService, err := admin.New(oauthHttpClient) -package admin - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - context "golang.org/x/net/context" - ctxhttp "golang.org/x/net/context/ctxhttp" - gensupport "google.golang.org/api/gensupport" - googleapi "google.golang.org/api/googleapi" - "io" - "net/http" - "net/url" - "strconv" - "strings" -) - -// Always reference these packages, just in case the auto-generated code -// below doesn't. -var _ = bytes.NewBuffer -var _ = strconv.Itoa -var _ = fmt.Sprintf -var _ = json.NewDecoder -var _ = io.Copy -var _ = url.Parse -var _ = gensupport.MarshalJSON -var _ = googleapi.Version -var _ = errors.New -var _ = strings.Replace -var _ = context.Canceled -var _ = ctxhttp.Do - -const apiId = "admin:directory_v1" -const apiName = "admin" -const apiVersion = "directory_v1" -const basePath = "https://www.googleapis.com/admin/directory/v1/" - -// OAuth2 scopes used by this API. -const ( - // View and manage customer related information - AdminDirectoryCustomerScope = "https://www.googleapis.com/auth/admin.directory.customer" - - // View customer related information - AdminDirectoryCustomerReadonlyScope = "https://www.googleapis.com/auth/admin.directory.customer.readonly" - - // View and manage your Chrome OS devices' metadata - AdminDirectoryDeviceChromeosScope = "https://www.googleapis.com/auth/admin.directory.device.chromeos" - - // View your Chrome OS devices' metadata - AdminDirectoryDeviceChromeosReadonlyScope = "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly" - - // View and manage your mobile devices' metadata - AdminDirectoryDeviceMobileScope = "https://www.googleapis.com/auth/admin.directory.device.mobile" - - // Manage your mobile devices by performing administrative tasks - AdminDirectoryDeviceMobileActionScope = "https://www.googleapis.com/auth/admin.directory.device.mobile.action" - - // View your mobile devices' metadata - AdminDirectoryDeviceMobileReadonlyScope = "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly" - - // View and manage the provisioning of domains for your customers - AdminDirectoryDomainScope = "https://www.googleapis.com/auth/admin.directory.domain" - - // View domains related to your customers - AdminDirectoryDomainReadonlyScope = "https://www.googleapis.com/auth/admin.directory.domain.readonly" - - // View and manage the provisioning of groups on your domain - AdminDirectoryGroupScope = "https://www.googleapis.com/auth/admin.directory.group" - - // View and manage group subscriptions on your domain - AdminDirectoryGroupMemberScope = "https://www.googleapis.com/auth/admin.directory.group.member" - - // View group subscriptions on your domain - AdminDirectoryGroupMemberReadonlyScope = "https://www.googleapis.com/auth/admin.directory.group.member.readonly" - - // View groups on your domain - AdminDirectoryGroupReadonlyScope = "https://www.googleapis.com/auth/admin.directory.group.readonly" - - // View and manage notifications received on your domain - AdminDirectoryNotificationsScope = "https://www.googleapis.com/auth/admin.directory.notifications" - - // View and manage organization units on your domain - AdminDirectoryOrgunitScope = "https://www.googleapis.com/auth/admin.directory.orgunit" - - // View organization units on your domain - AdminDirectoryOrgunitReadonlyScope = "https://www.googleapis.com/auth/admin.directory.orgunit.readonly" - - // View and manage the provisioning of calendar resources on your domain - AdminDirectoryResourceCalendarScope = "https://www.googleapis.com/auth/admin.directory.resource.calendar" - - // View calendar resources on your domain - AdminDirectoryResourceCalendarReadonlyScope = "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" - - // Manage delegated admin roles for your domain - AdminDirectoryRolemanagementScope = "https://www.googleapis.com/auth/admin.directory.rolemanagement" - - // View delegated admin roles for your domain - AdminDirectoryRolemanagementReadonlyScope = "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" - - // View and manage the provisioning of users on your domain - AdminDirectoryUserScope = "https://www.googleapis.com/auth/admin.directory.user" - - // View and manage user aliases on your domain - AdminDirectoryUserAliasScope = "https://www.googleapis.com/auth/admin.directory.user.alias" - - // View user aliases on your domain - AdminDirectoryUserAliasReadonlyScope = "https://www.googleapis.com/auth/admin.directory.user.alias.readonly" - - // View users on your domain - AdminDirectoryUserReadonlyScope = "https://www.googleapis.com/auth/admin.directory.user.readonly" - - // Manage data access permissions for users on your domain - AdminDirectoryUserSecurityScope = "https://www.googleapis.com/auth/admin.directory.user.security" - - // View and manage the provisioning of user schemas on your domain - AdminDirectoryUserschemaScope = "https://www.googleapis.com/auth/admin.directory.userschema" - - // View user schemas on your domain - AdminDirectoryUserschemaReadonlyScope = "https://www.googleapis.com/auth/admin.directory.userschema.readonly" -) - -func New(client *http.Client) (*Service, error) { - if client == nil { - return nil, errors.New("client is nil") - } - s := &Service{client: client, BasePath: basePath} - s.Asps = NewAspsService(s) - s.Channels = NewChannelsService(s) - s.Chromeosdevices = NewChromeosdevicesService(s) - s.Customers = NewCustomersService(s) - s.DomainAliases = NewDomainAliasesService(s) - s.Domains = NewDomainsService(s) - s.Groups = NewGroupsService(s) - s.Members = NewMembersService(s) - s.Mobiledevices = NewMobiledevicesService(s) - s.Notifications = NewNotificationsService(s) - s.Orgunits = NewOrgunitsService(s) - s.Privileges = NewPrivilegesService(s) - s.Resources = NewResourcesService(s) - s.RoleAssignments = NewRoleAssignmentsService(s) - s.Roles = NewRolesService(s) - s.Schemas = NewSchemasService(s) - s.Tokens = NewTokensService(s) - s.Users = NewUsersService(s) - s.VerificationCodes = NewVerificationCodesService(s) - return s, nil -} - -type Service struct { - client *http.Client - BasePath string // API endpoint base URL - UserAgent string // optional additional User-Agent fragment - - Asps *AspsService - - Channels *ChannelsService - - Chromeosdevices *ChromeosdevicesService - - Customers *CustomersService - - DomainAliases *DomainAliasesService - - Domains *DomainsService - - Groups *GroupsService - - Members *MembersService - - Mobiledevices *MobiledevicesService - - Notifications *NotificationsService - - Orgunits *OrgunitsService - - Privileges *PrivilegesService - - Resources *ResourcesService - - RoleAssignments *RoleAssignmentsService - - Roles *RolesService - - Schemas *SchemasService - - Tokens *TokensService - - Users *UsersService - - VerificationCodes *VerificationCodesService -} - -func (s *Service) userAgent() string { - if s.UserAgent == "" { - return googleapi.UserAgent - } - return googleapi.UserAgent + " " + s.UserAgent -} - -func NewAspsService(s *Service) *AspsService { - rs := &AspsService{s: s} - return rs -} - -type AspsService struct { - s *Service -} - -func NewChannelsService(s *Service) *ChannelsService { - rs := &ChannelsService{s: s} - return rs -} - -type ChannelsService struct { - s *Service -} - -func NewChromeosdevicesService(s *Service) *ChromeosdevicesService { - rs := &ChromeosdevicesService{s: s} - return rs -} - -type ChromeosdevicesService struct { - s *Service -} - -func NewCustomersService(s *Service) *CustomersService { - rs := &CustomersService{s: s} - return rs -} - -type CustomersService struct { - s *Service -} - -func NewDomainAliasesService(s *Service) *DomainAliasesService { - rs := &DomainAliasesService{s: s} - return rs -} - -type DomainAliasesService struct { - s *Service -} - -func NewDomainsService(s *Service) *DomainsService { - rs := &DomainsService{s: s} - return rs -} - -type DomainsService struct { - s *Service -} - -func NewGroupsService(s *Service) *GroupsService { - rs := &GroupsService{s: s} - rs.Aliases = NewGroupsAliasesService(s) - return rs -} - -type GroupsService struct { - s *Service - - Aliases *GroupsAliasesService -} - -func NewGroupsAliasesService(s *Service) *GroupsAliasesService { - rs := &GroupsAliasesService{s: s} - return rs -} - -type GroupsAliasesService struct { - s *Service -} - -func NewMembersService(s *Service) *MembersService { - rs := &MembersService{s: s} - return rs -} - -type MembersService struct { - s *Service -} - -func NewMobiledevicesService(s *Service) *MobiledevicesService { - rs := &MobiledevicesService{s: s} - return rs -} - -type MobiledevicesService struct { - s *Service -} - -func NewNotificationsService(s *Service) *NotificationsService { - rs := &NotificationsService{s: s} - return rs -} - -type NotificationsService struct { - s *Service -} - -func NewOrgunitsService(s *Service) *OrgunitsService { - rs := &OrgunitsService{s: s} - return rs -} - -type OrgunitsService struct { - s *Service -} - -func NewPrivilegesService(s *Service) *PrivilegesService { - rs := &PrivilegesService{s: s} - return rs -} - -type PrivilegesService struct { - s *Service -} - -func NewResourcesService(s *Service) *ResourcesService { - rs := &ResourcesService{s: s} - rs.Calendars = NewResourcesCalendarsService(s) - return rs -} - -type ResourcesService struct { - s *Service - - Calendars *ResourcesCalendarsService -} - -func NewResourcesCalendarsService(s *Service) *ResourcesCalendarsService { - rs := &ResourcesCalendarsService{s: s} - return rs -} - -type ResourcesCalendarsService struct { - s *Service -} - -func NewRoleAssignmentsService(s *Service) *RoleAssignmentsService { - rs := &RoleAssignmentsService{s: s} - return rs -} - -type RoleAssignmentsService struct { - s *Service -} - -func NewRolesService(s *Service) *RolesService { - rs := &RolesService{s: s} - return rs -} - -type RolesService struct { - s *Service -} - -func NewSchemasService(s *Service) *SchemasService { - rs := &SchemasService{s: s} - return rs -} - -type SchemasService struct { - s *Service -} - -func NewTokensService(s *Service) *TokensService { - rs := &TokensService{s: s} - return rs -} - -type TokensService struct { - s *Service -} - -func NewUsersService(s *Service) *UsersService { - rs := &UsersService{s: s} - rs.Aliases = NewUsersAliasesService(s) - rs.Photos = NewUsersPhotosService(s) - return rs -} - -type UsersService struct { - s *Service - - Aliases *UsersAliasesService - - Photos *UsersPhotosService -} - -func NewUsersAliasesService(s *Service) *UsersAliasesService { - rs := &UsersAliasesService{s: s} - return rs -} - -type UsersAliasesService struct { - s *Service -} - -func NewUsersPhotosService(s *Service) *UsersPhotosService { - rs := &UsersPhotosService{s: s} - return rs -} - -type UsersPhotosService struct { - s *Service -} - -func NewVerificationCodesService(s *Service) *VerificationCodesService { - rs := &VerificationCodesService{s: s} - return rs -} - -type VerificationCodesService struct { - s *Service -} - -// Alias: JSON template for Alias object in Directory API. -type Alias struct { - // Alias: A alias email - Alias string `json:"alias,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Id: Unique id of the group (Read-only) Unique id of the user - // (Read-only) - Id string `json:"id,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // PrimaryEmail: Group's primary email (Read-only) User's primary email - // (Read-only) - PrimaryEmail string `json:"primaryEmail,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Alias") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Alias) MarshalJSON() ([]byte, error) { - type noMethod Alias - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Aliases: JSON response template to list aliases in Directory API. -type Aliases struct { - // Aliases: List of alias objects. - Aliases []*Alias `json:"aliases,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Aliases") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Aliases) MarshalJSON() ([]byte, error) { - type noMethod Aliases - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Asp: The template that returns individual ASP (Access Code) data. -type Asp struct { - // CodeId: The unique ID of the ASP. - CodeId int64 `json:"codeId,omitempty"` - - // CreationTime: The time when the ASP was created. Expressed in Unix - // time format. - CreationTime int64 `json:"creationTime,omitempty,string"` - - // Etag: ETag of the ASP. - Etag string `json:"etag,omitempty"` - - // Kind: The type of the API resource. This is always - // admin#directory#asp. - Kind string `json:"kind,omitempty"` - - // LastTimeUsed: The time when the ASP was last used. Expressed in Unix - // time format. - LastTimeUsed int64 `json:"lastTimeUsed,omitempty,string"` - - // Name: The name of the application that the user, represented by their - // userId, entered when the ASP was created. - Name string `json:"name,omitempty"` - - // UserKey: The unique ID of the user who issued the ASP. - UserKey string `json:"userKey,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "CodeId") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Asp) MarshalJSON() ([]byte, error) { - type noMethod Asp - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -type Asps struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Items: A list of ASP resources. - Items []*Asp `json:"items,omitempty"` - - // Kind: The type of the API resource. This is always - // admin#directory#aspList. - Kind string `json:"kind,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Asps) MarshalJSON() ([]byte, error) { - type noMethod Asps - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// CalendarResource: JSON template for Calendar Resource object in -// Directory API. -type CalendarResource struct { - // Etags: ETag of the resource. - Etags string `json:"etags,omitempty"` - - // Kind: The type of the resource. For calendar resources, the value is - // admin#directory#resources#calendars#CalendarResource. - Kind string `json:"kind,omitempty"` - - // ResourceDescription: The brief description of the calendar resource. - ResourceDescription string `json:"resourceDescription,omitempty"` - - // ResourceEmail: The read-only email ID for the calendar resource. - // Generated as part of creating a new calendar resource. - ResourceEmail string `json:"resourceEmail,omitempty"` - - // ResourceId: The unique ID for the calendar resource. - ResourceId string `json:"resourceId,omitempty"` - - // ResourceName: The name of the calendar resource. For example, - // Training Room 1A - ResourceName string `json:"resourceName,omitempty"` - - // ResourceType: The type of the calendar resource. Used for grouping - // resources in the calendar user interface. - ResourceType string `json:"resourceType,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etags") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *CalendarResource) MarshalJSON() ([]byte, error) { - type noMethod CalendarResource - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// CalendarResources: JSON template for Calendar Resource List Response -// object in Directory API. -type CalendarResources struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Items: The CalendarResources in this page of results. - Items []*CalendarResource `json:"items,omitempty"` - - // Kind: Identifies this as a collection of CalendarResources. This is - // always admin#directory#resources#calendars#calendarResourcesList. - Kind string `json:"kind,omitempty"` - - // NextPageToken: The continuation token, used to page through large - // result sets. Provide this value in a subsequent request to return the - // next page of results. - NextPageToken string `json:"nextPageToken,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *CalendarResources) MarshalJSON() ([]byte, error) { - type noMethod CalendarResources - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Channel: An notification channel used to watch for resource changes. -type Channel struct { - // Address: The address where notifications are delivered for this - // channel. - Address string `json:"address,omitempty"` - - // Expiration: Date and time of notification channel expiration, - // expressed as a Unix timestamp, in milliseconds. Optional. - Expiration int64 `json:"expiration,omitempty,string"` - - // Id: A UUID or similar unique string that identifies this channel. - Id string `json:"id,omitempty"` - - // Kind: Identifies this as a notification channel used to watch for - // changes to a resource. Value: the fixed string "api#channel". - Kind string `json:"kind,omitempty"` - - // Params: Additional parameters controlling delivery channel behavior. - // Optional. - Params map[string]string `json:"params,omitempty"` - - // Payload: A Boolean value to indicate whether payload is wanted. - // Optional. - Payload bool `json:"payload,omitempty"` - - // ResourceId: An opaque ID that identifies the resource being watched - // on this channel. Stable across different API versions. - ResourceId string `json:"resourceId,omitempty"` - - // ResourceUri: A version-specific identifier for the watched resource. - ResourceUri string `json:"resourceUri,omitempty"` - - // Token: An arbitrary string delivered to the target address with each - // notification delivered over this channel. Optional. - Token string `json:"token,omitempty"` - - // Type: The type of delivery mechanism used for this channel. - Type string `json:"type,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Address") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Channel) MarshalJSON() ([]byte, error) { - type noMethod Channel - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// ChromeOsDevice: JSON template for Chrome Os Device resource in -// Directory API. -type ChromeOsDevice struct { - // ActiveTimeRanges: List of active time ranges (Read-only) - ActiveTimeRanges []*ChromeOsDeviceActiveTimeRanges `json:"activeTimeRanges,omitempty"` - - // AnnotatedAssetId: AssetId specified during enrollment or through - // later annotation - AnnotatedAssetId string `json:"annotatedAssetId,omitempty"` - - // AnnotatedLocation: Address or location of the device as noted by the - // administrator - AnnotatedLocation string `json:"annotatedLocation,omitempty"` - - // AnnotatedUser: User of the device - AnnotatedUser string `json:"annotatedUser,omitempty"` - - // BootMode: Chromebook boot mode (Read-only) - BootMode string `json:"bootMode,omitempty"` - - // DeviceId: Unique identifier of Chrome OS Device (Read-only) - DeviceId string `json:"deviceId,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // EthernetMacAddress: Chromebook Mac Address on ethernet network - // interface (Read-only) - EthernetMacAddress string `json:"ethernetMacAddress,omitempty"` - - // FirmwareVersion: Chromebook firmware version (Read-only) - FirmwareVersion string `json:"firmwareVersion,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // LastEnrollmentTime: Date and time the device was last enrolled - // (Read-only) - LastEnrollmentTime string `json:"lastEnrollmentTime,omitempty"` - - // LastSync: Date and time the device was last synchronized with the - // policy settings in the Google Apps administrator control panel - // (Read-only) - LastSync string `json:"lastSync,omitempty"` - - // MacAddress: Chromebook Mac Address on wifi network interface - // (Read-only) - MacAddress string `json:"macAddress,omitempty"` - - // Meid: Mobile Equipment identifier for the 3G mobile card in the - // Chromebook (Read-only) - Meid string `json:"meid,omitempty"` - - // Model: Chromebook Model (Read-only) - Model string `json:"model,omitempty"` - - // Notes: Notes added by the administrator - Notes string `json:"notes,omitempty"` - - // OrderNumber: Chromebook order number (Read-only) - OrderNumber string `json:"orderNumber,omitempty"` - - // OrgUnitPath: OrgUnit of the device - OrgUnitPath string `json:"orgUnitPath,omitempty"` - - // OsVersion: Chromebook Os Version (Read-only) - OsVersion string `json:"osVersion,omitempty"` - - // PlatformVersion: Chromebook platform version (Read-only) - PlatformVersion string `json:"platformVersion,omitempty"` - - // RecentUsers: List of recent device users, in descending order by last - // login time (Read-only) - RecentUsers []*ChromeOsDeviceRecentUsers `json:"recentUsers,omitempty"` - - // SerialNumber: Chromebook serial number (Read-only) - SerialNumber string `json:"serialNumber,omitempty"` - - // Status: status of the device (Read-only) - Status string `json:"status,omitempty"` - - // SupportEndDate: Final date the device will be supported (Read-only) - SupportEndDate string `json:"supportEndDate,omitempty"` - - // WillAutoRenew: Will Chromebook auto renew after support end date - // (Read-only) - WillAutoRenew bool `json:"willAutoRenew,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "ActiveTimeRanges") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *ChromeOsDevice) MarshalJSON() ([]byte, error) { - type noMethod ChromeOsDevice - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -type ChromeOsDeviceActiveTimeRanges struct { - // ActiveTime: Duration in milliseconds - ActiveTime int64 `json:"activeTime,omitempty"` - - // Date: Date of usage - Date string `json:"date,omitempty"` - - // ForceSendFields is a list of field names (e.g. "ActiveTime") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *ChromeOsDeviceActiveTimeRanges) MarshalJSON() ([]byte, error) { - type noMethod ChromeOsDeviceActiveTimeRanges - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -type ChromeOsDeviceRecentUsers struct { - // Email: Email address of the user. Present only if the user type is - // managed - Email string `json:"email,omitempty"` - - // Type: The type of the user - Type string `json:"type,omitempty"` - - // ForceSendFields is a list of field names (e.g. "Email") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *ChromeOsDeviceRecentUsers) MarshalJSON() ([]byte, error) { - type noMethod ChromeOsDeviceRecentUsers - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// ChromeOsDevices: JSON response template for List Chrome OS Devices -// operation in Directory API. -type ChromeOsDevices struct { - // Chromeosdevices: List of Chrome OS Device objects. - Chromeosdevices []*ChromeOsDevice `json:"chromeosdevices,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // NextPageToken: Token used to access next page of this result. - NextPageToken string `json:"nextPageToken,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Chromeosdevices") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *ChromeOsDevices) MarshalJSON() ([]byte, error) { - type noMethod ChromeOsDevices - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Customer: JSON template for Customer Resource object in Directory -// API. -type Customer struct { - // AlternateEmail: The customer's secondary contact email address. This - // email address cannot be on the same domain as the customerDomain - AlternateEmail string `json:"alternateEmail,omitempty"` - - // CustomerCreationTime: The customer's creation time (Readonly) - CustomerCreationTime string `json:"customerCreationTime,omitempty"` - - // CustomerDomain: The customer's primary domain name string. Do not - // include the www prefix when creating a new customer. - CustomerDomain string `json:"customerDomain,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Id: The unique ID for the customer's Google account. (Readonly) - Id string `json:"id,omitempty"` - - // Kind: Identifies the resource as a customer. Value: - // admin#directory#customer - Kind string `json:"kind,omitempty"` - - // Language: The customer's ISO 639-2 language code. The default value - // is en-US - Language string `json:"language,omitempty"` - - // PhoneNumber: The customer's contact phone number in E.164 format. - PhoneNumber string `json:"phoneNumber,omitempty"` - - // PostalAddress: The customer's postal address information. - PostalAddress *CustomerPostalAddress `json:"postalAddress,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "AlternateEmail") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Customer) MarshalJSON() ([]byte, error) { - type noMethod Customer - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// CustomerPostalAddress: JSON template for postal address of a -// customer. -type CustomerPostalAddress struct { - // AddressLine1: A customer's physical address. The address can be - // composed of one to three lines. - AddressLine1 string `json:"addressLine1,omitempty"` - - // AddressLine2: Address line 2 of the address. - AddressLine2 string `json:"addressLine2,omitempty"` - - // AddressLine3: Address line 3 of the address. - AddressLine3 string `json:"addressLine3,omitempty"` - - // ContactName: The customer contact's name. - ContactName string `json:"contactName,omitempty"` - - // CountryCode: This is a required property. For countryCode information - // see the ISO 3166 country code elements. - CountryCode string `json:"countryCode,omitempty"` - - // Locality: Name of the locality. An example of a locality value is the - // city of San Francisco. - Locality string `json:"locality,omitempty"` - - // OrganizationName: The company or company division name. - OrganizationName string `json:"organizationName,omitempty"` - - // PostalCode: The postal code. A postalCode example is a postal zip - // code such as 10009. This is in accordance with - - // http://portablecontacts.net/draft-spec.html#address_element. - PostalCode string `json:"postalCode,omitempty"` - - // Region: Name of the region. An example of a region value is NY for - // the state of New York. - Region string `json:"region,omitempty"` - - // ForceSendFields is a list of field names (e.g. "AddressLine1") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *CustomerPostalAddress) MarshalJSON() ([]byte, error) { - type noMethod CustomerPostalAddress - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// DomainAlias: JSON template for Domain Alias object in Directory API. -type DomainAlias struct { - // CreationTime: The creation time of the domain alias. (Read-only). - CreationTime int64 `json:"creationTime,omitempty,string"` - - // DomainAliasName: The domain alias name. - DomainAliasName string `json:"domainAliasName,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // ParentDomainName: The parent domain name that the domain alias is - // associated with. This can either be a primary or secondary domain - // name within a customer. - ParentDomainName string `json:"parentDomainName,omitempty"` - - // Verified: Indicates the verification state of a domain alias. - // (Read-only) - Verified bool `json:"verified,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "CreationTime") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *DomainAlias) MarshalJSON() ([]byte, error) { - type noMethod DomainAlias - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// DomainAliases: JSON response template to list domain aliases in -// Directory API. -type DomainAliases struct { - // DomainAliases: List of domain alias objects. - DomainAliases []*DomainAlias `json:"domainAliases,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "DomainAliases") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *DomainAliases) MarshalJSON() ([]byte, error) { - type noMethod DomainAliases - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Domains: JSON template for Domain object in Directory API. -type Domains struct { - // CreationTime: Creation time of the domain. (Read-only). - CreationTime int64 `json:"creationTime,omitempty,string"` - - // DomainAliases: List of domain alias objects. (Read-only) - DomainAliases []*DomainAlias `json:"domainAliases,omitempty"` - - // DomainName: The domain name of the customer. - DomainName string `json:"domainName,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // IsPrimary: Indicates if the domain is a primary domain (Read-only). - IsPrimary bool `json:"isPrimary,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // Verified: Indicates the verification state of a domain. (Read-only). - Verified bool `json:"verified,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "CreationTime") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Domains) MarshalJSON() ([]byte, error) { - type noMethod Domains - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Domains2: JSON response template to list Domains in Directory API. -type Domains2 struct { - // Domains: List of domain objects. - Domains []*Domains `json:"domains,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Domains") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Domains2) MarshalJSON() ([]byte, error) { - type noMethod Domains2 - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Group: JSON template for Group resource in Directory API. -type Group struct { - // AdminCreated: Is the group created by admin (Read-only) * - AdminCreated bool `json:"adminCreated,omitempty"` - - // Aliases: List of aliases (Read-only) - Aliases []string `json:"aliases,omitempty"` - - // Description: Description of the group - Description string `json:"description,omitempty"` - - // DirectMembersCount: Group direct members count - DirectMembersCount int64 `json:"directMembersCount,omitempty,string"` - - // Email: Email of Group - Email string `json:"email,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Id: Unique identifier of Group (Read-only) - Id string `json:"id,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // Name: Group name - Name string `json:"name,omitempty"` - - // NonEditableAliases: List of non editable aliases (Read-only) - NonEditableAliases []string `json:"nonEditableAliases,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "AdminCreated") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Group) MarshalJSON() ([]byte, error) { - type noMethod Group - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Groups: JSON response template for List Groups operation in Directory -// API. -type Groups struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Groups: List of group objects. - Groups []*Group `json:"groups,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // NextPageToken: Token used to access next page of this result. - NextPageToken string `json:"nextPageToken,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Groups) MarshalJSON() ([]byte, error) { - type noMethod Groups - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Member: JSON template for Member resource in Directory API. -type Member struct { - // Email: Email of member (Read-only) - Email string `json:"email,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Id: Unique identifier of customer member (Read-only) Unique - // identifier of group (Read-only) Unique identifier of member - // (Read-only) - Id string `json:"id,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // Role: Role of member - Role string `json:"role,omitempty"` - - // Type: Type of member (Immutable) - Type string `json:"type,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Email") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Member) MarshalJSON() ([]byte, error) { - type noMethod Member - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Members: JSON response template for List Members operation in -// Directory API. -type Members struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // Members: List of member objects. - Members []*Member `json:"members,omitempty"` - - // NextPageToken: Token used to access next page of this result. - NextPageToken string `json:"nextPageToken,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Members) MarshalJSON() ([]byte, error) { - type noMethod Members - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// MobileDevice: JSON template for Mobile Device resource in Directory -// API. -type MobileDevice struct { - // AdbStatus: Adb (USB debugging) enabled or disabled on device - // (Read-only) - AdbStatus bool `json:"adbStatus,omitempty"` - - // Applications: List of applications installed on Mobile Device - Applications []*MobileDeviceApplications `json:"applications,omitempty"` - - // BasebandVersion: Mobile Device Baseband version (Read-only) - BasebandVersion string `json:"basebandVersion,omitempty"` - - // BuildNumber: Mobile Device Build number (Read-only) - BuildNumber string `json:"buildNumber,omitempty"` - - // DefaultLanguage: The default locale used on the Mobile Device - // (Read-only) - DefaultLanguage string `json:"defaultLanguage,omitempty"` - - // DeveloperOptionsStatus: Developer options enabled or disabled on - // device (Read-only) - DeveloperOptionsStatus bool `json:"developerOptionsStatus,omitempty"` - - // DeviceCompromisedStatus: Mobile Device compromised status (Read-only) - DeviceCompromisedStatus string `json:"deviceCompromisedStatus,omitempty"` - - // DeviceId: Mobile Device serial number (Read-only) - DeviceId string `json:"deviceId,omitempty"` - - // Email: List of owner user's email addresses (Read-only) - Email []string `json:"email,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // FirstSync: Date and time the device was first synchronized with the - // policy settings in the Google Apps administrator control panel - // (Read-only) - FirstSync string `json:"firstSync,omitempty"` - - // HardwareId: Mobile Device Hardware Id (Read-only) - HardwareId string `json:"hardwareId,omitempty"` - - // Imei: Mobile Device IMEI number (Read-only) - Imei string `json:"imei,omitempty"` - - // KernelVersion: Mobile Device Kernel version (Read-only) - KernelVersion string `json:"kernelVersion,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // LastSync: Date and time the device was last synchronized with the - // policy settings in the Google Apps administrator control panel - // (Read-only) - LastSync string `json:"lastSync,omitempty"` - - // ManagedAccountIsOnOwnerProfile: Boolean indicating if this account is - // on owner/primary profile or not (Read-only) - ManagedAccountIsOnOwnerProfile bool `json:"managedAccountIsOnOwnerProfile,omitempty"` - - // Meid: Mobile Device MEID number (Read-only) - Meid string `json:"meid,omitempty"` - - // Model: Name of the model of the device - Model string `json:"model,omitempty"` - - // Name: List of owner user's names (Read-only) - Name []string `json:"name,omitempty"` - - // NetworkOperator: Mobile Device mobile or network operator (if - // available) (Read-only) - NetworkOperator string `json:"networkOperator,omitempty"` - - // Os: Name of the mobile operating system - Os string `json:"os,omitempty"` - - // OtherAccountsInfo: List of accounts added on device (Read-only) - OtherAccountsInfo []string `json:"otherAccountsInfo,omitempty"` - - // ResourceId: Unique identifier of Mobile Device (Read-only) - ResourceId string `json:"resourceId,omitempty"` - - // SerialNumber: Mobile Device SSN or Serial Number (Read-only) - SerialNumber string `json:"serialNumber,omitempty"` - - // Status: Status of the device (Read-only) - Status string `json:"status,omitempty"` - - // SupportsWorkProfile: Work profile supported on device (Read-only) - SupportsWorkProfile bool `json:"supportsWorkProfile,omitempty"` - - // Type: The type of device (Read-only) - Type string `json:"type,omitempty"` - - // UnknownSourcesStatus: Unknown sources enabled or disabled on device - // (Read-only) - UnknownSourcesStatus bool `json:"unknownSourcesStatus,omitempty"` - - // UserAgent: Mobile Device user agent - UserAgent string `json:"userAgent,omitempty"` - - // WifiMacAddress: Mobile Device WiFi MAC address (Read-only) - WifiMacAddress string `json:"wifiMacAddress,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "AdbStatus") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *MobileDevice) MarshalJSON() ([]byte, error) { - type noMethod MobileDevice - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -type MobileDeviceApplications struct { - // DisplayName: Display name of application - DisplayName string `json:"displayName,omitempty"` - - // PackageName: Package name of application - PackageName string `json:"packageName,omitempty"` - - // Permission: List of Permissions for application - Permission []string `json:"permission,omitempty"` - - // VersionCode: Version code of application - VersionCode int64 `json:"versionCode,omitempty"` - - // VersionName: Version name of application - VersionName string `json:"versionName,omitempty"` - - // ForceSendFields is a list of field names (e.g. "DisplayName") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *MobileDeviceApplications) MarshalJSON() ([]byte, error) { - type noMethod MobileDeviceApplications - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// MobileDeviceAction: JSON request template for firing commands on -// Mobile Device in Directory Devices API. -type MobileDeviceAction struct { - // Action: Action to be taken on the Mobile Device - Action string `json:"action,omitempty"` - - // ForceSendFields is a list of field names (e.g. "Action") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *MobileDeviceAction) MarshalJSON() ([]byte, error) { - type noMethod MobileDeviceAction - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// MobileDevices: JSON response template for List Mobile Devices -// operation in Directory API. -type MobileDevices struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // Mobiledevices: List of Mobile Device objects. - Mobiledevices []*MobileDevice `json:"mobiledevices,omitempty"` - - // NextPageToken: Token used to access next page of this result. - NextPageToken string `json:"nextPageToken,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *MobileDevices) MarshalJSON() ([]byte, error) { - type noMethod MobileDevices - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Notification: Template for a notification resource. -type Notification struct { - // Body: Body of the notification (Read-only) - Body string `json:"body,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // FromAddress: Address from which the notification is received - // (Read-only) - FromAddress string `json:"fromAddress,omitempty"` - - // IsUnread: Boolean indicating whether the notification is unread or - // not. - IsUnread bool `json:"isUnread,omitempty"` - - // Kind: The type of the resource. - Kind string `json:"kind,omitempty"` - - NotificationId string `json:"notificationId,omitempty"` - - // SendTime: Time at which notification was sent (Read-only) - SendTime string `json:"sendTime,omitempty"` - - // Subject: Subject of the notification (Read-only) - Subject string `json:"subject,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Body") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Notification) MarshalJSON() ([]byte, error) { - type noMethod Notification - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Notifications: Template for notifications list response. -type Notifications struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Items: List of notifications in this page. - Items []*Notification `json:"items,omitempty"` - - // Kind: The type of the resource. - Kind string `json:"kind,omitempty"` - - // NextPageToken: Token for fetching the next page of notifications. - NextPageToken string `json:"nextPageToken,omitempty"` - - // UnreadNotificationsCount: Number of unread notification for the - // domain. - UnreadNotificationsCount int64 `json:"unreadNotificationsCount,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Notifications) MarshalJSON() ([]byte, error) { - type noMethod Notifications - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// OrgUnit: JSON template for Org Unit resource in Directory API. -type OrgUnit struct { - // BlockInheritance: Should block inheritance - BlockInheritance bool `json:"blockInheritance,omitempty"` - - // Description: Description of OrgUnit - Description string `json:"description,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // Name: Name of OrgUnit - Name string `json:"name,omitempty"` - - // OrgUnitId: Id of OrgUnit - OrgUnitId string `json:"orgUnitId,omitempty"` - - // OrgUnitPath: Path of OrgUnit - OrgUnitPath string `json:"orgUnitPath,omitempty"` - - // ParentOrgUnitId: Id of parent OrgUnit - ParentOrgUnitId string `json:"parentOrgUnitId,omitempty"` - - // ParentOrgUnitPath: Path of parent OrgUnit - ParentOrgUnitPath string `json:"parentOrgUnitPath,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "BlockInheritance") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *OrgUnit) MarshalJSON() ([]byte, error) { - type noMethod OrgUnit - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// OrgUnits: JSON response template for List Organization Units -// operation in Directory API. -type OrgUnits struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // OrganizationUnits: List of user objects. - OrganizationUnits []*OrgUnit `json:"organizationUnits,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *OrgUnits) MarshalJSON() ([]byte, error) { - type noMethod OrgUnits - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Privilege: JSON template for privilege resource in Directory API. -type Privilege struct { - // ChildPrivileges: A list of child privileges. Privileges for a service - // form a tree. Each privilege can have a list of child privileges; this - // list is empty for a leaf privilege. - ChildPrivileges []*Privilege `json:"childPrivileges,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // IsOuScopable: If the privilege can be restricted to an organization - // unit. - IsOuScopable bool `json:"isOuScopable,omitempty"` - - // Kind: The type of the API resource. This is always - // admin#directory#privilege. - Kind string `json:"kind,omitempty"` - - // PrivilegeName: The name of the privilege. - PrivilegeName string `json:"privilegeName,omitempty"` - - // ServiceId: The obfuscated ID of the service this privilege is for. - ServiceId string `json:"serviceId,omitempty"` - - // ServiceName: The name of the service this privilege is for. - ServiceName string `json:"serviceName,omitempty"` - - // ForceSendFields is a list of field names (e.g. "ChildPrivileges") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Privilege) MarshalJSON() ([]byte, error) { - type noMethod Privilege - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Privileges: JSON response template for List privileges operation in -// Directory API. -type Privileges struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Items: A list of Privilege resources. - Items []*Privilege `json:"items,omitempty"` - - // Kind: The type of the API resource. This is always - // admin#directory#privileges. - Kind string `json:"kind,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Privileges) MarshalJSON() ([]byte, error) { - type noMethod Privileges - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Role: JSON template for role resource in Directory API. -type Role struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // IsSuperAdminRole: Returns true if the role is a super admin role. - IsSuperAdminRole bool `json:"isSuperAdminRole,omitempty"` - - // IsSystemRole: Returns true if this is a pre-defined system role. - IsSystemRole bool `json:"isSystemRole,omitempty"` - - // Kind: The type of the API resource. This is always - // admin#directory#role. - Kind string `json:"kind,omitempty"` - - // RoleDescription: A short description of the role. - RoleDescription string `json:"roleDescription,omitempty"` - - // RoleId: ID of the role. - RoleId int64 `json:"roleId,omitempty,string"` - - // RoleName: Name of the role. - RoleName string `json:"roleName,omitempty"` - - // RolePrivileges: The set of privileges that are granted to this role. - RolePrivileges []*RoleRolePrivileges `json:"rolePrivileges,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Role) MarshalJSON() ([]byte, error) { - type noMethod Role - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -type RoleRolePrivileges struct { - // PrivilegeName: The name of the privilege. - PrivilegeName string `json:"privilegeName,omitempty"` - - // ServiceId: The obfuscated ID of the service this privilege is for. - ServiceId string `json:"serviceId,omitempty"` - - // ForceSendFields is a list of field names (e.g. "PrivilegeName") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *RoleRolePrivileges) MarshalJSON() ([]byte, error) { - type noMethod RoleRolePrivileges - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// RoleAssignment: JSON template for roleAssignment resource in -// Directory API. -type RoleAssignment struct { - // AssignedTo: The unique ID of the user this role is assigned to. - AssignedTo string `json:"assignedTo,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: The type of the API resource. This is always - // admin#directory#roleAssignment. - Kind string `json:"kind,omitempty"` - - // OrgUnitId: If the role is restricted to an organization unit, this - // contains the ID for the organization unit the exercise of this role - // is restricted to. - OrgUnitId string `json:"orgUnitId,omitempty"` - - // RoleAssignmentId: ID of this roleAssignment. - RoleAssignmentId int64 `json:"roleAssignmentId,omitempty,string"` - - // RoleId: The ID of the role that is assigned. - RoleId int64 `json:"roleId,omitempty,string"` - - // ScopeType: The scope in which this role is assigned. Possible values - // are: - // - CUSTOMER - // - ORG_UNIT - ScopeType string `json:"scopeType,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "AssignedTo") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *RoleAssignment) MarshalJSON() ([]byte, error) { - type noMethod RoleAssignment - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// RoleAssignments: JSON response template for List roleAssignments -// operation in Directory API. -type RoleAssignments struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Items: A list of RoleAssignment resources. - Items []*RoleAssignment `json:"items,omitempty"` - - // Kind: The type of the API resource. This is always - // admin#directory#roleAssignments. - Kind string `json:"kind,omitempty"` - - NextPageToken string `json:"nextPageToken,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *RoleAssignments) MarshalJSON() ([]byte, error) { - type noMethod RoleAssignments - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Roles: JSON response template for List roles operation in Directory -// API. -type Roles struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Items: A list of Role resources. - Items []*Role `json:"items,omitempty"` - - // Kind: The type of the API resource. This is always - // admin#directory#roles. - Kind string `json:"kind,omitempty"` - - NextPageToken string `json:"nextPageToken,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Roles) MarshalJSON() ([]byte, error) { - type noMethod Roles - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Schema: JSON template for Schema resource in Directory API. -type Schema struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Fields: Fields of Schema - Fields []*SchemaFieldSpec `json:"fields,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // SchemaId: Unique identifier of Schema (Read-only) - SchemaId string `json:"schemaId,omitempty"` - - // SchemaName: Schema name - SchemaName string `json:"schemaName,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Schema) MarshalJSON() ([]byte, error) { - type noMethod Schema - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// SchemaFieldSpec: JSON template for FieldSpec resource for Schemas in -// Directory API. -type SchemaFieldSpec struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // FieldId: Unique identifier of Field (Read-only) - FieldId string `json:"fieldId,omitempty"` - - // FieldName: Name of the field. - FieldName string `json:"fieldName,omitempty"` - - // FieldType: Type of the field. - FieldType string `json:"fieldType,omitempty"` - - // Indexed: Boolean specifying whether the field is indexed or not. - // - // Default: true - Indexed *bool `json:"indexed,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // MultiValued: Boolean specifying whether this is a multi-valued field - // or not. - MultiValued bool `json:"multiValued,omitempty"` - - // NumericIndexingSpec: Indexing spec for a numeric field. By default, - // only exact match queries will be supported for numeric fields. - // Setting the numericIndexingSpec allows range queries to be supported. - NumericIndexingSpec *SchemaFieldSpecNumericIndexingSpec `json:"numericIndexingSpec,omitempty"` - - // ReadAccessType: Read ACLs on the field specifying who can view values - // of this field. Valid values are "ALL_DOMAIN_USERS" and - // "ADMINS_AND_SELF". - ReadAccessType string `json:"readAccessType,omitempty"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *SchemaFieldSpec) MarshalJSON() ([]byte, error) { - type noMethod SchemaFieldSpec - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// SchemaFieldSpecNumericIndexingSpec: Indexing spec for a numeric -// field. By default, only exact match queries will be supported for -// numeric fields. Setting the numericIndexingSpec allows range queries -// to be supported. -type SchemaFieldSpecNumericIndexingSpec struct { - // MaxValue: Maximum value of this field. This is meant to be indicative - // rather than enforced. Values outside this range will still be - // indexed, but search may not be as performant. - MaxValue float64 `json:"maxValue,omitempty"` - - // MinValue: Minimum value of this field. This is meant to be indicative - // rather than enforced. Values outside this range will still be - // indexed, but search may not be as performant. - MinValue float64 `json:"minValue,omitempty"` - - // ForceSendFields is a list of field names (e.g. "MaxValue") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *SchemaFieldSpecNumericIndexingSpec) MarshalJSON() ([]byte, error) { - type noMethod SchemaFieldSpecNumericIndexingSpec - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Schemas: JSON response template for List Schema operation in -// Directory API. -type Schemas struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // Schemas: List of UserSchema objects. - Schemas []*Schema `json:"schemas,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Schemas) MarshalJSON() ([]byte, error) { - type noMethod Schemas - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Token: JSON template for token resource in Directory API. -type Token struct { - // Anonymous: Whether the application is registered with Google. The - // value is true if the application has an anonymous Client ID. - Anonymous bool `json:"anonymous,omitempty"` - - // ClientId: The Client ID of the application the token is issued to. - ClientId string `json:"clientId,omitempty"` - - // DisplayText: The displayable name of the application the token is - // issued to. - DisplayText string `json:"displayText,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: The type of the API resource. This is always - // admin#directory#token. - Kind string `json:"kind,omitempty"` - - // NativeApp: Whether the token is issued to an installed application. - // The value is true if the application is installed to a desktop or - // mobile device. - NativeApp bool `json:"nativeApp,omitempty"` - - // Scopes: A list of authorization scopes the application is granted. - Scopes []string `json:"scopes,omitempty"` - - // UserKey: The unique ID of the user that issued the token. - UserKey string `json:"userKey,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Anonymous") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Token) MarshalJSON() ([]byte, error) { - type noMethod Token - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Tokens: JSON response template for List tokens operation in Directory -// API. -type Tokens struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Items: A list of Token resources. - Items []*Token `json:"items,omitempty"` - - // Kind: The type of the API resource. This is always - // admin#directory#tokenList. - Kind string `json:"kind,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Tokens) MarshalJSON() ([]byte, error) { - type noMethod Tokens - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// User: JSON template for User object in Directory API. -type User struct { - Addresses interface{} `json:"addresses,omitempty"` - - // AgreedToTerms: Indicates if user has agreed to terms (Read-only) - AgreedToTerms bool `json:"agreedToTerms,omitempty"` - - // Aliases: List of aliases (Read-only) - Aliases []string `json:"aliases,omitempty"` - - // ChangePasswordAtNextLogin: Boolean indicating if the user should - // change password in next login - ChangePasswordAtNextLogin bool `json:"changePasswordAtNextLogin,omitempty"` - - // CreationTime: User's Google account creation time. (Read-only) - CreationTime string `json:"creationTime,omitempty"` - - // CustomSchemas: Custom fields of the user. - CustomSchemas map[string]UserCustomProperties `json:"customSchemas,omitempty"` - - // CustomerId: CustomerId of User (Read-only) - CustomerId string `json:"customerId,omitempty"` - - DeletionTime string `json:"deletionTime,omitempty"` - - Emails interface{} `json:"emails,omitempty"` - - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - ExternalIds interface{} `json:"externalIds,omitempty"` - - // HashFunction: Hash function name for password. Supported are MD5, - // SHA-1 and crypt - HashFunction string `json:"hashFunction,omitempty"` - - // Id: Unique identifier of User (Read-only) - Id string `json:"id,omitempty"` - - Ims interface{} `json:"ims,omitempty"` - - // IncludeInGlobalAddressList: Boolean indicating if user is included in - // Global Address List - IncludeInGlobalAddressList bool `json:"includeInGlobalAddressList,omitempty"` - - // IpWhitelisted: Boolean indicating if ip is whitelisted - IpWhitelisted bool `json:"ipWhitelisted,omitempty"` - - // IsAdmin: Boolean indicating if the user is admin (Read-only) - IsAdmin bool `json:"isAdmin,omitempty"` - - // IsDelegatedAdmin: Boolean indicating if the user is delegated admin - // (Read-only) - IsDelegatedAdmin bool `json:"isDelegatedAdmin,omitempty"` - - // IsMailboxSetup: Is mailbox setup (Read-only) - IsMailboxSetup bool `json:"isMailboxSetup,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // LastLoginTime: User's last login time. (Read-only) - LastLoginTime string `json:"lastLoginTime,omitempty"` - - // Name: User's name - Name *UserName `json:"name,omitempty"` - - // NonEditableAliases: List of non editable aliases (Read-only) - NonEditableAliases []string `json:"nonEditableAliases,omitempty"` - - Notes interface{} `json:"notes,omitempty"` - - // OrgUnitPath: OrgUnit of User - OrgUnitPath string `json:"orgUnitPath,omitempty"` - - Organizations interface{} `json:"organizations,omitempty"` - - // Password: User's password - Password string `json:"password,omitempty"` - - Phones interface{} `json:"phones,omitempty"` - - // PrimaryEmail: username of User - PrimaryEmail string `json:"primaryEmail,omitempty"` - - Relations interface{} `json:"relations,omitempty"` - - // Suspended: Indicates if user is suspended - Suspended bool `json:"suspended,omitempty"` - - // SuspensionReason: Suspension reason if user is suspended (Read-only) - SuspensionReason string `json:"suspensionReason,omitempty"` - - // ThumbnailPhotoEtag: ETag of the user's photo (Read-only) - ThumbnailPhotoEtag string `json:"thumbnailPhotoEtag,omitempty"` - - // ThumbnailPhotoUrl: Photo Url of the user (Read-only) - ThumbnailPhotoUrl string `json:"thumbnailPhotoUrl,omitempty"` - - Websites interface{} `json:"websites,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Addresses") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *User) MarshalJSON() ([]byte, error) { - type noMethod User - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// UserAbout: JSON template for About (notes) of a user in Directory -// API. -type UserAbout struct { - // ContentType: About entry can have a type which indicates the content - // type. It can either be plain or html. By default, notes contents are - // assumed to contain plain text. - ContentType string `json:"contentType,omitempty"` - - // Value: Actual value of notes. - Value string `json:"value,omitempty"` - - // ForceSendFields is a list of field names (e.g. "ContentType") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *UserAbout) MarshalJSON() ([]byte, error) { - type noMethod UserAbout - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// UserAddress: JSON template for address. -type UserAddress struct { - // Country: Country. - Country string `json:"country,omitempty"` - - // CountryCode: Country code. - CountryCode string `json:"countryCode,omitempty"` - - // CustomType: Custom type. - CustomType string `json:"customType,omitempty"` - - // ExtendedAddress: Extended Address. - ExtendedAddress string `json:"extendedAddress,omitempty"` - - // Formatted: Formatted address. - Formatted string `json:"formatted,omitempty"` - - // Locality: Locality. - Locality string `json:"locality,omitempty"` - - // PoBox: Other parts of address. - PoBox string `json:"poBox,omitempty"` - - // PostalCode: Postal code. - PostalCode string `json:"postalCode,omitempty"` - - // Primary: If this is user's primary address. Only one entry could be - // marked as primary. - Primary bool `json:"primary,omitempty"` - - // Region: Region. - Region string `json:"region,omitempty"` - - // SourceIsStructured: User supplied address was structured. Structured - // addresses are NOT supported at this time. You might be able to write - // structured addresses, but any values will eventually be clobbered. - SourceIsStructured bool `json:"sourceIsStructured,omitempty"` - - // StreetAddress: Street. - StreetAddress string `json:"streetAddress,omitempty"` - - // Type: Each entry can have a type which indicates standard values of - // that entry. For example address could be of home, work etc. In - // addition to the standard type, an entry can have a custom type and - // can take any value. Such type should have the CUSTOM value as type - // and also have a customType value. - Type string `json:"type,omitempty"` - - // ForceSendFields is a list of field names (e.g. "Country") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *UserAddress) MarshalJSON() ([]byte, error) { - type noMethod UserAddress - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -type UserCustomProperties interface{} - -// UserEmail: JSON template for an email. -type UserEmail struct { - // Address: Email id of the user. - Address string `json:"address,omitempty"` - - // CustomType: Custom Type. - CustomType string `json:"customType,omitempty"` - - // Primary: If this is user's primary email. Only one entry could be - // marked as primary. - Primary bool `json:"primary,omitempty"` - - // Type: Each entry can have a type which indicates standard types of - // that entry. For example email could be of home, work etc. In addition - // to the standard type, an entry can have a custom type and can take - // any value Such types should have the CUSTOM value as type and also - // have a customType value. - Type string `json:"type,omitempty"` - - // ForceSendFields is a list of field names (e.g. "Address") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *UserEmail) MarshalJSON() ([]byte, error) { - type noMethod UserEmail - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// UserExternalId: JSON template for an externalId entry. -type UserExternalId struct { - // CustomType: Custom type. - CustomType string `json:"customType,omitempty"` - - // Type: The type of the Id. - Type string `json:"type,omitempty"` - - // Value: The value of the id. - Value string `json:"value,omitempty"` - - // ForceSendFields is a list of field names (e.g. "CustomType") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *UserExternalId) MarshalJSON() ([]byte, error) { - type noMethod UserExternalId - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// UserIm: JSON template for instant messenger of an user. -type UserIm struct { - // CustomProtocol: Custom protocol. - CustomProtocol string `json:"customProtocol,omitempty"` - - // CustomType: Custom type. - CustomType string `json:"customType,omitempty"` - - // Im: Instant messenger id. - Im string `json:"im,omitempty"` - - // Primary: If this is user's primary im. Only one entry could be marked - // as primary. - Primary bool `json:"primary,omitempty"` - - // Protocol: Protocol used in the instant messenger. It should be one of - // the values from ImProtocolTypes map. Similar to type, it can take a - // CUSTOM value and specify the custom name in customProtocol field. - Protocol string `json:"protocol,omitempty"` - - // Type: Each entry can have a type which indicates standard types of - // that entry. For example instant messengers could be of home, work - // etc. In addition to the standard type, an entry can have a custom - // type and can take any value. Such types should have the CUSTOM value - // as type and also have a customType value. - Type string `json:"type,omitempty"` - - // ForceSendFields is a list of field names (e.g. "CustomProtocol") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *UserIm) MarshalJSON() ([]byte, error) { - type noMethod UserIm - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// UserMakeAdmin: JSON request template for setting/revoking admin -// status of a user in Directory API. -type UserMakeAdmin struct { - // Status: Boolean indicating new admin status of the user - Status bool `json:"status,omitempty"` - - // ForceSendFields is a list of field names (e.g. "Status") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *UserMakeAdmin) MarshalJSON() ([]byte, error) { - type noMethod UserMakeAdmin - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// UserName: JSON template for name of a user in Directory API. -type UserName struct { - // FamilyName: Last Name - FamilyName string `json:"familyName,omitempty"` - - // FullName: Full Name - FullName string `json:"fullName,omitempty"` - - // GivenName: First Name - GivenName string `json:"givenName,omitempty"` - - // ForceSendFields is a list of field names (e.g. "FamilyName") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *UserName) MarshalJSON() ([]byte, error) { - type noMethod UserName - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// UserOrganization: JSON template for an organization entry. -type UserOrganization struct { - // CostCenter: The cost center of the users department. - CostCenter string `json:"costCenter,omitempty"` - - // CustomType: Custom type. - CustomType string `json:"customType,omitempty"` - - // Department: Department within the organization. - Department string `json:"department,omitempty"` - - // Description: Description of the organization. - Description string `json:"description,omitempty"` - - // Domain: The domain to which the organization belongs to. - Domain string `json:"domain,omitempty"` - - // Location: Location of the organization. This need not be fully - // qualified address. - Location string `json:"location,omitempty"` - - // Name: Name of the organization - Name string `json:"name,omitempty"` - - // Primary: If it user's primary organization. - Primary bool `json:"primary,omitempty"` - - // Symbol: Symbol of the organization. - Symbol string `json:"symbol,omitempty"` - - // Title: Title (designation) of the user in the organization. - Title string `json:"title,omitempty"` - - // Type: Each entry can have a type which indicates standard types of - // that entry. For example organization could be of school, work etc. In - // addition to the standard type, an entry can have a custom type and - // can give it any name. Such types should have the CUSTOM value as type - // and also have a CustomType value. - Type string `json:"type,omitempty"` - - // ForceSendFields is a list of field names (e.g. "CostCenter") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *UserOrganization) MarshalJSON() ([]byte, error) { - type noMethod UserOrganization - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// UserPhone: JSON template for a phone entry. -type UserPhone struct { - // CustomType: Custom Type. - CustomType string `json:"customType,omitempty"` - - // Primary: If this is user's primary phone or not. - Primary bool `json:"primary,omitempty"` - - // Type: Each entry can have a type which indicates standard types of - // that entry. For example phone could be of home_fax, work, mobile etc. - // In addition to the standard type, an entry can have a custom type and - // can give it any name. Such types should have the CUSTOM value as type - // and also have a customType value. - Type string `json:"type,omitempty"` - - // Value: Phone number. - Value string `json:"value,omitempty"` - - // ForceSendFields is a list of field names (e.g. "CustomType") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *UserPhone) MarshalJSON() ([]byte, error) { - type noMethod UserPhone - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// UserPhoto: JSON template for Photo object in Directory API. -type UserPhoto struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Height: Height in pixels of the photo - Height int64 `json:"height,omitempty"` - - // Id: Unique identifier of User (Read-only) - Id string `json:"id,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // MimeType: Mime Type of the photo - MimeType string `json:"mimeType,omitempty"` - - // PhotoData: Base64 encoded photo data - PhotoData string `json:"photoData,omitempty"` - - // PrimaryEmail: Primary email of User (Read-only) - PrimaryEmail string `json:"primaryEmail,omitempty"` - - // Width: Width in pixels of the photo - Width int64 `json:"width,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *UserPhoto) MarshalJSON() ([]byte, error) { - type noMethod UserPhoto - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// UserRelation: JSON template for a relation entry. -type UserRelation struct { - // CustomType: Custom Type. - CustomType string `json:"customType,omitempty"` - - // Type: The relation of the user. Some of the possible values are - // mother, father, sister, brother, manager, assistant, partner. - Type string `json:"type,omitempty"` - - // Value: The name of the relation. - Value string `json:"value,omitempty"` - - // ForceSendFields is a list of field names (e.g. "CustomType") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *UserRelation) MarshalJSON() ([]byte, error) { - type noMethod UserRelation - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// UserUndelete: JSON request template to undelete a user in Directory -// API. -type UserUndelete struct { - // OrgUnitPath: OrgUnit of User - OrgUnitPath string `json:"orgUnitPath,omitempty"` - - // ForceSendFields is a list of field names (e.g. "OrgUnitPath") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *UserUndelete) MarshalJSON() ([]byte, error) { - type noMethod UserUndelete - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// UserWebsite: JSON template for a website entry. -type UserWebsite struct { - // CustomType: Custom Type. - CustomType string `json:"customType,omitempty"` - - // Primary: If this is user's primary website or not. - Primary bool `json:"primary,omitempty"` - - // Type: Each entry can have a type which indicates standard types of - // that entry. For example website could be of home, work, blog etc. In - // addition to the standard type, an entry can have a custom type and - // can give it any name. Such types should have the CUSTOM value as type - // and also have a customType value. - Type string `json:"type,omitempty"` - - // Value: Website. - Value string `json:"value,omitempty"` - - // ForceSendFields is a list of field names (e.g. "CustomType") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *UserWebsite) MarshalJSON() ([]byte, error) { - type noMethod UserWebsite - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// Users: JSON response template for List Users operation in Apps -// Directory API. -type Users struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: Kind of resource this is. - Kind string `json:"kind,omitempty"` - - // NextPageToken: Token used to access next page of this result. - NextPageToken string `json:"nextPageToken,omitempty"` - - // TriggerEvent: Event that triggered this response (only used in case - // of Push Response) - TriggerEvent string `json:"trigger_event,omitempty"` - - // Users: List of user objects. - Users []*User `json:"users,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *Users) MarshalJSON() ([]byte, error) { - type noMethod Users - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// VerificationCode: JSON template for verification codes in Directory -// API. -type VerificationCode struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Kind: The type of the resource. This is always - // admin#directory#verificationCode. - Kind string `json:"kind,omitempty"` - - // UserId: The obfuscated unique ID of the user. - UserId string `json:"userId,omitempty"` - - // VerificationCode: A current verification code for the user. - // Invalidated or used verification codes are not returned as part of - // the result. - VerificationCode string `json:"verificationCode,omitempty"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *VerificationCode) MarshalJSON() ([]byte, error) { - type noMethod VerificationCode - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// VerificationCodes: JSON response template for List verification codes -// operation in Directory API. -type VerificationCodes struct { - // Etag: ETag of the resource. - Etag string `json:"etag,omitempty"` - - // Items: A list of verification code resources. - Items []*VerificationCode `json:"items,omitempty"` - - // Kind: The type of the resource. This is always - // admin#directory#verificationCodesList. - Kind string `json:"kind,omitempty"` - - // ServerResponse contains the HTTP response code and headers from the - // server. - googleapi.ServerResponse `json:"-"` - - // ForceSendFields is a list of field names (e.g. "Etag") to - // unconditionally include in API requests. By default, fields with - // empty values are omitted from API requests. However, any non-pointer, - // non-interface field appearing in ForceSendFields will be sent to the - // server regardless of whether the field is empty or not. This may be - // used to include empty fields in Patch requests. - ForceSendFields []string `json:"-"` -} - -func (s *VerificationCodes) MarshalJSON() ([]byte, error) { - type noMethod VerificationCodes - raw := noMethod(*s) - return gensupport.MarshalJSON(raw, s.ForceSendFields) -} - -// method id "directory.asps.delete": - -type AspsDeleteCall struct { - s *Service - userKey string - codeId int64 - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Delete an ASP issued by a user. -func (r *AspsService) Delete(userKey string, codeId int64) *AspsDeleteCall { - c := &AspsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - c.codeId = codeId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *AspsDeleteCall) Fields(s ...googleapi.Field) *AspsDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *AspsDeleteCall) Context(ctx context.Context) *AspsDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *AspsDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/asps/{codeId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - "codeId": strconv.FormatInt(c.codeId, 10), - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.asps.delete" call. -func (c *AspsDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Delete an ASP issued by a user.", - // "httpMethod": "DELETE", - // "id": "directory.asps.delete", - // "parameterOrder": [ - // "userKey", - // "codeId" - // ], - // "parameters": { - // "codeId": { - // "description": "The unique ID of the ASP to be deleted.", - // "format": "int32", - // "location": "path", - // "required": true, - // "type": "integer" - // }, - // "userKey": { - // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/asps/{codeId}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user.security" - // ] - // } - -} - -// method id "directory.asps.get": - -type AspsGetCall struct { - s *Service - userKey string - codeId int64 - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Get information about an ASP issued by a user. -func (r *AspsService) Get(userKey string, codeId int64) *AspsGetCall { - c := &AspsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - c.codeId = codeId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *AspsGetCall) Fields(s ...googleapi.Field) *AspsGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *AspsGetCall) IfNoneMatch(entityTag string) *AspsGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *AspsGetCall) Context(ctx context.Context) *AspsGetCall { - c.ctx_ = ctx - return c -} - -func (c *AspsGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/asps/{codeId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - "codeId": strconv.FormatInt(c.codeId, 10), - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.asps.get" call. -// Exactly one of *Asp or error will be non-nil. Any non-2xx status code -// is an error. Response headers are in either -// *Asp.ServerResponse.Header or (if a response was returned at all) in -// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check -// whether the returned error was because http.StatusNotModified was -// returned. -func (c *AspsGetCall) Do(opts ...googleapi.CallOption) (*Asp, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Asp{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Get information about an ASP issued by a user.", - // "httpMethod": "GET", - // "id": "directory.asps.get", - // "parameterOrder": [ - // "userKey", - // "codeId" - // ], - // "parameters": { - // "codeId": { - // "description": "The unique ID of the ASP.", - // "format": "int32", - // "location": "path", - // "required": true, - // "type": "integer" - // }, - // "userKey": { - // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/asps/{codeId}", - // "response": { - // "$ref": "Asp" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user.security" - // ] - // } - -} - -// method id "directory.asps.list": - -type AspsListCall struct { - s *Service - userKey string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: List the ASPs issued by a user. -func (r *AspsService) List(userKey string) *AspsListCall { - c := &AspsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *AspsListCall) Fields(s ...googleapi.Field) *AspsListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *AspsListCall) IfNoneMatch(entityTag string) *AspsListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *AspsListCall) Context(ctx context.Context) *AspsListCall { - c.ctx_ = ctx - return c -} - -func (c *AspsListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/asps") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.asps.list" call. -// Exactly one of *Asps or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Asps.ServerResponse.Header or (if a response was returned at all) in -// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check -// whether the returned error was because http.StatusNotModified was -// returned. -func (c *AspsListCall) Do(opts ...googleapi.CallOption) (*Asps, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Asps{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "List the ASPs issued by a user.", - // "httpMethod": "GET", - // "id": "directory.asps.list", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/asps", - // "response": { - // "$ref": "Asps" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user.security" - // ] - // } - -} - -// method id "admin.channels.stop": - -type ChannelsStopCall struct { - s *Service - channel *Channel - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Stop: Stop watching resources through this channel -func (r *ChannelsService) Stop(channel *Channel) *ChannelsStopCall { - c := &ChannelsStopCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.channel = channel - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *ChannelsStopCall) Fields(s ...googleapi.Field) *ChannelsStopCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *ChannelsStopCall) Context(ctx context.Context) *ChannelsStopCall { - c.ctx_ = ctx - return c -} - -func (c *ChannelsStopCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.channel) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "/admin/directory_v1/channels/stop") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.SetOpaque(req.URL) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "admin.channels.stop" call. -func (c *ChannelsStopCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Stop watching resources through this channel", - // "httpMethod": "POST", - // "id": "admin.channels.stop", - // "path": "/admin/directory_v1/channels/stop", - // "request": { - // "$ref": "Channel", - // "parameterName": "resource" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user", - // "https://www.googleapis.com/auth/admin.directory.user.alias", - // "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", - // "https://www.googleapis.com/auth/admin.directory.user.readonly" - // ] - // } - -} - -// method id "directory.chromeosdevices.get": - -type ChromeosdevicesGetCall struct { - s *Service - customerId string - deviceId string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrieve Chrome OS Device -func (r *ChromeosdevicesService) Get(customerId string, deviceId string) *ChromeosdevicesGetCall { - c := &ChromeosdevicesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.deviceId = deviceId - return c -} - -// Projection sets the optional parameter "projection": Restrict -// information returned to a set of selected fields. -// -// Possible values: -// "BASIC" - Includes only the basic metadata fields (e.g., deviceId, -// serialNumber, status, and user) -// "FULL" - Includes all metadata fields -func (c *ChromeosdevicesGetCall) Projection(projection string) *ChromeosdevicesGetCall { - c.urlParams_.Set("projection", projection) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *ChromeosdevicesGetCall) Fields(s ...googleapi.Field) *ChromeosdevicesGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *ChromeosdevicesGetCall) IfNoneMatch(entityTag string) *ChromeosdevicesGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *ChromeosdevicesGetCall) Context(ctx context.Context) *ChromeosdevicesGetCall { - c.ctx_ = ctx - return c -} - -func (c *ChromeosdevicesGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/chromeos/{deviceId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "deviceId": c.deviceId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.chromeosdevices.get" call. -// Exactly one of *ChromeOsDevice or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *ChromeOsDevice.ServerResponse.Header or (if a response was returned -// at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *ChromeosdevicesGetCall) Do(opts ...googleapi.CallOption) (*ChromeOsDevice, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &ChromeOsDevice{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve Chrome OS Device", - // "httpMethod": "GET", - // "id": "directory.chromeosdevices.get", - // "parameterOrder": [ - // "customerId", - // "deviceId" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "deviceId": { - // "description": "Immutable id of Chrome OS Device", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "projection": { - // "description": "Restrict information returned to a set of selected fields.", - // "enum": [ - // "BASIC", - // "FULL" - // ], - // "enumDescriptions": [ - // "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", - // "Includes all metadata fields" - // ], - // "location": "query", - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/devices/chromeos/{deviceId}", - // "response": { - // "$ref": "ChromeOsDevice" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.device.chromeos", - // "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly" - // ] - // } - -} - -// method id "directory.chromeosdevices.list": - -type ChromeosdevicesListCall struct { - s *Service - customerId string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Retrieve all Chrome OS Devices of a customer (paginated) -func (r *ChromeosdevicesService) List(customerId string) *ChromeosdevicesListCall { - c := &ChromeosdevicesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - return c -} - -// MaxResults sets the optional parameter "maxResults": Maximum number -// of results to return. Default is 100 -func (c *ChromeosdevicesListCall) MaxResults(maxResults int64) *ChromeosdevicesListCall { - c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) - return c -} - -// OrderBy sets the optional parameter "orderBy": Column to use for -// sorting results -// -// Possible values: -// "annotatedLocation" - Chromebook location as annotated by the -// administrator. -// "annotatedUser" - Chromebook user as annotated by administrator. -// "lastSync" - Chromebook last sync. -// "notes" - Chromebook notes as annotated by the administrator. -// "serialNumber" - Chromebook Serial Number. -// "status" - Chromebook status. -// "supportEndDate" - Chromebook support end date. -func (c *ChromeosdevicesListCall) OrderBy(orderBy string) *ChromeosdevicesListCall { - c.urlParams_.Set("orderBy", orderBy) - return c -} - -// PageToken sets the optional parameter "pageToken": Token to specify -// next page in the list -func (c *ChromeosdevicesListCall) PageToken(pageToken string) *ChromeosdevicesListCall { - c.urlParams_.Set("pageToken", pageToken) - return c -} - -// Projection sets the optional parameter "projection": Restrict -// information returned to a set of selected fields. -// -// Possible values: -// "BASIC" - Includes only the basic metadata fields (e.g., deviceId, -// serialNumber, status, and user) -// "FULL" - Includes all metadata fields -func (c *ChromeosdevicesListCall) Projection(projection string) *ChromeosdevicesListCall { - c.urlParams_.Set("projection", projection) - return c -} - -// Query sets the optional parameter "query": Search string in the -// format given at -// http://support.google.com/chromeos/a/bin/answer.py?hl=en&answer=1698333 -func (c *ChromeosdevicesListCall) Query(query string) *ChromeosdevicesListCall { - c.urlParams_.Set("query", query) - return c -} - -// SortOrder sets the optional parameter "sortOrder": Whether to return -// results in ascending or descending order. Only of use when orderBy is -// also used -// -// Possible values: -// "ASCENDING" - Ascending order. -// "DESCENDING" - Descending order. -func (c *ChromeosdevicesListCall) SortOrder(sortOrder string) *ChromeosdevicesListCall { - c.urlParams_.Set("sortOrder", sortOrder) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *ChromeosdevicesListCall) Fields(s ...googleapi.Field) *ChromeosdevicesListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *ChromeosdevicesListCall) IfNoneMatch(entityTag string) *ChromeosdevicesListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *ChromeosdevicesListCall) Context(ctx context.Context) *ChromeosdevicesListCall { - c.ctx_ = ctx - return c -} - -func (c *ChromeosdevicesListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/chromeos") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.chromeosdevices.list" call. -// Exactly one of *ChromeOsDevices or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *ChromeOsDevices.ServerResponse.Header or (if a response was returned -// at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *ChromeosdevicesListCall) Do(opts ...googleapi.CallOption) (*ChromeOsDevices, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &ChromeOsDevices{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve all Chrome OS Devices of a customer (paginated)", - // "httpMethod": "GET", - // "id": "directory.chromeosdevices.list", - // "parameterOrder": [ - // "customerId" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "maxResults": { - // "description": "Maximum number of results to return. Default is 100", - // "format": "int32", - // "location": "query", - // "minimum": "1", - // "type": "integer" - // }, - // "orderBy": { - // "description": "Column to use for sorting results", - // "enum": [ - // "annotatedLocation", - // "annotatedUser", - // "lastSync", - // "notes", - // "serialNumber", - // "status", - // "supportEndDate" - // ], - // "enumDescriptions": [ - // "Chromebook location as annotated by the administrator.", - // "Chromebook user as annotated by administrator.", - // "Chromebook last sync.", - // "Chromebook notes as annotated by the administrator.", - // "Chromebook Serial Number.", - // "Chromebook status.", - // "Chromebook support end date." - // ], - // "location": "query", - // "type": "string" - // }, - // "pageToken": { - // "description": "Token to specify next page in the list", - // "location": "query", - // "type": "string" - // }, - // "projection": { - // "description": "Restrict information returned to a set of selected fields.", - // "enum": [ - // "BASIC", - // "FULL" - // ], - // "enumDescriptions": [ - // "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", - // "Includes all metadata fields" - // ], - // "location": "query", - // "type": "string" - // }, - // "query": { - // "description": "Search string in the format given at http://support.google.com/chromeos/a/bin/answer.py?hl=en\u0026answer=1698333", - // "location": "query", - // "type": "string" - // }, - // "sortOrder": { - // "description": "Whether to return results in ascending or descending order. Only of use when orderBy is also used", - // "enum": [ - // "ASCENDING", - // "DESCENDING" - // ], - // "enumDescriptions": [ - // "Ascending order.", - // "Descending order." - // ], - // "location": "query", - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/devices/chromeos", - // "response": { - // "$ref": "ChromeOsDevices" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.device.chromeos", - // "https://www.googleapis.com/auth/admin.directory.device.chromeos.readonly" - // ] - // } - -} - -// Pages invokes f for each page of results. -// A non-nil error returned from f will halt the iteration. -// The provided context supersedes any context provided to the Context method. -func (c *ChromeosdevicesListCall) Pages(ctx context.Context, f func(*ChromeOsDevices) error) error { - c.ctx_ = ctx - defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point - for { - x, err := c.Do() - if err != nil { - return err - } - if err := f(x); err != nil { - return err - } - if x.NextPageToken == "" { - return nil - } - c.PageToken(x.NextPageToken) - } -} - -// method id "directory.chromeosdevices.patch": - -type ChromeosdevicesPatchCall struct { - s *Service - customerId string - deviceId string - chromeosdevice *ChromeOsDevice - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Patch: Update Chrome OS Device. This method supports patch semantics. -func (r *ChromeosdevicesService) Patch(customerId string, deviceId string, chromeosdevice *ChromeOsDevice) *ChromeosdevicesPatchCall { - c := &ChromeosdevicesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.deviceId = deviceId - c.chromeosdevice = chromeosdevice - return c -} - -// Projection sets the optional parameter "projection": Restrict -// information returned to a set of selected fields. -// -// Possible values: -// "BASIC" - Includes only the basic metadata fields (e.g., deviceId, -// serialNumber, status, and user) -// "FULL" - Includes all metadata fields -func (c *ChromeosdevicesPatchCall) Projection(projection string) *ChromeosdevicesPatchCall { - c.urlParams_.Set("projection", projection) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *ChromeosdevicesPatchCall) Fields(s ...googleapi.Field) *ChromeosdevicesPatchCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *ChromeosdevicesPatchCall) Context(ctx context.Context) *ChromeosdevicesPatchCall { - c.ctx_ = ctx - return c -} - -func (c *ChromeosdevicesPatchCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.chromeosdevice) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/chromeos/{deviceId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PATCH", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "deviceId": c.deviceId, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.chromeosdevices.patch" call. -// Exactly one of *ChromeOsDevice or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *ChromeOsDevice.ServerResponse.Header or (if a response was returned -// at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *ChromeosdevicesPatchCall) Do(opts ...googleapi.CallOption) (*ChromeOsDevice, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &ChromeOsDevice{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Update Chrome OS Device. This method supports patch semantics.", - // "httpMethod": "PATCH", - // "id": "directory.chromeosdevices.patch", - // "parameterOrder": [ - // "customerId", - // "deviceId" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "deviceId": { - // "description": "Immutable id of Chrome OS Device", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "projection": { - // "description": "Restrict information returned to a set of selected fields.", - // "enum": [ - // "BASIC", - // "FULL" - // ], - // "enumDescriptions": [ - // "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", - // "Includes all metadata fields" - // ], - // "location": "query", - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/devices/chromeos/{deviceId}", - // "request": { - // "$ref": "ChromeOsDevice" - // }, - // "response": { - // "$ref": "ChromeOsDevice" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.device.chromeos" - // ] - // } - -} - -// method id "directory.chromeosdevices.update": - -type ChromeosdevicesUpdateCall struct { - s *Service - customerId string - deviceId string - chromeosdevice *ChromeOsDevice - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Update: Update Chrome OS Device -func (r *ChromeosdevicesService) Update(customerId string, deviceId string, chromeosdevice *ChromeOsDevice) *ChromeosdevicesUpdateCall { - c := &ChromeosdevicesUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.deviceId = deviceId - c.chromeosdevice = chromeosdevice - return c -} - -// Projection sets the optional parameter "projection": Restrict -// information returned to a set of selected fields. -// -// Possible values: -// "BASIC" - Includes only the basic metadata fields (e.g., deviceId, -// serialNumber, status, and user) -// "FULL" - Includes all metadata fields -func (c *ChromeosdevicesUpdateCall) Projection(projection string) *ChromeosdevicesUpdateCall { - c.urlParams_.Set("projection", projection) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *ChromeosdevicesUpdateCall) Fields(s ...googleapi.Field) *ChromeosdevicesUpdateCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *ChromeosdevicesUpdateCall) Context(ctx context.Context) *ChromeosdevicesUpdateCall { - c.ctx_ = ctx - return c -} - -func (c *ChromeosdevicesUpdateCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.chromeosdevice) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/chromeos/{deviceId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PUT", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "deviceId": c.deviceId, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.chromeosdevices.update" call. -// Exactly one of *ChromeOsDevice or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *ChromeOsDevice.ServerResponse.Header or (if a response was returned -// at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *ChromeosdevicesUpdateCall) Do(opts ...googleapi.CallOption) (*ChromeOsDevice, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &ChromeOsDevice{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Update Chrome OS Device", - // "httpMethod": "PUT", - // "id": "directory.chromeosdevices.update", - // "parameterOrder": [ - // "customerId", - // "deviceId" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "deviceId": { - // "description": "Immutable id of Chrome OS Device", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "projection": { - // "description": "Restrict information returned to a set of selected fields.", - // "enum": [ - // "BASIC", - // "FULL" - // ], - // "enumDescriptions": [ - // "Includes only the basic metadata fields (e.g., deviceId, serialNumber, status, and user)", - // "Includes all metadata fields" - // ], - // "location": "query", - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/devices/chromeos/{deviceId}", - // "request": { - // "$ref": "ChromeOsDevice" - // }, - // "response": { - // "$ref": "ChromeOsDevice" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.device.chromeos" - // ] - // } - -} - -// method id "directory.customers.get": - -type CustomersGetCall struct { - s *Service - customerKey string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrives a customer. -func (r *CustomersService) Get(customerKey string) *CustomersGetCall { - c := &CustomersGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerKey = customerKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *CustomersGetCall) Fields(s ...googleapi.Field) *CustomersGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *CustomersGetCall) IfNoneMatch(entityTag string) *CustomersGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *CustomersGetCall) Context(ctx context.Context) *CustomersGetCall { - c.ctx_ = ctx - return c -} - -func (c *CustomersGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customers/{customerKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerKey": c.customerKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.customers.get" call. -// Exactly one of *Customer or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Customer.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *CustomersGetCall) Do(opts ...googleapi.CallOption) (*Customer, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Customer{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrives a customer.", - // "httpMethod": "GET", - // "id": "directory.customers.get", - // "parameterOrder": [ - // "customerKey" - // ], - // "parameters": { - // "customerKey": { - // "description": "Id of the customer to be retrieved", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customers/{customerKey}", - // "response": { - // "$ref": "Customer" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.customer", - // "https://www.googleapis.com/auth/admin.directory.customer.readonly" - // ] - // } - -} - -// method id "directory.customers.patch": - -type CustomersPatchCall struct { - s *Service - customerKey string - customer *Customer - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Patch: Updates a customer. This method supports patch semantics. -func (r *CustomersService) Patch(customerKey string, customer *Customer) *CustomersPatchCall { - c := &CustomersPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerKey = customerKey - c.customer = customer - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *CustomersPatchCall) Fields(s ...googleapi.Field) *CustomersPatchCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *CustomersPatchCall) Context(ctx context.Context) *CustomersPatchCall { - c.ctx_ = ctx - return c -} - -func (c *CustomersPatchCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.customer) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customers/{customerKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PATCH", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerKey": c.customerKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.customers.patch" call. -// Exactly one of *Customer or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Customer.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *CustomersPatchCall) Do(opts ...googleapi.CallOption) (*Customer, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Customer{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Updates a customer. This method supports patch semantics.", - // "httpMethod": "PATCH", - // "id": "directory.customers.patch", - // "parameterOrder": [ - // "customerKey" - // ], - // "parameters": { - // "customerKey": { - // "description": "Id of the customer to be updated", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customers/{customerKey}", - // "request": { - // "$ref": "Customer" - // }, - // "response": { - // "$ref": "Customer" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.customer" - // ] - // } - -} - -// method id "directory.customers.update": - -type CustomersUpdateCall struct { - s *Service - customerKey string - customer *Customer - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Update: Updates a customer. -func (r *CustomersService) Update(customerKey string, customer *Customer) *CustomersUpdateCall { - c := &CustomersUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerKey = customerKey - c.customer = customer - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *CustomersUpdateCall) Fields(s ...googleapi.Field) *CustomersUpdateCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *CustomersUpdateCall) Context(ctx context.Context) *CustomersUpdateCall { - c.ctx_ = ctx - return c -} - -func (c *CustomersUpdateCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.customer) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customers/{customerKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PUT", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerKey": c.customerKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.customers.update" call. -// Exactly one of *Customer or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Customer.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *CustomersUpdateCall) Do(opts ...googleapi.CallOption) (*Customer, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Customer{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Updates a customer.", - // "httpMethod": "PUT", - // "id": "directory.customers.update", - // "parameterOrder": [ - // "customerKey" - // ], - // "parameters": { - // "customerKey": { - // "description": "Id of the customer to be updated", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customers/{customerKey}", - // "request": { - // "$ref": "Customer" - // }, - // "response": { - // "$ref": "Customer" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.customer" - // ] - // } - -} - -// method id "directory.domainAliases.delete": - -type DomainAliasesDeleteCall struct { - s *Service - customer string - domainAliasName string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Deletes a Domain Alias of the customer. -func (r *DomainAliasesService) Delete(customer string, domainAliasName string) *DomainAliasesDeleteCall { - c := &DomainAliasesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.domainAliasName = domainAliasName - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *DomainAliasesDeleteCall) Fields(s ...googleapi.Field) *DomainAliasesDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *DomainAliasesDeleteCall) Context(ctx context.Context) *DomainAliasesDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *DomainAliasesDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domainaliases/{domainAliasName}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "domainAliasName": c.domainAliasName, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.domainAliases.delete" call. -func (c *DomainAliasesDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Deletes a Domain Alias of the customer.", - // "httpMethod": "DELETE", - // "id": "directory.domainAliases.delete", - // "parameterOrder": [ - // "customer", - // "domainAliasName" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable id of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "domainAliasName": { - // "description": "Name of domain alias to be retrieved.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/domainaliases/{domainAliasName}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.domain" - // ] - // } - -} - -// method id "directory.domainAliases.get": - -type DomainAliasesGetCall struct { - s *Service - customer string - domainAliasName string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrieves a domain alias of the customer. -func (r *DomainAliasesService) Get(customer string, domainAliasName string) *DomainAliasesGetCall { - c := &DomainAliasesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.domainAliasName = domainAliasName - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *DomainAliasesGetCall) Fields(s ...googleapi.Field) *DomainAliasesGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *DomainAliasesGetCall) IfNoneMatch(entityTag string) *DomainAliasesGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *DomainAliasesGetCall) Context(ctx context.Context) *DomainAliasesGetCall { - c.ctx_ = ctx - return c -} - -func (c *DomainAliasesGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domainaliases/{domainAliasName}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "domainAliasName": c.domainAliasName, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.domainAliases.get" call. -// Exactly one of *DomainAlias or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *DomainAlias.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *DomainAliasesGetCall) Do(opts ...googleapi.CallOption) (*DomainAlias, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &DomainAlias{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieves a domain alias of the customer.", - // "httpMethod": "GET", - // "id": "directory.domainAliases.get", - // "parameterOrder": [ - // "customer", - // "domainAliasName" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable id of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "domainAliasName": { - // "description": "Name of domain alias to be retrieved.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/domainaliases/{domainAliasName}", - // "response": { - // "$ref": "DomainAlias" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.domain", - // "https://www.googleapis.com/auth/admin.directory.domain.readonly" - // ] - // } - -} - -// method id "directory.domainAliases.insert": - -type DomainAliasesInsertCall struct { - s *Service - customer string - domainalias *DomainAlias - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Insert: Inserts a Domain alias of the customer. -func (r *DomainAliasesService) Insert(customer string, domainalias *DomainAlias) *DomainAliasesInsertCall { - c := &DomainAliasesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.domainalias = domainalias - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *DomainAliasesInsertCall) Fields(s ...googleapi.Field) *DomainAliasesInsertCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *DomainAliasesInsertCall) Context(ctx context.Context) *DomainAliasesInsertCall { - c.ctx_ = ctx - return c -} - -func (c *DomainAliasesInsertCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.domainalias) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domainaliases") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.domainAliases.insert" call. -// Exactly one of *DomainAlias or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *DomainAlias.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *DomainAliasesInsertCall) Do(opts ...googleapi.CallOption) (*DomainAlias, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &DomainAlias{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Inserts a Domain alias of the customer.", - // "httpMethod": "POST", - // "id": "directory.domainAliases.insert", - // "parameterOrder": [ - // "customer" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable id of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/domainaliases", - // "request": { - // "$ref": "DomainAlias" - // }, - // "response": { - // "$ref": "DomainAlias" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.domain" - // ] - // } - -} - -// method id "directory.domainAliases.list": - -type DomainAliasesListCall struct { - s *Service - customer string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Lists the domain aliases of the customer. -func (r *DomainAliasesService) List(customer string) *DomainAliasesListCall { - c := &DomainAliasesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - return c -} - -// ParentDomainName sets the optional parameter "parentDomainName": Name -// of the parent domain for which domain aliases are to be fetched. -func (c *DomainAliasesListCall) ParentDomainName(parentDomainName string) *DomainAliasesListCall { - c.urlParams_.Set("parentDomainName", parentDomainName) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *DomainAliasesListCall) Fields(s ...googleapi.Field) *DomainAliasesListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *DomainAliasesListCall) IfNoneMatch(entityTag string) *DomainAliasesListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *DomainAliasesListCall) Context(ctx context.Context) *DomainAliasesListCall { - c.ctx_ = ctx - return c -} - -func (c *DomainAliasesListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domainaliases") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.domainAliases.list" call. -// Exactly one of *DomainAliases or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *DomainAliases.ServerResponse.Header or (if a response was returned -// at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *DomainAliasesListCall) Do(opts ...googleapi.CallOption) (*DomainAliases, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &DomainAliases{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Lists the domain aliases of the customer.", - // "httpMethod": "GET", - // "id": "directory.domainAliases.list", - // "parameterOrder": [ - // "customer" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable id of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "parentDomainName": { - // "description": "Name of the parent domain for which domain aliases are to be fetched.", - // "location": "query", - // "type": "string" - // } - // }, - // "path": "customer/{customer}/domainaliases", - // "response": { - // "$ref": "DomainAliases" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.domain", - // "https://www.googleapis.com/auth/admin.directory.domain.readonly" - // ] - // } - -} - -// method id "directory.domains.delete": - -type DomainsDeleteCall struct { - s *Service - customer string - domainName string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Deletes a domain of the customer. -func (r *DomainsService) Delete(customer string, domainName string) *DomainsDeleteCall { - c := &DomainsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.domainName = domainName - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *DomainsDeleteCall) Fields(s ...googleapi.Field) *DomainsDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *DomainsDeleteCall) Context(ctx context.Context) *DomainsDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *DomainsDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domains/{domainName}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "domainName": c.domainName, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.domains.delete" call. -func (c *DomainsDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Deletes a domain of the customer.", - // "httpMethod": "DELETE", - // "id": "directory.domains.delete", - // "parameterOrder": [ - // "customer", - // "domainName" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable id of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "domainName": { - // "description": "Name of domain to be deleted", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/domains/{domainName}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.domain" - // ] - // } - -} - -// method id "directory.domains.get": - -type DomainsGetCall struct { - s *Service - customer string - domainName string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrives a domain of the customer. -func (r *DomainsService) Get(customer string, domainName string) *DomainsGetCall { - c := &DomainsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.domainName = domainName - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *DomainsGetCall) Fields(s ...googleapi.Field) *DomainsGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *DomainsGetCall) IfNoneMatch(entityTag string) *DomainsGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *DomainsGetCall) Context(ctx context.Context) *DomainsGetCall { - c.ctx_ = ctx - return c -} - -func (c *DomainsGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domains/{domainName}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "domainName": c.domainName, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.domains.get" call. -// Exactly one of *Domains or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Domains.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *DomainsGetCall) Do(opts ...googleapi.CallOption) (*Domains, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Domains{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrives a domain of the customer.", - // "httpMethod": "GET", - // "id": "directory.domains.get", - // "parameterOrder": [ - // "customer", - // "domainName" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable id of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "domainName": { - // "description": "Name of domain to be retrieved", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/domains/{domainName}", - // "response": { - // "$ref": "Domains" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.domain", - // "https://www.googleapis.com/auth/admin.directory.domain.readonly" - // ] - // } - -} - -// method id "directory.domains.insert": - -type DomainsInsertCall struct { - s *Service - customer string - domains *Domains - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Insert: Inserts a domain of the customer. -func (r *DomainsService) Insert(customer string, domains *Domains) *DomainsInsertCall { - c := &DomainsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.domains = domains - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *DomainsInsertCall) Fields(s ...googleapi.Field) *DomainsInsertCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *DomainsInsertCall) Context(ctx context.Context) *DomainsInsertCall { - c.ctx_ = ctx - return c -} - -func (c *DomainsInsertCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.domains) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domains") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.domains.insert" call. -// Exactly one of *Domains or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Domains.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *DomainsInsertCall) Do(opts ...googleapi.CallOption) (*Domains, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Domains{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Inserts a domain of the customer.", - // "httpMethod": "POST", - // "id": "directory.domains.insert", - // "parameterOrder": [ - // "customer" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable id of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/domains", - // "request": { - // "$ref": "Domains" - // }, - // "response": { - // "$ref": "Domains" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.domain" - // ] - // } - -} - -// method id "directory.domains.list": - -type DomainsListCall struct { - s *Service - customer string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Lists the domains of the customer. -func (r *DomainsService) List(customer string) *DomainsListCall { - c := &DomainsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *DomainsListCall) Fields(s ...googleapi.Field) *DomainsListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *DomainsListCall) IfNoneMatch(entityTag string) *DomainsListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *DomainsListCall) Context(ctx context.Context) *DomainsListCall { - c.ctx_ = ctx - return c -} - -func (c *DomainsListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/domains") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.domains.list" call. -// Exactly one of *Domains2 or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Domains2.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *DomainsListCall) Do(opts ...googleapi.CallOption) (*Domains2, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Domains2{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Lists the domains of the customer.", - // "httpMethod": "GET", - // "id": "directory.domains.list", - // "parameterOrder": [ - // "customer" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable id of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/domains", - // "response": { - // "$ref": "Domains2" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.domain", - // "https://www.googleapis.com/auth/admin.directory.domain.readonly" - // ] - // } - -} - -// method id "directory.groups.delete": - -type GroupsDeleteCall struct { - s *Service - groupKey string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Delete Group -func (r *GroupsService) Delete(groupKey string) *GroupsDeleteCall { - c := &GroupsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.groupKey = groupKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *GroupsDeleteCall) Fields(s ...googleapi.Field) *GroupsDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *GroupsDeleteCall) Context(ctx context.Context) *GroupsDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *GroupsDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "groupKey": c.groupKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.groups.delete" call. -func (c *GroupsDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Delete Group", - // "httpMethod": "DELETE", - // "id": "directory.groups.delete", - // "parameterOrder": [ - // "groupKey" - // ], - // "parameters": { - // "groupKey": { - // "description": "Email or immutable Id of the group", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "groups/{groupKey}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group" - // ] - // } - -} - -// method id "directory.groups.get": - -type GroupsGetCall struct { - s *Service - groupKey string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrieve Group -func (r *GroupsService) Get(groupKey string) *GroupsGetCall { - c := &GroupsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.groupKey = groupKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *GroupsGetCall) Fields(s ...googleapi.Field) *GroupsGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *GroupsGetCall) IfNoneMatch(entityTag string) *GroupsGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *GroupsGetCall) Context(ctx context.Context) *GroupsGetCall { - c.ctx_ = ctx - return c -} - -func (c *GroupsGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "groupKey": c.groupKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.groups.get" call. -// Exactly one of *Group or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Group.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *GroupsGetCall) Do(opts ...googleapi.CallOption) (*Group, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Group{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve Group", - // "httpMethod": "GET", - // "id": "directory.groups.get", - // "parameterOrder": [ - // "groupKey" - // ], - // "parameters": { - // "groupKey": { - // "description": "Email or immutable Id of the group", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "groups/{groupKey}", - // "response": { - // "$ref": "Group" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group", - // "https://www.googleapis.com/auth/admin.directory.group.readonly" - // ] - // } - -} - -// method id "directory.groups.insert": - -type GroupsInsertCall struct { - s *Service - group *Group - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Insert: Create Group -func (r *GroupsService) Insert(group *Group) *GroupsInsertCall { - c := &GroupsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.group = group - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *GroupsInsertCall) Fields(s ...googleapi.Field) *GroupsInsertCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *GroupsInsertCall) Context(ctx context.Context) *GroupsInsertCall { - c.ctx_ = ctx - return c -} - -func (c *GroupsInsertCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.group) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.SetOpaque(req.URL) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.groups.insert" call. -// Exactly one of *Group or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Group.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *GroupsInsertCall) Do(opts ...googleapi.CallOption) (*Group, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Group{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Create Group", - // "httpMethod": "POST", - // "id": "directory.groups.insert", - // "path": "groups", - // "request": { - // "$ref": "Group" - // }, - // "response": { - // "$ref": "Group" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group" - // ] - // } - -} - -// method id "directory.groups.list": - -type GroupsListCall struct { - s *Service - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Retrieve all groups in a domain (paginated) -func (r *GroupsService) List() *GroupsListCall { - c := &GroupsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - return c -} - -// Customer sets the optional parameter "customer": Immutable id of the -// Google Apps account. In case of multi-domain, to fetch all groups for -// a customer, fill this field instead of domain. -func (c *GroupsListCall) Customer(customer string) *GroupsListCall { - c.urlParams_.Set("customer", customer) - return c -} - -// Domain sets the optional parameter "domain": Name of the domain. Fill -// this field to get groups from only this domain. To return all groups -// in a multi-domain fill customer field instead. -func (c *GroupsListCall) Domain(domain string) *GroupsListCall { - c.urlParams_.Set("domain", domain) - return c -} - -// MaxResults sets the optional parameter "maxResults": Maximum number -// of results to return. Default is 200 -func (c *GroupsListCall) MaxResults(maxResults int64) *GroupsListCall { - c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) - return c -} - -// PageToken sets the optional parameter "pageToken": Token to specify -// next page in the list -func (c *GroupsListCall) PageToken(pageToken string) *GroupsListCall { - c.urlParams_.Set("pageToken", pageToken) - return c -} - -// UserKey sets the optional parameter "userKey": Email or immutable Id -// of the user if only those groups are to be listed, the given user is -// a member of. If Id, it should match with id of user object -func (c *GroupsListCall) UserKey(userKey string) *GroupsListCall { - c.urlParams_.Set("userKey", userKey) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *GroupsListCall) Fields(s ...googleapi.Field) *GroupsListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *GroupsListCall) IfNoneMatch(entityTag string) *GroupsListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *GroupsListCall) Context(ctx context.Context) *GroupsListCall { - c.ctx_ = ctx - return c -} - -func (c *GroupsListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.SetOpaque(req.URL) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.groups.list" call. -// Exactly one of *Groups or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Groups.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *GroupsListCall) Do(opts ...googleapi.CallOption) (*Groups, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Groups{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve all groups in a domain (paginated)", - // "httpMethod": "GET", - // "id": "directory.groups.list", - // "parameters": { - // "customer": { - // "description": "Immutable id of the Google Apps account. In case of multi-domain, to fetch all groups for a customer, fill this field instead of domain.", - // "location": "query", - // "type": "string" - // }, - // "domain": { - // "description": "Name of the domain. Fill this field to get groups from only this domain. To return all groups in a multi-domain fill customer field instead.", - // "location": "query", - // "type": "string" - // }, - // "maxResults": { - // "description": "Maximum number of results to return. Default is 200", - // "format": "int32", - // "location": "query", - // "minimum": "1", - // "type": "integer" - // }, - // "pageToken": { - // "description": "Token to specify next page in the list", - // "location": "query", - // "type": "string" - // }, - // "userKey": { - // "description": "Email or immutable Id of the user if only those groups are to be listed, the given user is a member of. If Id, it should match with id of user object", - // "location": "query", - // "type": "string" - // } - // }, - // "path": "groups", - // "response": { - // "$ref": "Groups" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group", - // "https://www.googleapis.com/auth/admin.directory.group.readonly" - // ] - // } - -} - -// Pages invokes f for each page of results. -// A non-nil error returned from f will halt the iteration. -// The provided context supersedes any context provided to the Context method. -func (c *GroupsListCall) Pages(ctx context.Context, f func(*Groups) error) error { - c.ctx_ = ctx - defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point - for { - x, err := c.Do() - if err != nil { - return err - } - if err := f(x); err != nil { - return err - } - if x.NextPageToken == "" { - return nil - } - c.PageToken(x.NextPageToken) - } -} - -// method id "directory.groups.patch": - -type GroupsPatchCall struct { - s *Service - groupKey string - group *Group - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Patch: Update Group. This method supports patch semantics. -func (r *GroupsService) Patch(groupKey string, group *Group) *GroupsPatchCall { - c := &GroupsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.groupKey = groupKey - c.group = group - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *GroupsPatchCall) Fields(s ...googleapi.Field) *GroupsPatchCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *GroupsPatchCall) Context(ctx context.Context) *GroupsPatchCall { - c.ctx_ = ctx - return c -} - -func (c *GroupsPatchCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.group) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PATCH", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "groupKey": c.groupKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.groups.patch" call. -// Exactly one of *Group or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Group.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *GroupsPatchCall) Do(opts ...googleapi.CallOption) (*Group, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Group{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Update Group. This method supports patch semantics.", - // "httpMethod": "PATCH", - // "id": "directory.groups.patch", - // "parameterOrder": [ - // "groupKey" - // ], - // "parameters": { - // "groupKey": { - // "description": "Email or immutable Id of the group. If Id, it should match with id of group object", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "groups/{groupKey}", - // "request": { - // "$ref": "Group" - // }, - // "response": { - // "$ref": "Group" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group" - // ] - // } - -} - -// method id "directory.groups.update": - -type GroupsUpdateCall struct { - s *Service - groupKey string - group *Group - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Update: Update Group -func (r *GroupsService) Update(groupKey string, group *Group) *GroupsUpdateCall { - c := &GroupsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.groupKey = groupKey - c.group = group - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *GroupsUpdateCall) Fields(s ...googleapi.Field) *GroupsUpdateCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *GroupsUpdateCall) Context(ctx context.Context) *GroupsUpdateCall { - c.ctx_ = ctx - return c -} - -func (c *GroupsUpdateCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.group) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PUT", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "groupKey": c.groupKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.groups.update" call. -// Exactly one of *Group or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Group.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *GroupsUpdateCall) Do(opts ...googleapi.CallOption) (*Group, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Group{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Update Group", - // "httpMethod": "PUT", - // "id": "directory.groups.update", - // "parameterOrder": [ - // "groupKey" - // ], - // "parameters": { - // "groupKey": { - // "description": "Email or immutable Id of the group. If Id, it should match with id of group object", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "groups/{groupKey}", - // "request": { - // "$ref": "Group" - // }, - // "response": { - // "$ref": "Group" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group" - // ] - // } - -} - -// method id "directory.groups.aliases.delete": - -type GroupsAliasesDeleteCall struct { - s *Service - groupKey string - alias string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Remove a alias for the group -func (r *GroupsAliasesService) Delete(groupKey string, alias string) *GroupsAliasesDeleteCall { - c := &GroupsAliasesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.groupKey = groupKey - c.alias = alias - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *GroupsAliasesDeleteCall) Fields(s ...googleapi.Field) *GroupsAliasesDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *GroupsAliasesDeleteCall) Context(ctx context.Context) *GroupsAliasesDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *GroupsAliasesDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/aliases/{alias}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "groupKey": c.groupKey, - "alias": c.alias, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.groups.aliases.delete" call. -func (c *GroupsAliasesDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Remove a alias for the group", - // "httpMethod": "DELETE", - // "id": "directory.groups.aliases.delete", - // "parameterOrder": [ - // "groupKey", - // "alias" - // ], - // "parameters": { - // "alias": { - // "description": "The alias to be removed", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "groupKey": { - // "description": "Email or immutable Id of the group", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "groups/{groupKey}/aliases/{alias}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group" - // ] - // } - -} - -// method id "directory.groups.aliases.insert": - -type GroupsAliasesInsertCall struct { - s *Service - groupKey string - alias *Alias - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Insert: Add a alias for the group -func (r *GroupsAliasesService) Insert(groupKey string, alias *Alias) *GroupsAliasesInsertCall { - c := &GroupsAliasesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.groupKey = groupKey - c.alias = alias - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *GroupsAliasesInsertCall) Fields(s ...googleapi.Field) *GroupsAliasesInsertCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *GroupsAliasesInsertCall) Context(ctx context.Context) *GroupsAliasesInsertCall { - c.ctx_ = ctx - return c -} - -func (c *GroupsAliasesInsertCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.alias) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/aliases") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "groupKey": c.groupKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.groups.aliases.insert" call. -// Exactly one of *Alias or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Alias.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *GroupsAliasesInsertCall) Do(opts ...googleapi.CallOption) (*Alias, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Alias{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Add a alias for the group", - // "httpMethod": "POST", - // "id": "directory.groups.aliases.insert", - // "parameterOrder": [ - // "groupKey" - // ], - // "parameters": { - // "groupKey": { - // "description": "Email or immutable Id of the group", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "groups/{groupKey}/aliases", - // "request": { - // "$ref": "Alias" - // }, - // "response": { - // "$ref": "Alias" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group" - // ] - // } - -} - -// method id "directory.groups.aliases.list": - -type GroupsAliasesListCall struct { - s *Service - groupKey string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: List all aliases for a group -func (r *GroupsAliasesService) List(groupKey string) *GroupsAliasesListCall { - c := &GroupsAliasesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.groupKey = groupKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *GroupsAliasesListCall) Fields(s ...googleapi.Field) *GroupsAliasesListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *GroupsAliasesListCall) IfNoneMatch(entityTag string) *GroupsAliasesListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *GroupsAliasesListCall) Context(ctx context.Context) *GroupsAliasesListCall { - c.ctx_ = ctx - return c -} - -func (c *GroupsAliasesListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/aliases") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "groupKey": c.groupKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.groups.aliases.list" call. -// Exactly one of *Aliases or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Aliases.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *GroupsAliasesListCall) Do(opts ...googleapi.CallOption) (*Aliases, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Aliases{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "List all aliases for a group", - // "httpMethod": "GET", - // "id": "directory.groups.aliases.list", - // "parameterOrder": [ - // "groupKey" - // ], - // "parameters": { - // "groupKey": { - // "description": "Email or immutable Id of the group", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "groups/{groupKey}/aliases", - // "response": { - // "$ref": "Aliases" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group", - // "https://www.googleapis.com/auth/admin.directory.group.readonly" - // ], - // "supportsSubscription": true - // } - -} - -// method id "directory.members.delete": - -type MembersDeleteCall struct { - s *Service - groupKey string - memberKey string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Remove membership. -func (r *MembersService) Delete(groupKey string, memberKey string) *MembersDeleteCall { - c := &MembersDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.groupKey = groupKey - c.memberKey = memberKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *MembersDeleteCall) Fields(s ...googleapi.Field) *MembersDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *MembersDeleteCall) Context(ctx context.Context) *MembersDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *MembersDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/members/{memberKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "groupKey": c.groupKey, - "memberKey": c.memberKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.members.delete" call. -func (c *MembersDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Remove membership.", - // "httpMethod": "DELETE", - // "id": "directory.members.delete", - // "parameterOrder": [ - // "groupKey", - // "memberKey" - // ], - // "parameters": { - // "groupKey": { - // "description": "Email or immutable Id of the group", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "memberKey": { - // "description": "Email or immutable Id of the member", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "groups/{groupKey}/members/{memberKey}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group", - // "https://www.googleapis.com/auth/admin.directory.group.member" - // ] - // } - -} - -// method id "directory.members.get": - -type MembersGetCall struct { - s *Service - groupKey string - memberKey string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrieve Group Member -func (r *MembersService) Get(groupKey string, memberKey string) *MembersGetCall { - c := &MembersGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.groupKey = groupKey - c.memberKey = memberKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *MembersGetCall) Fields(s ...googleapi.Field) *MembersGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *MembersGetCall) IfNoneMatch(entityTag string) *MembersGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *MembersGetCall) Context(ctx context.Context) *MembersGetCall { - c.ctx_ = ctx - return c -} - -func (c *MembersGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/members/{memberKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "groupKey": c.groupKey, - "memberKey": c.memberKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.members.get" call. -// Exactly one of *Member or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Member.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *MembersGetCall) Do(opts ...googleapi.CallOption) (*Member, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Member{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve Group Member", - // "httpMethod": "GET", - // "id": "directory.members.get", - // "parameterOrder": [ - // "groupKey", - // "memberKey" - // ], - // "parameters": { - // "groupKey": { - // "description": "Email or immutable Id of the group", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "memberKey": { - // "description": "Email or immutable Id of the member", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "groups/{groupKey}/members/{memberKey}", - // "response": { - // "$ref": "Member" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group", - // "https://www.googleapis.com/auth/admin.directory.group.member", - // "https://www.googleapis.com/auth/admin.directory.group.member.readonly", - // "https://www.googleapis.com/auth/admin.directory.group.readonly" - // ] - // } - -} - -// method id "directory.members.insert": - -type MembersInsertCall struct { - s *Service - groupKey string - member *Member - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Insert: Add user to the specified group. -func (r *MembersService) Insert(groupKey string, member *Member) *MembersInsertCall { - c := &MembersInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.groupKey = groupKey - c.member = member - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *MembersInsertCall) Fields(s ...googleapi.Field) *MembersInsertCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *MembersInsertCall) Context(ctx context.Context) *MembersInsertCall { - c.ctx_ = ctx - return c -} - -func (c *MembersInsertCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.member) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/members") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "groupKey": c.groupKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.members.insert" call. -// Exactly one of *Member or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Member.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *MembersInsertCall) Do(opts ...googleapi.CallOption) (*Member, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Member{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Add user to the specified group.", - // "httpMethod": "POST", - // "id": "directory.members.insert", - // "parameterOrder": [ - // "groupKey" - // ], - // "parameters": { - // "groupKey": { - // "description": "Email or immutable Id of the group", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "groups/{groupKey}/members", - // "request": { - // "$ref": "Member" - // }, - // "response": { - // "$ref": "Member" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group", - // "https://www.googleapis.com/auth/admin.directory.group.member" - // ] - // } - -} - -// method id "directory.members.list": - -type MembersListCall struct { - s *Service - groupKey string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Retrieve all members in a group (paginated) -func (r *MembersService) List(groupKey string) *MembersListCall { - c := &MembersListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.groupKey = groupKey - return c -} - -// MaxResults sets the optional parameter "maxResults": Maximum number -// of results to return. Default is 200 -func (c *MembersListCall) MaxResults(maxResults int64) *MembersListCall { - c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) - return c -} - -// PageToken sets the optional parameter "pageToken": Token to specify -// next page in the list -func (c *MembersListCall) PageToken(pageToken string) *MembersListCall { - c.urlParams_.Set("pageToken", pageToken) - return c -} - -// Roles sets the optional parameter "roles": Comma separated role -// values to filter list results on. -func (c *MembersListCall) Roles(roles string) *MembersListCall { - c.urlParams_.Set("roles", roles) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *MembersListCall) Fields(s ...googleapi.Field) *MembersListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *MembersListCall) IfNoneMatch(entityTag string) *MembersListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *MembersListCall) Context(ctx context.Context) *MembersListCall { - c.ctx_ = ctx - return c -} - -func (c *MembersListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/members") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "groupKey": c.groupKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.members.list" call. -// Exactly one of *Members or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Members.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *MembersListCall) Do(opts ...googleapi.CallOption) (*Members, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Members{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve all members in a group (paginated)", - // "httpMethod": "GET", - // "id": "directory.members.list", - // "parameterOrder": [ - // "groupKey" - // ], - // "parameters": { - // "groupKey": { - // "description": "Email or immutable Id of the group", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "maxResults": { - // "description": "Maximum number of results to return. Default is 200", - // "format": "int32", - // "location": "query", - // "minimum": "1", - // "type": "integer" - // }, - // "pageToken": { - // "description": "Token to specify next page in the list", - // "location": "query", - // "type": "string" - // }, - // "roles": { - // "description": "Comma separated role values to filter list results on.", - // "location": "query", - // "type": "string" - // } - // }, - // "path": "groups/{groupKey}/members", - // "response": { - // "$ref": "Members" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group", - // "https://www.googleapis.com/auth/admin.directory.group.member", - // "https://www.googleapis.com/auth/admin.directory.group.member.readonly", - // "https://www.googleapis.com/auth/admin.directory.group.readonly" - // ] - // } - -} - -// Pages invokes f for each page of results. -// A non-nil error returned from f will halt the iteration. -// The provided context supersedes any context provided to the Context method. -func (c *MembersListCall) Pages(ctx context.Context, f func(*Members) error) error { - c.ctx_ = ctx - defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point - for { - x, err := c.Do() - if err != nil { - return err - } - if err := f(x); err != nil { - return err - } - if x.NextPageToken == "" { - return nil - } - c.PageToken(x.NextPageToken) - } -} - -// method id "directory.members.patch": - -type MembersPatchCall struct { - s *Service - groupKey string - memberKey string - member *Member - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Patch: Update membership of a user in the specified group. This -// method supports patch semantics. -func (r *MembersService) Patch(groupKey string, memberKey string, member *Member) *MembersPatchCall { - c := &MembersPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.groupKey = groupKey - c.memberKey = memberKey - c.member = member - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *MembersPatchCall) Fields(s ...googleapi.Field) *MembersPatchCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *MembersPatchCall) Context(ctx context.Context) *MembersPatchCall { - c.ctx_ = ctx - return c -} - -func (c *MembersPatchCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.member) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/members/{memberKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PATCH", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "groupKey": c.groupKey, - "memberKey": c.memberKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.members.patch" call. -// Exactly one of *Member or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Member.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *MembersPatchCall) Do(opts ...googleapi.CallOption) (*Member, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Member{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Update membership of a user in the specified group. This method supports patch semantics.", - // "httpMethod": "PATCH", - // "id": "directory.members.patch", - // "parameterOrder": [ - // "groupKey", - // "memberKey" - // ], - // "parameters": { - // "groupKey": { - // "description": "Email or immutable Id of the group. If Id, it should match with id of group object", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "memberKey": { - // "description": "Email or immutable Id of the user. If Id, it should match with id of member object", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "groups/{groupKey}/members/{memberKey}", - // "request": { - // "$ref": "Member" - // }, - // "response": { - // "$ref": "Member" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group", - // "https://www.googleapis.com/auth/admin.directory.group.member" - // ] - // } - -} - -// method id "directory.members.update": - -type MembersUpdateCall struct { - s *Service - groupKey string - memberKey string - member *Member - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Update: Update membership of a user in the specified group. -func (r *MembersService) Update(groupKey string, memberKey string, member *Member) *MembersUpdateCall { - c := &MembersUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.groupKey = groupKey - c.memberKey = memberKey - c.member = member - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *MembersUpdateCall) Fields(s ...googleapi.Field) *MembersUpdateCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *MembersUpdateCall) Context(ctx context.Context) *MembersUpdateCall { - c.ctx_ = ctx - return c -} - -func (c *MembersUpdateCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.member) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "groups/{groupKey}/members/{memberKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PUT", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "groupKey": c.groupKey, - "memberKey": c.memberKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.members.update" call. -// Exactly one of *Member or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Member.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *MembersUpdateCall) Do(opts ...googleapi.CallOption) (*Member, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Member{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Update membership of a user in the specified group.", - // "httpMethod": "PUT", - // "id": "directory.members.update", - // "parameterOrder": [ - // "groupKey", - // "memberKey" - // ], - // "parameters": { - // "groupKey": { - // "description": "Email or immutable Id of the group. If Id, it should match with id of group object", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "memberKey": { - // "description": "Email or immutable Id of the user. If Id, it should match with id of member object", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "groups/{groupKey}/members/{memberKey}", - // "request": { - // "$ref": "Member" - // }, - // "response": { - // "$ref": "Member" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.group", - // "https://www.googleapis.com/auth/admin.directory.group.member" - // ] - // } - -} - -// method id "directory.mobiledevices.action": - -type MobiledevicesActionCall struct { - s *Service - customerId string - resourceId string - mobiledeviceaction *MobileDeviceAction - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Action: Take action on Mobile Device -func (r *MobiledevicesService) Action(customerId string, resourceId string, mobiledeviceaction *MobileDeviceAction) *MobiledevicesActionCall { - c := &MobiledevicesActionCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.resourceId = resourceId - c.mobiledeviceaction = mobiledeviceaction - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *MobiledevicesActionCall) Fields(s ...googleapi.Field) *MobiledevicesActionCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *MobiledevicesActionCall) Context(ctx context.Context) *MobiledevicesActionCall { - c.ctx_ = ctx - return c -} - -func (c *MobiledevicesActionCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.mobiledeviceaction) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/mobile/{resourceId}/action") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "resourceId": c.resourceId, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.mobiledevices.action" call. -func (c *MobiledevicesActionCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Take action on Mobile Device", - // "httpMethod": "POST", - // "id": "directory.mobiledevices.action", - // "parameterOrder": [ - // "customerId", - // "resourceId" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "resourceId": { - // "description": "Immutable id of Mobile Device", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/devices/mobile/{resourceId}/action", - // "request": { - // "$ref": "MobileDeviceAction" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.device.mobile", - // "https://www.googleapis.com/auth/admin.directory.device.mobile.action" - // ] - // } - -} - -// method id "directory.mobiledevices.delete": - -type MobiledevicesDeleteCall struct { - s *Service - customerId string - resourceId string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Delete Mobile Device -func (r *MobiledevicesService) Delete(customerId string, resourceId string) *MobiledevicesDeleteCall { - c := &MobiledevicesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.resourceId = resourceId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *MobiledevicesDeleteCall) Fields(s ...googleapi.Field) *MobiledevicesDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *MobiledevicesDeleteCall) Context(ctx context.Context) *MobiledevicesDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *MobiledevicesDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/mobile/{resourceId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "resourceId": c.resourceId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.mobiledevices.delete" call. -func (c *MobiledevicesDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Delete Mobile Device", - // "httpMethod": "DELETE", - // "id": "directory.mobiledevices.delete", - // "parameterOrder": [ - // "customerId", - // "resourceId" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "resourceId": { - // "description": "Immutable id of Mobile Device", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/devices/mobile/{resourceId}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.device.mobile" - // ] - // } - -} - -// method id "directory.mobiledevices.get": - -type MobiledevicesGetCall struct { - s *Service - customerId string - resourceId string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrieve Mobile Device -func (r *MobiledevicesService) Get(customerId string, resourceId string) *MobiledevicesGetCall { - c := &MobiledevicesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.resourceId = resourceId - return c -} - -// Projection sets the optional parameter "projection": Restrict -// information returned to a set of selected fields. -// -// Possible values: -// "BASIC" - Includes only the basic metadata fields (e.g., deviceId, -// model, status, type, and status) -// "FULL" - Includes all metadata fields -func (c *MobiledevicesGetCall) Projection(projection string) *MobiledevicesGetCall { - c.urlParams_.Set("projection", projection) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *MobiledevicesGetCall) Fields(s ...googleapi.Field) *MobiledevicesGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *MobiledevicesGetCall) IfNoneMatch(entityTag string) *MobiledevicesGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *MobiledevicesGetCall) Context(ctx context.Context) *MobiledevicesGetCall { - c.ctx_ = ctx - return c -} - -func (c *MobiledevicesGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/mobile/{resourceId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "resourceId": c.resourceId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.mobiledevices.get" call. -// Exactly one of *MobileDevice or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *MobileDevice.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *MobiledevicesGetCall) Do(opts ...googleapi.CallOption) (*MobileDevice, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &MobileDevice{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve Mobile Device", - // "httpMethod": "GET", - // "id": "directory.mobiledevices.get", - // "parameterOrder": [ - // "customerId", - // "resourceId" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "projection": { - // "description": "Restrict information returned to a set of selected fields.", - // "enum": [ - // "BASIC", - // "FULL" - // ], - // "enumDescriptions": [ - // "Includes only the basic metadata fields (e.g., deviceId, model, status, type, and status)", - // "Includes all metadata fields" - // ], - // "location": "query", - // "type": "string" - // }, - // "resourceId": { - // "description": "Immutable id of Mobile Device", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/devices/mobile/{resourceId}", - // "response": { - // "$ref": "MobileDevice" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.device.mobile", - // "https://www.googleapis.com/auth/admin.directory.device.mobile.action", - // "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly" - // ] - // } - -} - -// method id "directory.mobiledevices.list": - -type MobiledevicesListCall struct { - s *Service - customerId string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Retrieve all Mobile Devices of a customer (paginated) -func (r *MobiledevicesService) List(customerId string) *MobiledevicesListCall { - c := &MobiledevicesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - return c -} - -// MaxResults sets the optional parameter "maxResults": Maximum number -// of results to return. Default is 100 -func (c *MobiledevicesListCall) MaxResults(maxResults int64) *MobiledevicesListCall { - c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) - return c -} - -// OrderBy sets the optional parameter "orderBy": Column to use for -// sorting results -// -// Possible values: -// "deviceId" - Mobile Device serial number. -// "email" - Owner user email. -// "lastSync" - Last policy settings sync date time of the device. -// "model" - Mobile Device model. -// "name" - Owner user name. -// "os" - Mobile operating system. -// "status" - Status of the device. -// "type" - Type of the device. -func (c *MobiledevicesListCall) OrderBy(orderBy string) *MobiledevicesListCall { - c.urlParams_.Set("orderBy", orderBy) - return c -} - -// PageToken sets the optional parameter "pageToken": Token to specify -// next page in the list -func (c *MobiledevicesListCall) PageToken(pageToken string) *MobiledevicesListCall { - c.urlParams_.Set("pageToken", pageToken) - return c -} - -// Projection sets the optional parameter "projection": Restrict -// information returned to a set of selected fields. -// -// Possible values: -// "BASIC" - Includes only the basic metadata fields (e.g., deviceId, -// model, status, type, and status) -// "FULL" - Includes all metadata fields -func (c *MobiledevicesListCall) Projection(projection string) *MobiledevicesListCall { - c.urlParams_.Set("projection", projection) - return c -} - -// Query sets the optional parameter "query": Search string in the -// format given at -// http://support.google.com/a/bin/answer.py?hl=en&answer=1408863#search -func (c *MobiledevicesListCall) Query(query string) *MobiledevicesListCall { - c.urlParams_.Set("query", query) - return c -} - -// SortOrder sets the optional parameter "sortOrder": Whether to return -// results in ascending or descending order. Only of use when orderBy is -// also used -// -// Possible values: -// "ASCENDING" - Ascending order. -// "DESCENDING" - Descending order. -func (c *MobiledevicesListCall) SortOrder(sortOrder string) *MobiledevicesListCall { - c.urlParams_.Set("sortOrder", sortOrder) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *MobiledevicesListCall) Fields(s ...googleapi.Field) *MobiledevicesListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *MobiledevicesListCall) IfNoneMatch(entityTag string) *MobiledevicesListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *MobiledevicesListCall) Context(ctx context.Context) *MobiledevicesListCall { - c.ctx_ = ctx - return c -} - -func (c *MobiledevicesListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/devices/mobile") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.mobiledevices.list" call. -// Exactly one of *MobileDevices or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *MobileDevices.ServerResponse.Header or (if a response was returned -// at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *MobiledevicesListCall) Do(opts ...googleapi.CallOption) (*MobileDevices, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &MobileDevices{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve all Mobile Devices of a customer (paginated)", - // "httpMethod": "GET", - // "id": "directory.mobiledevices.list", - // "parameterOrder": [ - // "customerId" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "maxResults": { - // "description": "Maximum number of results to return. Default is 100", - // "format": "int32", - // "location": "query", - // "minimum": "1", - // "type": "integer" - // }, - // "orderBy": { - // "description": "Column to use for sorting results", - // "enum": [ - // "deviceId", - // "email", - // "lastSync", - // "model", - // "name", - // "os", - // "status", - // "type" - // ], - // "enumDescriptions": [ - // "Mobile Device serial number.", - // "Owner user email.", - // "Last policy settings sync date time of the device.", - // "Mobile Device model.", - // "Owner user name.", - // "Mobile operating system.", - // "Status of the device.", - // "Type of the device." - // ], - // "location": "query", - // "type": "string" - // }, - // "pageToken": { - // "description": "Token to specify next page in the list", - // "location": "query", - // "type": "string" - // }, - // "projection": { - // "description": "Restrict information returned to a set of selected fields.", - // "enum": [ - // "BASIC", - // "FULL" - // ], - // "enumDescriptions": [ - // "Includes only the basic metadata fields (e.g., deviceId, model, status, type, and status)", - // "Includes all metadata fields" - // ], - // "location": "query", - // "type": "string" - // }, - // "query": { - // "description": "Search string in the format given at http://support.google.com/a/bin/answer.py?hl=en\u0026answer=1408863#search", - // "location": "query", - // "type": "string" - // }, - // "sortOrder": { - // "description": "Whether to return results in ascending or descending order. Only of use when orderBy is also used", - // "enum": [ - // "ASCENDING", - // "DESCENDING" - // ], - // "enumDescriptions": [ - // "Ascending order.", - // "Descending order." - // ], - // "location": "query", - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/devices/mobile", - // "response": { - // "$ref": "MobileDevices" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.device.mobile", - // "https://www.googleapis.com/auth/admin.directory.device.mobile.action", - // "https://www.googleapis.com/auth/admin.directory.device.mobile.readonly" - // ] - // } - -} - -// Pages invokes f for each page of results. -// A non-nil error returned from f will halt the iteration. -// The provided context supersedes any context provided to the Context method. -func (c *MobiledevicesListCall) Pages(ctx context.Context, f func(*MobileDevices) error) error { - c.ctx_ = ctx - defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point - for { - x, err := c.Do() - if err != nil { - return err - } - if err := f(x); err != nil { - return err - } - if x.NextPageToken == "" { - return nil - } - c.PageToken(x.NextPageToken) - } -} - -// method id "directory.notifications.delete": - -type NotificationsDeleteCall struct { - s *Service - customer string - notificationId string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Deletes a notification -func (r *NotificationsService) Delete(customer string, notificationId string) *NotificationsDeleteCall { - c := &NotificationsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.notificationId = notificationId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *NotificationsDeleteCall) Fields(s ...googleapi.Field) *NotificationsDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *NotificationsDeleteCall) Context(ctx context.Context) *NotificationsDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *NotificationsDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/notifications/{notificationId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "notificationId": c.notificationId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.notifications.delete" call. -func (c *NotificationsDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Deletes a notification", - // "httpMethod": "DELETE", - // "id": "directory.notifications.delete", - // "parameterOrder": [ - // "customer", - // "notificationId" - // ], - // "parameters": { - // "customer": { - // "description": "The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "notificationId": { - // "description": "The unique ID of the notification.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/notifications/{notificationId}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.notifications" - // ] - // } - -} - -// method id "directory.notifications.get": - -type NotificationsGetCall struct { - s *Service - customer string - notificationId string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrieves a notification. -func (r *NotificationsService) Get(customer string, notificationId string) *NotificationsGetCall { - c := &NotificationsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.notificationId = notificationId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *NotificationsGetCall) Fields(s ...googleapi.Field) *NotificationsGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *NotificationsGetCall) IfNoneMatch(entityTag string) *NotificationsGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *NotificationsGetCall) Context(ctx context.Context) *NotificationsGetCall { - c.ctx_ = ctx - return c -} - -func (c *NotificationsGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/notifications/{notificationId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "notificationId": c.notificationId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.notifications.get" call. -// Exactly one of *Notification or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *Notification.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *NotificationsGetCall) Do(opts ...googleapi.CallOption) (*Notification, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Notification{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieves a notification.", - // "httpMethod": "GET", - // "id": "directory.notifications.get", - // "parameterOrder": [ - // "customer", - // "notificationId" - // ], - // "parameters": { - // "customer": { - // "description": "The unique ID for the customer's Google account. The customerId is also returned as part of the Users resource.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "notificationId": { - // "description": "The unique ID of the notification.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/notifications/{notificationId}", - // "response": { - // "$ref": "Notification" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.notifications" - // ] - // } - -} - -// method id "directory.notifications.list": - -type NotificationsListCall struct { - s *Service - customer string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Retrieves a list of notifications. -func (r *NotificationsService) List(customer string) *NotificationsListCall { - c := &NotificationsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - return c -} - -// Language sets the optional parameter "language": The ISO 639-1 code -// of the language notifications are returned in. The default is English -// (en). -func (c *NotificationsListCall) Language(language string) *NotificationsListCall { - c.urlParams_.Set("language", language) - return c -} - -// MaxResults sets the optional parameter "maxResults": Maximum number -// of notifications to return per page. The default is 100. -func (c *NotificationsListCall) MaxResults(maxResults int64) *NotificationsListCall { - c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) - return c -} - -// PageToken sets the optional parameter "pageToken": The token to -// specify the page of results to retrieve. -func (c *NotificationsListCall) PageToken(pageToken string) *NotificationsListCall { - c.urlParams_.Set("pageToken", pageToken) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *NotificationsListCall) Fields(s ...googleapi.Field) *NotificationsListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *NotificationsListCall) IfNoneMatch(entityTag string) *NotificationsListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *NotificationsListCall) Context(ctx context.Context) *NotificationsListCall { - c.ctx_ = ctx - return c -} - -func (c *NotificationsListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/notifications") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.notifications.list" call. -// Exactly one of *Notifications or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *Notifications.ServerResponse.Header or (if a response was returned -// at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *NotificationsListCall) Do(opts ...googleapi.CallOption) (*Notifications, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Notifications{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieves a list of notifications.", - // "httpMethod": "GET", - // "id": "directory.notifications.list", - // "parameterOrder": [ - // "customer" - // ], - // "parameters": { - // "customer": { - // "description": "The unique ID for the customer's Google account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "language": { - // "description": "The ISO 639-1 code of the language notifications are returned in. The default is English (en).", - // "location": "query", - // "type": "string" - // }, - // "maxResults": { - // "description": "Maximum number of notifications to return per page. The default is 100.", - // "format": "uint32", - // "location": "query", - // "type": "integer" - // }, - // "pageToken": { - // "description": "The token to specify the page of results to retrieve.", - // "location": "query", - // "type": "string" - // } - // }, - // "path": "customer/{customer}/notifications", - // "response": { - // "$ref": "Notifications" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.notifications" - // ] - // } - -} - -// Pages invokes f for each page of results. -// A non-nil error returned from f will halt the iteration. -// The provided context supersedes any context provided to the Context method. -func (c *NotificationsListCall) Pages(ctx context.Context, f func(*Notifications) error) error { - c.ctx_ = ctx - defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point - for { - x, err := c.Do() - if err != nil { - return err - } - if err := f(x); err != nil { - return err - } - if x.NextPageToken == "" { - return nil - } - c.PageToken(x.NextPageToken) - } -} - -// method id "directory.notifications.patch": - -type NotificationsPatchCall struct { - s *Service - customer string - notificationId string - notification *Notification - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Patch: Updates a notification. This method supports patch semantics. -func (r *NotificationsService) Patch(customer string, notificationId string, notification *Notification) *NotificationsPatchCall { - c := &NotificationsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.notificationId = notificationId - c.notification = notification - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *NotificationsPatchCall) Fields(s ...googleapi.Field) *NotificationsPatchCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *NotificationsPatchCall) Context(ctx context.Context) *NotificationsPatchCall { - c.ctx_ = ctx - return c -} - -func (c *NotificationsPatchCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.notification) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/notifications/{notificationId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PATCH", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "notificationId": c.notificationId, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.notifications.patch" call. -// Exactly one of *Notification or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *Notification.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *NotificationsPatchCall) Do(opts ...googleapi.CallOption) (*Notification, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Notification{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Updates a notification. This method supports patch semantics.", - // "httpMethod": "PATCH", - // "id": "directory.notifications.patch", - // "parameterOrder": [ - // "customer", - // "notificationId" - // ], - // "parameters": { - // "customer": { - // "description": "The unique ID for the customer's Google account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "notificationId": { - // "description": "The unique ID of the notification.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/notifications/{notificationId}", - // "request": { - // "$ref": "Notification" - // }, - // "response": { - // "$ref": "Notification" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.notifications" - // ] - // } - -} - -// method id "directory.notifications.update": - -type NotificationsUpdateCall struct { - s *Service - customer string - notificationId string - notification *Notification - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Update: Updates a notification. -func (r *NotificationsService) Update(customer string, notificationId string, notification *Notification) *NotificationsUpdateCall { - c := &NotificationsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.notificationId = notificationId - c.notification = notification - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *NotificationsUpdateCall) Fields(s ...googleapi.Field) *NotificationsUpdateCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *NotificationsUpdateCall) Context(ctx context.Context) *NotificationsUpdateCall { - c.ctx_ = ctx - return c -} - -func (c *NotificationsUpdateCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.notification) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/notifications/{notificationId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PUT", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "notificationId": c.notificationId, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.notifications.update" call. -// Exactly one of *Notification or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *Notification.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *NotificationsUpdateCall) Do(opts ...googleapi.CallOption) (*Notification, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Notification{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Updates a notification.", - // "httpMethod": "PUT", - // "id": "directory.notifications.update", - // "parameterOrder": [ - // "customer", - // "notificationId" - // ], - // "parameters": { - // "customer": { - // "description": "The unique ID for the customer's Google account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "notificationId": { - // "description": "The unique ID of the notification.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/notifications/{notificationId}", - // "request": { - // "$ref": "Notification" - // }, - // "response": { - // "$ref": "Notification" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.notifications" - // ] - // } - -} - -// method id "directory.orgunits.delete": - -type OrgunitsDeleteCall struct { - s *Service - customerId string - orgUnitPath []string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Remove Organization Unit -func (r *OrgunitsService) Delete(customerId string, orgUnitPath []string) *OrgunitsDeleteCall { - c := &OrgunitsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.orgUnitPath = append([]string{}, orgUnitPath...) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *OrgunitsDeleteCall) Fields(s ...googleapi.Field) *OrgunitsDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *OrgunitsDeleteCall) Context(ctx context.Context) *OrgunitsDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *OrgunitsDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/orgunits{/orgUnitPath*}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "orgUnitPath": c.orgUnitPath[0], - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.orgunits.delete" call. -func (c *OrgunitsDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Remove Organization Unit", - // "httpMethod": "DELETE", - // "id": "directory.orgunits.delete", - // "parameterOrder": [ - // "customerId", - // "orgUnitPath" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "orgUnitPath": { - // "description": "Full path of the organization unit or its Id", - // "location": "path", - // "repeated": true, - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/orgunits{/orgUnitPath*}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.orgunit" - // ] - // } - -} - -// method id "directory.orgunits.get": - -type OrgunitsGetCall struct { - s *Service - customerId string - orgUnitPath []string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrieve Organization Unit -func (r *OrgunitsService) Get(customerId string, orgUnitPath []string) *OrgunitsGetCall { - c := &OrgunitsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.orgUnitPath = append([]string{}, orgUnitPath...) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *OrgunitsGetCall) Fields(s ...googleapi.Field) *OrgunitsGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *OrgunitsGetCall) IfNoneMatch(entityTag string) *OrgunitsGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *OrgunitsGetCall) Context(ctx context.Context) *OrgunitsGetCall { - c.ctx_ = ctx - return c -} - -func (c *OrgunitsGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/orgunits{/orgUnitPath*}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "orgUnitPath": c.orgUnitPath[0], - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.orgunits.get" call. -// Exactly one of *OrgUnit or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *OrgUnit.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *OrgunitsGetCall) Do(opts ...googleapi.CallOption) (*OrgUnit, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &OrgUnit{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve Organization Unit", - // "httpMethod": "GET", - // "id": "directory.orgunits.get", - // "parameterOrder": [ - // "customerId", - // "orgUnitPath" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "orgUnitPath": { - // "description": "Full path of the organization unit or its Id", - // "location": "path", - // "repeated": true, - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/orgunits{/orgUnitPath*}", - // "response": { - // "$ref": "OrgUnit" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.orgunit", - // "https://www.googleapis.com/auth/admin.directory.orgunit.readonly" - // ] - // } - -} - -// method id "directory.orgunits.insert": - -type OrgunitsInsertCall struct { - s *Service - customerId string - orgunit *OrgUnit - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Insert: Add Organization Unit -func (r *OrgunitsService) Insert(customerId string, orgunit *OrgUnit) *OrgunitsInsertCall { - c := &OrgunitsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.orgunit = orgunit - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *OrgunitsInsertCall) Fields(s ...googleapi.Field) *OrgunitsInsertCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *OrgunitsInsertCall) Context(ctx context.Context) *OrgunitsInsertCall { - c.ctx_ = ctx - return c -} - -func (c *OrgunitsInsertCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.orgunit) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/orgunits") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.orgunits.insert" call. -// Exactly one of *OrgUnit or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *OrgUnit.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *OrgunitsInsertCall) Do(opts ...googleapi.CallOption) (*OrgUnit, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &OrgUnit{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Add Organization Unit", - // "httpMethod": "POST", - // "id": "directory.orgunits.insert", - // "parameterOrder": [ - // "customerId" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/orgunits", - // "request": { - // "$ref": "OrgUnit" - // }, - // "response": { - // "$ref": "OrgUnit" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.orgunit" - // ] - // } - -} - -// method id "directory.orgunits.list": - -type OrgunitsListCall struct { - s *Service - customerId string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Retrieve all Organization Units -func (r *OrgunitsService) List(customerId string) *OrgunitsListCall { - c := &OrgunitsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - return c -} - -// OrgUnitPath sets the optional parameter "orgUnitPath": the -// URL-encoded organization unit's path or its Id -func (c *OrgunitsListCall) OrgUnitPath(orgUnitPath string) *OrgunitsListCall { - c.urlParams_.Set("orgUnitPath", orgUnitPath) - return c -} - -// Type sets the optional parameter "type": Whether to return all -// sub-organizations or just immediate children -// -// Possible values: -// "all" - All sub-organization units. -// "children" - Immediate children only (default). -func (c *OrgunitsListCall) Type(type_ string) *OrgunitsListCall { - c.urlParams_.Set("type", type_) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *OrgunitsListCall) Fields(s ...googleapi.Field) *OrgunitsListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *OrgunitsListCall) IfNoneMatch(entityTag string) *OrgunitsListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *OrgunitsListCall) Context(ctx context.Context) *OrgunitsListCall { - c.ctx_ = ctx - return c -} - -func (c *OrgunitsListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/orgunits") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.orgunits.list" call. -// Exactly one of *OrgUnits or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *OrgUnits.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *OrgunitsListCall) Do(opts ...googleapi.CallOption) (*OrgUnits, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &OrgUnits{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve all Organization Units", - // "httpMethod": "GET", - // "id": "directory.orgunits.list", - // "parameterOrder": [ - // "customerId" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "orgUnitPath": { - // "default": "", - // "description": "the URL-encoded organization unit's path or its Id", - // "location": "query", - // "type": "string" - // }, - // "type": { - // "description": "Whether to return all sub-organizations or just immediate children", - // "enum": [ - // "all", - // "children" - // ], - // "enumDescriptions": [ - // "All sub-organization units.", - // "Immediate children only (default)." - // ], - // "location": "query", - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/orgunits", - // "response": { - // "$ref": "OrgUnits" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.orgunit", - // "https://www.googleapis.com/auth/admin.directory.orgunit.readonly" - // ] - // } - -} - -// method id "directory.orgunits.patch": - -type OrgunitsPatchCall struct { - s *Service - customerId string - orgUnitPath []string - orgunit *OrgUnit - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Patch: Update Organization Unit. This method supports patch -// semantics. -func (r *OrgunitsService) Patch(customerId string, orgUnitPath []string, orgunit *OrgUnit) *OrgunitsPatchCall { - c := &OrgunitsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.orgUnitPath = append([]string{}, orgUnitPath...) - c.orgunit = orgunit - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *OrgunitsPatchCall) Fields(s ...googleapi.Field) *OrgunitsPatchCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *OrgunitsPatchCall) Context(ctx context.Context) *OrgunitsPatchCall { - c.ctx_ = ctx - return c -} - -func (c *OrgunitsPatchCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.orgunit) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/orgunits{/orgUnitPath*}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PATCH", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "orgUnitPath": c.orgUnitPath[0], - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.orgunits.patch" call. -// Exactly one of *OrgUnit or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *OrgUnit.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *OrgunitsPatchCall) Do(opts ...googleapi.CallOption) (*OrgUnit, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &OrgUnit{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Update Organization Unit. This method supports patch semantics.", - // "httpMethod": "PATCH", - // "id": "directory.orgunits.patch", - // "parameterOrder": [ - // "customerId", - // "orgUnitPath" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "orgUnitPath": { - // "description": "Full path of the organization unit or its Id", - // "location": "path", - // "repeated": true, - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/orgunits{/orgUnitPath*}", - // "request": { - // "$ref": "OrgUnit" - // }, - // "response": { - // "$ref": "OrgUnit" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.orgunit" - // ] - // } - -} - -// method id "directory.orgunits.update": - -type OrgunitsUpdateCall struct { - s *Service - customerId string - orgUnitPath []string - orgunit *OrgUnit - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Update: Update Organization Unit -func (r *OrgunitsService) Update(customerId string, orgUnitPath []string, orgunit *OrgUnit) *OrgunitsUpdateCall { - c := &OrgunitsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.orgUnitPath = append([]string{}, orgUnitPath...) - c.orgunit = orgunit - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *OrgunitsUpdateCall) Fields(s ...googleapi.Field) *OrgunitsUpdateCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *OrgunitsUpdateCall) Context(ctx context.Context) *OrgunitsUpdateCall { - c.ctx_ = ctx - return c -} - -func (c *OrgunitsUpdateCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.orgunit) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/orgunits{/orgUnitPath*}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PUT", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "orgUnitPath": c.orgUnitPath[0], - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.orgunits.update" call. -// Exactly one of *OrgUnit or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *OrgUnit.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *OrgunitsUpdateCall) Do(opts ...googleapi.CallOption) (*OrgUnit, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &OrgUnit{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Update Organization Unit", - // "httpMethod": "PUT", - // "id": "directory.orgunits.update", - // "parameterOrder": [ - // "customerId", - // "orgUnitPath" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "orgUnitPath": { - // "description": "Full path of the organization unit or its Id", - // "location": "path", - // "repeated": true, - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/orgunits{/orgUnitPath*}", - // "request": { - // "$ref": "OrgUnit" - // }, - // "response": { - // "$ref": "OrgUnit" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.orgunit" - // ] - // } - -} - -// method id "directory.privileges.list": - -type PrivilegesListCall struct { - s *Service - customer string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Retrieves a paginated list of all privileges for a customer. -func (r *PrivilegesService) List(customer string) *PrivilegesListCall { - c := &PrivilegesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *PrivilegesListCall) Fields(s ...googleapi.Field) *PrivilegesListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *PrivilegesListCall) IfNoneMatch(entityTag string) *PrivilegesListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *PrivilegesListCall) Context(ctx context.Context) *PrivilegesListCall { - c.ctx_ = ctx - return c -} - -func (c *PrivilegesListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles/ALL/privileges") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.privileges.list" call. -// Exactly one of *Privileges or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *Privileges.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *PrivilegesListCall) Do(opts ...googleapi.CallOption) (*Privileges, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Privileges{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieves a paginated list of all privileges for a customer.", - // "httpMethod": "GET", - // "id": "directory.privileges.list", - // "parameterOrder": [ - // "customer" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable ID of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/roles/ALL/privileges", - // "response": { - // "$ref": "Privileges" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.rolemanagement", - // "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" - // ] - // } - -} - -// method id "directory.resources.calendars.delete": - -type ResourcesCalendarsDeleteCall struct { - s *Service - customer string - calendarResourceId string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Deletes a calendar resource. -func (r *ResourcesCalendarsService) Delete(customer string, calendarResourceId string) *ResourcesCalendarsDeleteCall { - c := &ResourcesCalendarsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.calendarResourceId = calendarResourceId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *ResourcesCalendarsDeleteCall) Fields(s ...googleapi.Field) *ResourcesCalendarsDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *ResourcesCalendarsDeleteCall) Context(ctx context.Context) *ResourcesCalendarsDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *ResourcesCalendarsDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/calendars/{calendarResourceId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "calendarResourceId": c.calendarResourceId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.resources.calendars.delete" call. -func (c *ResourcesCalendarsDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Deletes a calendar resource.", - // "httpMethod": "DELETE", - // "id": "directory.resources.calendars.delete", - // "parameterOrder": [ - // "customer", - // "calendarResourceId" - // ], - // "parameters": { - // "calendarResourceId": { - // "description": "The unique ID of the calendar resource to delete.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "customer": { - // "description": "The unique ID for the customer's Google account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/resources/calendars/{calendarResourceId}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.resource.calendar" - // ] - // } - -} - -// method id "directory.resources.calendars.get": - -type ResourcesCalendarsGetCall struct { - s *Service - customer string - calendarResourceId string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrieves a calendar resource. -func (r *ResourcesCalendarsService) Get(customer string, calendarResourceId string) *ResourcesCalendarsGetCall { - c := &ResourcesCalendarsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.calendarResourceId = calendarResourceId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *ResourcesCalendarsGetCall) Fields(s ...googleapi.Field) *ResourcesCalendarsGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *ResourcesCalendarsGetCall) IfNoneMatch(entityTag string) *ResourcesCalendarsGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *ResourcesCalendarsGetCall) Context(ctx context.Context) *ResourcesCalendarsGetCall { - c.ctx_ = ctx - return c -} - -func (c *ResourcesCalendarsGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/calendars/{calendarResourceId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "calendarResourceId": c.calendarResourceId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.resources.calendars.get" call. -// Exactly one of *CalendarResource or error will be non-nil. Any -// non-2xx status code is an error. Response headers are in either -// *CalendarResource.ServerResponse.Header or (if a response was -// returned at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *ResourcesCalendarsGetCall) Do(opts ...googleapi.CallOption) (*CalendarResource, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &CalendarResource{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieves a calendar resource.", - // "httpMethod": "GET", - // "id": "directory.resources.calendars.get", - // "parameterOrder": [ - // "customer", - // "calendarResourceId" - // ], - // "parameters": { - // "calendarResourceId": { - // "description": "The unique ID of the calendar resource to retrieve.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "customer": { - // "description": "The unique ID for the customer's Google account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/resources/calendars/{calendarResourceId}", - // "response": { - // "$ref": "CalendarResource" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.resource.calendar", - // "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" - // ] - // } - -} - -// method id "directory.resources.calendars.insert": - -type ResourcesCalendarsInsertCall struct { - s *Service - customer string - calendarresource *CalendarResource - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Insert: Inserts a calendar resource. -func (r *ResourcesCalendarsService) Insert(customer string, calendarresource *CalendarResource) *ResourcesCalendarsInsertCall { - c := &ResourcesCalendarsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.calendarresource = calendarresource - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *ResourcesCalendarsInsertCall) Fields(s ...googleapi.Field) *ResourcesCalendarsInsertCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *ResourcesCalendarsInsertCall) Context(ctx context.Context) *ResourcesCalendarsInsertCall { - c.ctx_ = ctx - return c -} - -func (c *ResourcesCalendarsInsertCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.calendarresource) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/calendars") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.resources.calendars.insert" call. -// Exactly one of *CalendarResource or error will be non-nil. Any -// non-2xx status code is an error. Response headers are in either -// *CalendarResource.ServerResponse.Header or (if a response was -// returned at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *ResourcesCalendarsInsertCall) Do(opts ...googleapi.CallOption) (*CalendarResource, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &CalendarResource{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Inserts a calendar resource.", - // "httpMethod": "POST", - // "id": "directory.resources.calendars.insert", - // "parameterOrder": [ - // "customer" - // ], - // "parameters": { - // "customer": { - // "description": "The unique ID for the customer's Google account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/resources/calendars", - // "request": { - // "$ref": "CalendarResource" - // }, - // "response": { - // "$ref": "CalendarResource" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.resource.calendar" - // ] - // } - -} - -// method id "directory.resources.calendars.list": - -type ResourcesCalendarsListCall struct { - s *Service - customer string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Retrieves a list of calendar resources for an account. -func (r *ResourcesCalendarsService) List(customer string) *ResourcesCalendarsListCall { - c := &ResourcesCalendarsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - return c -} - -// MaxResults sets the optional parameter "maxResults": Maximum number -// of results to return. -func (c *ResourcesCalendarsListCall) MaxResults(maxResults int64) *ResourcesCalendarsListCall { - c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) - return c -} - -// PageToken sets the optional parameter "pageToken": Token to specify -// the next page in the list. -func (c *ResourcesCalendarsListCall) PageToken(pageToken string) *ResourcesCalendarsListCall { - c.urlParams_.Set("pageToken", pageToken) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *ResourcesCalendarsListCall) Fields(s ...googleapi.Field) *ResourcesCalendarsListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *ResourcesCalendarsListCall) IfNoneMatch(entityTag string) *ResourcesCalendarsListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *ResourcesCalendarsListCall) Context(ctx context.Context) *ResourcesCalendarsListCall { - c.ctx_ = ctx - return c -} - -func (c *ResourcesCalendarsListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/calendars") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.resources.calendars.list" call. -// Exactly one of *CalendarResources or error will be non-nil. Any -// non-2xx status code is an error. Response headers are in either -// *CalendarResources.ServerResponse.Header or (if a response was -// returned at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *ResourcesCalendarsListCall) Do(opts ...googleapi.CallOption) (*CalendarResources, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &CalendarResources{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieves a list of calendar resources for an account.", - // "httpMethod": "GET", - // "id": "directory.resources.calendars.list", - // "parameterOrder": [ - // "customer" - // ], - // "parameters": { - // "customer": { - // "description": "The unique ID for the customer's Google account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "maxResults": { - // "description": "Maximum number of results to return.", - // "format": "int32", - // "location": "query", - // "maximum": "500", - // "minimum": "1", - // "type": "integer" - // }, - // "pageToken": { - // "description": "Token to specify the next page in the list.", - // "location": "query", - // "type": "string" - // } - // }, - // "path": "customer/{customer}/resources/calendars", - // "response": { - // "$ref": "CalendarResources" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.resource.calendar", - // "https://www.googleapis.com/auth/admin.directory.resource.calendar.readonly" - // ] - // } - -} - -// Pages invokes f for each page of results. -// A non-nil error returned from f will halt the iteration. -// The provided context supersedes any context provided to the Context method. -func (c *ResourcesCalendarsListCall) Pages(ctx context.Context, f func(*CalendarResources) error) error { - c.ctx_ = ctx - defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point - for { - x, err := c.Do() - if err != nil { - return err - } - if err := f(x); err != nil { - return err - } - if x.NextPageToken == "" { - return nil - } - c.PageToken(x.NextPageToken) - } -} - -// method id "directory.resources.calendars.patch": - -type ResourcesCalendarsPatchCall struct { - s *Service - customer string - calendarResourceId string - calendarresource *CalendarResource - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Patch: Updates a calendar resource. This method supports patch -// semantics. -func (r *ResourcesCalendarsService) Patch(customer string, calendarResourceId string, calendarresource *CalendarResource) *ResourcesCalendarsPatchCall { - c := &ResourcesCalendarsPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.calendarResourceId = calendarResourceId - c.calendarresource = calendarresource - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *ResourcesCalendarsPatchCall) Fields(s ...googleapi.Field) *ResourcesCalendarsPatchCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *ResourcesCalendarsPatchCall) Context(ctx context.Context) *ResourcesCalendarsPatchCall { - c.ctx_ = ctx - return c -} - -func (c *ResourcesCalendarsPatchCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.calendarresource) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/calendars/{calendarResourceId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PATCH", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "calendarResourceId": c.calendarResourceId, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.resources.calendars.patch" call. -// Exactly one of *CalendarResource or error will be non-nil. Any -// non-2xx status code is an error. Response headers are in either -// *CalendarResource.ServerResponse.Header or (if a response was -// returned at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *ResourcesCalendarsPatchCall) Do(opts ...googleapi.CallOption) (*CalendarResource, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &CalendarResource{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Updates a calendar resource. This method supports patch semantics.", - // "httpMethod": "PATCH", - // "id": "directory.resources.calendars.patch", - // "parameterOrder": [ - // "customer", - // "calendarResourceId" - // ], - // "parameters": { - // "calendarResourceId": { - // "description": "The unique ID of the calendar resource to update.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "customer": { - // "description": "The unique ID for the customer's Google account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/resources/calendars/{calendarResourceId}", - // "request": { - // "$ref": "CalendarResource" - // }, - // "response": { - // "$ref": "CalendarResource" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.resource.calendar" - // ] - // } - -} - -// method id "directory.resources.calendars.update": - -type ResourcesCalendarsUpdateCall struct { - s *Service - customer string - calendarResourceId string - calendarresource *CalendarResource - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Update: Updates a calendar resource. -func (r *ResourcesCalendarsService) Update(customer string, calendarResourceId string, calendarresource *CalendarResource) *ResourcesCalendarsUpdateCall { - c := &ResourcesCalendarsUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.calendarResourceId = calendarResourceId - c.calendarresource = calendarresource - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *ResourcesCalendarsUpdateCall) Fields(s ...googleapi.Field) *ResourcesCalendarsUpdateCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *ResourcesCalendarsUpdateCall) Context(ctx context.Context) *ResourcesCalendarsUpdateCall { - c.ctx_ = ctx - return c -} - -func (c *ResourcesCalendarsUpdateCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.calendarresource) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/resources/calendars/{calendarResourceId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PUT", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "calendarResourceId": c.calendarResourceId, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.resources.calendars.update" call. -// Exactly one of *CalendarResource or error will be non-nil. Any -// non-2xx status code is an error. Response headers are in either -// *CalendarResource.ServerResponse.Header or (if a response was -// returned at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *ResourcesCalendarsUpdateCall) Do(opts ...googleapi.CallOption) (*CalendarResource, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &CalendarResource{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Updates a calendar resource.", - // "httpMethod": "PUT", - // "id": "directory.resources.calendars.update", - // "parameterOrder": [ - // "customer", - // "calendarResourceId" - // ], - // "parameters": { - // "calendarResourceId": { - // "description": "The unique ID of the calendar resource to update.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "customer": { - // "description": "The unique ID for the customer's Google account. As an account administrator, you can also use the my_customer alias to represent your account's customer ID.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/resources/calendars/{calendarResourceId}", - // "request": { - // "$ref": "CalendarResource" - // }, - // "response": { - // "$ref": "CalendarResource" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.resource.calendar" - // ] - // } - -} - -// method id "directory.roleAssignments.delete": - -type RoleAssignmentsDeleteCall struct { - s *Service - customer string - roleAssignmentId string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Deletes a role assignment. -func (r *RoleAssignmentsService) Delete(customer string, roleAssignmentId string) *RoleAssignmentsDeleteCall { - c := &RoleAssignmentsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.roleAssignmentId = roleAssignmentId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *RoleAssignmentsDeleteCall) Fields(s ...googleapi.Field) *RoleAssignmentsDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *RoleAssignmentsDeleteCall) Context(ctx context.Context) *RoleAssignmentsDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *RoleAssignmentsDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roleassignments/{roleAssignmentId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "roleAssignmentId": c.roleAssignmentId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.roleAssignments.delete" call. -func (c *RoleAssignmentsDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Deletes a role assignment.", - // "httpMethod": "DELETE", - // "id": "directory.roleAssignments.delete", - // "parameterOrder": [ - // "customer", - // "roleAssignmentId" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable ID of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "roleAssignmentId": { - // "description": "Immutable ID of the role assignment.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/roleassignments/{roleAssignmentId}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.rolemanagement" - // ] - // } - -} - -// method id "directory.roleAssignments.get": - -type RoleAssignmentsGetCall struct { - s *Service - customer string - roleAssignmentId string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrieve a role assignment. -func (r *RoleAssignmentsService) Get(customer string, roleAssignmentId string) *RoleAssignmentsGetCall { - c := &RoleAssignmentsGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.roleAssignmentId = roleAssignmentId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *RoleAssignmentsGetCall) Fields(s ...googleapi.Field) *RoleAssignmentsGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *RoleAssignmentsGetCall) IfNoneMatch(entityTag string) *RoleAssignmentsGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *RoleAssignmentsGetCall) Context(ctx context.Context) *RoleAssignmentsGetCall { - c.ctx_ = ctx - return c -} - -func (c *RoleAssignmentsGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roleassignments/{roleAssignmentId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "roleAssignmentId": c.roleAssignmentId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.roleAssignments.get" call. -// Exactly one of *RoleAssignment or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *RoleAssignment.ServerResponse.Header or (if a response was returned -// at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *RoleAssignmentsGetCall) Do(opts ...googleapi.CallOption) (*RoleAssignment, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &RoleAssignment{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve a role assignment.", - // "httpMethod": "GET", - // "id": "directory.roleAssignments.get", - // "parameterOrder": [ - // "customer", - // "roleAssignmentId" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable ID of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "roleAssignmentId": { - // "description": "Immutable ID of the role assignment.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/roleassignments/{roleAssignmentId}", - // "response": { - // "$ref": "RoleAssignment" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.rolemanagement", - // "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" - // ] - // } - -} - -// method id "directory.roleAssignments.insert": - -type RoleAssignmentsInsertCall struct { - s *Service - customer string - roleassignment *RoleAssignment - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Insert: Creates a role assignment. -func (r *RoleAssignmentsService) Insert(customer string, roleassignment *RoleAssignment) *RoleAssignmentsInsertCall { - c := &RoleAssignmentsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.roleassignment = roleassignment - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *RoleAssignmentsInsertCall) Fields(s ...googleapi.Field) *RoleAssignmentsInsertCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *RoleAssignmentsInsertCall) Context(ctx context.Context) *RoleAssignmentsInsertCall { - c.ctx_ = ctx - return c -} - -func (c *RoleAssignmentsInsertCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.roleassignment) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roleassignments") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.roleAssignments.insert" call. -// Exactly one of *RoleAssignment or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *RoleAssignment.ServerResponse.Header or (if a response was returned -// at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *RoleAssignmentsInsertCall) Do(opts ...googleapi.CallOption) (*RoleAssignment, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &RoleAssignment{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Creates a role assignment.", - // "httpMethod": "POST", - // "id": "directory.roleAssignments.insert", - // "parameterOrder": [ - // "customer" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable ID of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/roleassignments", - // "request": { - // "$ref": "RoleAssignment" - // }, - // "response": { - // "$ref": "RoleAssignment" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.rolemanagement" - // ] - // } - -} - -// method id "directory.roleAssignments.list": - -type RoleAssignmentsListCall struct { - s *Service - customer string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Retrieves a paginated list of all roleAssignments. -func (r *RoleAssignmentsService) List(customer string) *RoleAssignmentsListCall { - c := &RoleAssignmentsListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - return c -} - -// MaxResults sets the optional parameter "maxResults": Maximum number -// of results to return. -func (c *RoleAssignmentsListCall) MaxResults(maxResults int64) *RoleAssignmentsListCall { - c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) - return c -} - -// PageToken sets the optional parameter "pageToken": Token to specify -// the next page in the list. -func (c *RoleAssignmentsListCall) PageToken(pageToken string) *RoleAssignmentsListCall { - c.urlParams_.Set("pageToken", pageToken) - return c -} - -// RoleId sets the optional parameter "roleId": Immutable ID of a role. -// If included in the request, returns only role assignments containing -// this role ID. -func (c *RoleAssignmentsListCall) RoleId(roleId string) *RoleAssignmentsListCall { - c.urlParams_.Set("roleId", roleId) - return c -} - -// UserKey sets the optional parameter "userKey": The user's primary -// email address, alias email address, or unique user ID. If included in -// the request, returns role assignments only for this user. -func (c *RoleAssignmentsListCall) UserKey(userKey string) *RoleAssignmentsListCall { - c.urlParams_.Set("userKey", userKey) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *RoleAssignmentsListCall) Fields(s ...googleapi.Field) *RoleAssignmentsListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *RoleAssignmentsListCall) IfNoneMatch(entityTag string) *RoleAssignmentsListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *RoleAssignmentsListCall) Context(ctx context.Context) *RoleAssignmentsListCall { - c.ctx_ = ctx - return c -} - -func (c *RoleAssignmentsListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roleassignments") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.roleAssignments.list" call. -// Exactly one of *RoleAssignments or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *RoleAssignments.ServerResponse.Header or (if a response was returned -// at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *RoleAssignmentsListCall) Do(opts ...googleapi.CallOption) (*RoleAssignments, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &RoleAssignments{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieves a paginated list of all roleAssignments.", - // "httpMethod": "GET", - // "id": "directory.roleAssignments.list", - // "parameterOrder": [ - // "customer" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable ID of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "maxResults": { - // "description": "Maximum number of results to return.", - // "format": "int32", - // "location": "query", - // "maximum": "200", - // "minimum": "1", - // "type": "integer" - // }, - // "pageToken": { - // "description": "Token to specify the next page in the list.", - // "location": "query", - // "type": "string" - // }, - // "roleId": { - // "description": "Immutable ID of a role. If included in the request, returns only role assignments containing this role ID.", - // "location": "query", - // "type": "string" - // }, - // "userKey": { - // "description": "The user's primary email address, alias email address, or unique user ID. If included in the request, returns role assignments only for this user.", - // "location": "query", - // "type": "string" - // } - // }, - // "path": "customer/{customer}/roleassignments", - // "response": { - // "$ref": "RoleAssignments" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.rolemanagement", - // "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" - // ] - // } - -} - -// Pages invokes f for each page of results. -// A non-nil error returned from f will halt the iteration. -// The provided context supersedes any context provided to the Context method. -func (c *RoleAssignmentsListCall) Pages(ctx context.Context, f func(*RoleAssignments) error) error { - c.ctx_ = ctx - defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point - for { - x, err := c.Do() - if err != nil { - return err - } - if err := f(x); err != nil { - return err - } - if x.NextPageToken == "" { - return nil - } - c.PageToken(x.NextPageToken) - } -} - -// method id "directory.roles.delete": - -type RolesDeleteCall struct { - s *Service - customer string - roleId string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Deletes a role. -func (r *RolesService) Delete(customer string, roleId string) *RolesDeleteCall { - c := &RolesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.roleId = roleId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *RolesDeleteCall) Fields(s ...googleapi.Field) *RolesDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *RolesDeleteCall) Context(ctx context.Context) *RolesDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *RolesDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles/{roleId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "roleId": c.roleId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.roles.delete" call. -func (c *RolesDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Deletes a role.", - // "httpMethod": "DELETE", - // "id": "directory.roles.delete", - // "parameterOrder": [ - // "customer", - // "roleId" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable ID of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "roleId": { - // "description": "Immutable ID of the role.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/roles/{roleId}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.rolemanagement" - // ] - // } - -} - -// method id "directory.roles.get": - -type RolesGetCall struct { - s *Service - customer string - roleId string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrieves a role. -func (r *RolesService) Get(customer string, roleId string) *RolesGetCall { - c := &RolesGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.roleId = roleId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *RolesGetCall) Fields(s ...googleapi.Field) *RolesGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *RolesGetCall) IfNoneMatch(entityTag string) *RolesGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *RolesGetCall) Context(ctx context.Context) *RolesGetCall { - c.ctx_ = ctx - return c -} - -func (c *RolesGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles/{roleId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "roleId": c.roleId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.roles.get" call. -// Exactly one of *Role or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Role.ServerResponse.Header or (if a response was returned at all) in -// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check -// whether the returned error was because http.StatusNotModified was -// returned. -func (c *RolesGetCall) Do(opts ...googleapi.CallOption) (*Role, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Role{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieves a role.", - // "httpMethod": "GET", - // "id": "directory.roles.get", - // "parameterOrder": [ - // "customer", - // "roleId" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable ID of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "roleId": { - // "description": "Immutable ID of the role.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/roles/{roleId}", - // "response": { - // "$ref": "Role" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.rolemanagement", - // "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" - // ] - // } - -} - -// method id "directory.roles.insert": - -type RolesInsertCall struct { - s *Service - customer string - role *Role - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Insert: Creates a role. -func (r *RolesService) Insert(customer string, role *Role) *RolesInsertCall { - c := &RolesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.role = role - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *RolesInsertCall) Fields(s ...googleapi.Field) *RolesInsertCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *RolesInsertCall) Context(ctx context.Context) *RolesInsertCall { - c.ctx_ = ctx - return c -} - -func (c *RolesInsertCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.role) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.roles.insert" call. -// Exactly one of *Role or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Role.ServerResponse.Header or (if a response was returned at all) in -// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check -// whether the returned error was because http.StatusNotModified was -// returned. -func (c *RolesInsertCall) Do(opts ...googleapi.CallOption) (*Role, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Role{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Creates a role.", - // "httpMethod": "POST", - // "id": "directory.roles.insert", - // "parameterOrder": [ - // "customer" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable ID of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/roles", - // "request": { - // "$ref": "Role" - // }, - // "response": { - // "$ref": "Role" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.rolemanagement" - // ] - // } - -} - -// method id "directory.roles.list": - -type RolesListCall struct { - s *Service - customer string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Retrieves a paginated list of all the roles in a domain. -func (r *RolesService) List(customer string) *RolesListCall { - c := &RolesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - return c -} - -// MaxResults sets the optional parameter "maxResults": Maximum number -// of results to return. -func (c *RolesListCall) MaxResults(maxResults int64) *RolesListCall { - c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) - return c -} - -// PageToken sets the optional parameter "pageToken": Token to specify -// the next page in the list. -func (c *RolesListCall) PageToken(pageToken string) *RolesListCall { - c.urlParams_.Set("pageToken", pageToken) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *RolesListCall) Fields(s ...googleapi.Field) *RolesListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *RolesListCall) IfNoneMatch(entityTag string) *RolesListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *RolesListCall) Context(ctx context.Context) *RolesListCall { - c.ctx_ = ctx - return c -} - -func (c *RolesListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.roles.list" call. -// Exactly one of *Roles or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Roles.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *RolesListCall) Do(opts ...googleapi.CallOption) (*Roles, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Roles{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieves a paginated list of all the roles in a domain.", - // "httpMethod": "GET", - // "id": "directory.roles.list", - // "parameterOrder": [ - // "customer" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable id of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "maxResults": { - // "description": "Maximum number of results to return.", - // "format": "int32", - // "location": "query", - // "maximum": "100", - // "minimum": "1", - // "type": "integer" - // }, - // "pageToken": { - // "description": "Token to specify the next page in the list.", - // "location": "query", - // "type": "string" - // } - // }, - // "path": "customer/{customer}/roles", - // "response": { - // "$ref": "Roles" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.rolemanagement", - // "https://www.googleapis.com/auth/admin.directory.rolemanagement.readonly" - // ] - // } - -} - -// Pages invokes f for each page of results. -// A non-nil error returned from f will halt the iteration. -// The provided context supersedes any context provided to the Context method. -func (c *RolesListCall) Pages(ctx context.Context, f func(*Roles) error) error { - c.ctx_ = ctx - defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point - for { - x, err := c.Do() - if err != nil { - return err - } - if err := f(x); err != nil { - return err - } - if x.NextPageToken == "" { - return nil - } - c.PageToken(x.NextPageToken) - } -} - -// method id "directory.roles.patch": - -type RolesPatchCall struct { - s *Service - customer string - roleId string - role *Role - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Patch: Updates a role. This method supports patch semantics. -func (r *RolesService) Patch(customer string, roleId string, role *Role) *RolesPatchCall { - c := &RolesPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.roleId = roleId - c.role = role - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *RolesPatchCall) Fields(s ...googleapi.Field) *RolesPatchCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *RolesPatchCall) Context(ctx context.Context) *RolesPatchCall { - c.ctx_ = ctx - return c -} - -func (c *RolesPatchCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.role) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles/{roleId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PATCH", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "roleId": c.roleId, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.roles.patch" call. -// Exactly one of *Role or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Role.ServerResponse.Header or (if a response was returned at all) in -// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check -// whether the returned error was because http.StatusNotModified was -// returned. -func (c *RolesPatchCall) Do(opts ...googleapi.CallOption) (*Role, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Role{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Updates a role. This method supports patch semantics.", - // "httpMethod": "PATCH", - // "id": "directory.roles.patch", - // "parameterOrder": [ - // "customer", - // "roleId" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable ID of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "roleId": { - // "description": "Immutable ID of the role.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/roles/{roleId}", - // "request": { - // "$ref": "Role" - // }, - // "response": { - // "$ref": "Role" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.rolemanagement" - // ] - // } - -} - -// method id "directory.roles.update": - -type RolesUpdateCall struct { - s *Service - customer string - roleId string - role *Role - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Update: Updates a role. -func (r *RolesService) Update(customer string, roleId string, role *Role) *RolesUpdateCall { - c := &RolesUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customer = customer - c.roleId = roleId - c.role = role - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *RolesUpdateCall) Fields(s ...googleapi.Field) *RolesUpdateCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *RolesUpdateCall) Context(ctx context.Context) *RolesUpdateCall { - c.ctx_ = ctx - return c -} - -func (c *RolesUpdateCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.role) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customer}/roles/{roleId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PUT", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customer": c.customer, - "roleId": c.roleId, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.roles.update" call. -// Exactly one of *Role or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Role.ServerResponse.Header or (if a response was returned at all) in -// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check -// whether the returned error was because http.StatusNotModified was -// returned. -func (c *RolesUpdateCall) Do(opts ...googleapi.CallOption) (*Role, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Role{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Updates a role.", - // "httpMethod": "PUT", - // "id": "directory.roles.update", - // "parameterOrder": [ - // "customer", - // "roleId" - // ], - // "parameters": { - // "customer": { - // "description": "Immutable ID of the Google Apps account.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "roleId": { - // "description": "Immutable ID of the role.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customer}/roles/{roleId}", - // "request": { - // "$ref": "Role" - // }, - // "response": { - // "$ref": "Role" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.rolemanagement" - // ] - // } - -} - -// method id "directory.schemas.delete": - -type SchemasDeleteCall struct { - s *Service - customerId string - schemaKey string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Delete schema -func (r *SchemasService) Delete(customerId string, schemaKey string) *SchemasDeleteCall { - c := &SchemasDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.schemaKey = schemaKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *SchemasDeleteCall) Fields(s ...googleapi.Field) *SchemasDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *SchemasDeleteCall) Context(ctx context.Context) *SchemasDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *SchemasDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/schemas/{schemaKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "schemaKey": c.schemaKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.schemas.delete" call. -func (c *SchemasDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Delete schema", - // "httpMethod": "DELETE", - // "id": "directory.schemas.delete", - // "parameterOrder": [ - // "customerId", - // "schemaKey" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "schemaKey": { - // "description": "Name or immutable Id of the schema", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/schemas/{schemaKey}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.userschema" - // ] - // } - -} - -// method id "directory.schemas.get": - -type SchemasGetCall struct { - s *Service - customerId string - schemaKey string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrieve schema -func (r *SchemasService) Get(customerId string, schemaKey string) *SchemasGetCall { - c := &SchemasGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.schemaKey = schemaKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *SchemasGetCall) Fields(s ...googleapi.Field) *SchemasGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *SchemasGetCall) IfNoneMatch(entityTag string) *SchemasGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *SchemasGetCall) Context(ctx context.Context) *SchemasGetCall { - c.ctx_ = ctx - return c -} - -func (c *SchemasGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/schemas/{schemaKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "schemaKey": c.schemaKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.schemas.get" call. -// Exactly one of *Schema or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Schema.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *SchemasGetCall) Do(opts ...googleapi.CallOption) (*Schema, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Schema{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve schema", - // "httpMethod": "GET", - // "id": "directory.schemas.get", - // "parameterOrder": [ - // "customerId", - // "schemaKey" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "schemaKey": { - // "description": "Name or immutable Id of the schema", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/schemas/{schemaKey}", - // "response": { - // "$ref": "Schema" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.userschema", - // "https://www.googleapis.com/auth/admin.directory.userschema.readonly" - // ] - // } - -} - -// method id "directory.schemas.insert": - -type SchemasInsertCall struct { - s *Service - customerId string - schema *Schema - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Insert: Create schema. -func (r *SchemasService) Insert(customerId string, schema *Schema) *SchemasInsertCall { - c := &SchemasInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.schema = schema - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *SchemasInsertCall) Fields(s ...googleapi.Field) *SchemasInsertCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *SchemasInsertCall) Context(ctx context.Context) *SchemasInsertCall { - c.ctx_ = ctx - return c -} - -func (c *SchemasInsertCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.schema) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/schemas") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.schemas.insert" call. -// Exactly one of *Schema or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Schema.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *SchemasInsertCall) Do(opts ...googleapi.CallOption) (*Schema, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Schema{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Create schema.", - // "httpMethod": "POST", - // "id": "directory.schemas.insert", - // "parameterOrder": [ - // "customerId" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/schemas", - // "request": { - // "$ref": "Schema" - // }, - // "response": { - // "$ref": "Schema" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.userschema" - // ] - // } - -} - -// method id "directory.schemas.list": - -type SchemasListCall struct { - s *Service - customerId string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Retrieve all schemas for a customer -func (r *SchemasService) List(customerId string) *SchemasListCall { - c := &SchemasListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *SchemasListCall) Fields(s ...googleapi.Field) *SchemasListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *SchemasListCall) IfNoneMatch(entityTag string) *SchemasListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *SchemasListCall) Context(ctx context.Context) *SchemasListCall { - c.ctx_ = ctx - return c -} - -func (c *SchemasListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/schemas") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.schemas.list" call. -// Exactly one of *Schemas or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Schemas.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *SchemasListCall) Do(opts ...googleapi.CallOption) (*Schemas, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Schemas{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve all schemas for a customer", - // "httpMethod": "GET", - // "id": "directory.schemas.list", - // "parameterOrder": [ - // "customerId" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/schemas", - // "response": { - // "$ref": "Schemas" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.userschema", - // "https://www.googleapis.com/auth/admin.directory.userschema.readonly" - // ] - // } - -} - -// method id "directory.schemas.patch": - -type SchemasPatchCall struct { - s *Service - customerId string - schemaKey string - schema *Schema - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Patch: Update schema. This method supports patch semantics. -func (r *SchemasService) Patch(customerId string, schemaKey string, schema *Schema) *SchemasPatchCall { - c := &SchemasPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.schemaKey = schemaKey - c.schema = schema - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *SchemasPatchCall) Fields(s ...googleapi.Field) *SchemasPatchCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *SchemasPatchCall) Context(ctx context.Context) *SchemasPatchCall { - c.ctx_ = ctx - return c -} - -func (c *SchemasPatchCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.schema) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/schemas/{schemaKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PATCH", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "schemaKey": c.schemaKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.schemas.patch" call. -// Exactly one of *Schema or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Schema.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *SchemasPatchCall) Do(opts ...googleapi.CallOption) (*Schema, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Schema{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Update schema. This method supports patch semantics.", - // "httpMethod": "PATCH", - // "id": "directory.schemas.patch", - // "parameterOrder": [ - // "customerId", - // "schemaKey" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "schemaKey": { - // "description": "Name or immutable Id of the schema.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/schemas/{schemaKey}", - // "request": { - // "$ref": "Schema" - // }, - // "response": { - // "$ref": "Schema" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.userschema" - // ] - // } - -} - -// method id "directory.schemas.update": - -type SchemasUpdateCall struct { - s *Service - customerId string - schemaKey string - schema *Schema - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Update: Update schema -func (r *SchemasService) Update(customerId string, schemaKey string, schema *Schema) *SchemasUpdateCall { - c := &SchemasUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.customerId = customerId - c.schemaKey = schemaKey - c.schema = schema - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *SchemasUpdateCall) Fields(s ...googleapi.Field) *SchemasUpdateCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *SchemasUpdateCall) Context(ctx context.Context) *SchemasUpdateCall { - c.ctx_ = ctx - return c -} - -func (c *SchemasUpdateCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.schema) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "customer/{customerId}/schemas/{schemaKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PUT", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "customerId": c.customerId, - "schemaKey": c.schemaKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.schemas.update" call. -// Exactly one of *Schema or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Schema.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *SchemasUpdateCall) Do(opts ...googleapi.CallOption) (*Schema, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Schema{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Update schema", - // "httpMethod": "PUT", - // "id": "directory.schemas.update", - // "parameterOrder": [ - // "customerId", - // "schemaKey" - // ], - // "parameters": { - // "customerId": { - // "description": "Immutable id of the Google Apps account", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "schemaKey": { - // "description": "Name or immutable Id of the schema.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "customer/{customerId}/schemas/{schemaKey}", - // "request": { - // "$ref": "Schema" - // }, - // "response": { - // "$ref": "Schema" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.userschema" - // ] - // } - -} - -// method id "directory.tokens.delete": - -type TokensDeleteCall struct { - s *Service - userKey string - clientId string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Delete all access tokens issued by a user for an application. -func (r *TokensService) Delete(userKey string, clientId string) *TokensDeleteCall { - c := &TokensDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - c.clientId = clientId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *TokensDeleteCall) Fields(s ...googleapi.Field) *TokensDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *TokensDeleteCall) Context(ctx context.Context) *TokensDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *TokensDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/tokens/{clientId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - "clientId": c.clientId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.tokens.delete" call. -func (c *TokensDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Delete all access tokens issued by a user for an application.", - // "httpMethod": "DELETE", - // "id": "directory.tokens.delete", - // "parameterOrder": [ - // "userKey", - // "clientId" - // ], - // "parameters": { - // "clientId": { - // "description": "The Client ID of the application the token is issued to.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "userKey": { - // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/tokens/{clientId}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user.security" - // ] - // } - -} - -// method id "directory.tokens.get": - -type TokensGetCall struct { - s *Service - userKey string - clientId string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Get information about an access token issued by a user. -func (r *TokensService) Get(userKey string, clientId string) *TokensGetCall { - c := &TokensGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - c.clientId = clientId - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *TokensGetCall) Fields(s ...googleapi.Field) *TokensGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *TokensGetCall) IfNoneMatch(entityTag string) *TokensGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *TokensGetCall) Context(ctx context.Context) *TokensGetCall { - c.ctx_ = ctx - return c -} - -func (c *TokensGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/tokens/{clientId}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - "clientId": c.clientId, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.tokens.get" call. -// Exactly one of *Token or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Token.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *TokensGetCall) Do(opts ...googleapi.CallOption) (*Token, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Token{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Get information about an access token issued by a user.", - // "httpMethod": "GET", - // "id": "directory.tokens.get", - // "parameterOrder": [ - // "userKey", - // "clientId" - // ], - // "parameters": { - // "clientId": { - // "description": "The Client ID of the application the token is issued to.", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "userKey": { - // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/tokens/{clientId}", - // "response": { - // "$ref": "Token" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user.security" - // ] - // } - -} - -// method id "directory.tokens.list": - -type TokensListCall struct { - s *Service - userKey string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Returns the set of tokens specified user has issued to 3rd -// party applications. -func (r *TokensService) List(userKey string) *TokensListCall { - c := &TokensListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *TokensListCall) Fields(s ...googleapi.Field) *TokensListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *TokensListCall) IfNoneMatch(entityTag string) *TokensListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *TokensListCall) Context(ctx context.Context) *TokensListCall { - c.ctx_ = ctx - return c -} - -func (c *TokensListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/tokens") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.tokens.list" call. -// Exactly one of *Tokens or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Tokens.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *TokensListCall) Do(opts ...googleapi.CallOption) (*Tokens, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Tokens{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Returns the set of tokens specified user has issued to 3rd party applications.", - // "httpMethod": "GET", - // "id": "directory.tokens.list", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/tokens", - // "response": { - // "$ref": "Tokens" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user.security" - // ] - // } - -} - -// method id "directory.users.delete": - -type UsersDeleteCall struct { - s *Service - userKey string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Delete user -func (r *UsersService) Delete(userKey string) *UsersDeleteCall { - c := &UsersDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersDeleteCall) Fields(s ...googleapi.Field) *UsersDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersDeleteCall) Context(ctx context.Context) *UsersDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *UsersDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.delete" call. -func (c *UsersDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Delete user", - // "httpMethod": "DELETE", - // "id": "directory.users.delete", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Email or immutable Id of the user", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user" - // ] - // } - -} - -// method id "directory.users.get": - -type UsersGetCall struct { - s *Service - userKey string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: retrieve user -func (r *UsersService) Get(userKey string) *UsersGetCall { - c := &UsersGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - return c -} - -// CustomFieldMask sets the optional parameter "customFieldMask": -// Comma-separated list of schema names. All fields from these schemas -// are fetched. This should only be set when projection=custom. -func (c *UsersGetCall) CustomFieldMask(customFieldMask string) *UsersGetCall { - c.urlParams_.Set("customFieldMask", customFieldMask) - return c -} - -// Projection sets the optional parameter "projection": What subset of -// fields to fetch for this user. -// -// Possible values: -// "basic" (default) - Do not include any custom fields for the user. -// "custom" - Include custom fields from schemas mentioned in -// customFieldMask. -// "full" - Include all fields associated with this user. -func (c *UsersGetCall) Projection(projection string) *UsersGetCall { - c.urlParams_.Set("projection", projection) - return c -} - -// ViewType sets the optional parameter "viewType": Whether to fetch the -// ADMIN_VIEW or DOMAIN_PUBLIC view of the user. -// -// Possible values: -// "admin_view" (default) - Fetches the ADMIN_VIEW of the user. -// "domain_public" - Fetches the DOMAIN_PUBLIC view of the user. -func (c *UsersGetCall) ViewType(viewType string) *UsersGetCall { - c.urlParams_.Set("viewType", viewType) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersGetCall) Fields(s ...googleapi.Field) *UsersGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *UsersGetCall) IfNoneMatch(entityTag string) *UsersGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersGetCall) Context(ctx context.Context) *UsersGetCall { - c.ctx_ = ctx - return c -} - -func (c *UsersGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.get" call. -// Exactly one of *User or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *User.ServerResponse.Header or (if a response was returned at all) in -// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check -// whether the returned error was because http.StatusNotModified was -// returned. -func (c *UsersGetCall) Do(opts ...googleapi.CallOption) (*User, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &User{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "retrieve user", - // "httpMethod": "GET", - // "id": "directory.users.get", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "customFieldMask": { - // "description": "Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.", - // "location": "query", - // "type": "string" - // }, - // "projection": { - // "default": "basic", - // "description": "What subset of fields to fetch for this user.", - // "enum": [ - // "basic", - // "custom", - // "full" - // ], - // "enumDescriptions": [ - // "Do not include any custom fields for the user.", - // "Include custom fields from schemas mentioned in customFieldMask.", - // "Include all fields associated with this user." - // ], - // "location": "query", - // "type": "string" - // }, - // "userKey": { - // "description": "Email or immutable Id of the user", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "viewType": { - // "default": "admin_view", - // "description": "Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.", - // "enum": [ - // "admin_view", - // "domain_public" - // ], - // "enumDescriptions": [ - // "Fetches the ADMIN_VIEW of the user.", - // "Fetches the DOMAIN_PUBLIC view of the user." - // ], - // "location": "query", - // "type": "string" - // } - // }, - // "path": "users/{userKey}", - // "response": { - // "$ref": "User" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user", - // "https://www.googleapis.com/auth/admin.directory.user.readonly" - // ] - // } - -} - -// method id "directory.users.insert": - -type UsersInsertCall struct { - s *Service - user *User - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Insert: create user. -func (r *UsersService) Insert(user *User) *UsersInsertCall { - c := &UsersInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.user = user - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersInsertCall) Fields(s ...googleapi.Field) *UsersInsertCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersInsertCall) Context(ctx context.Context) *UsersInsertCall { - c.ctx_ = ctx - return c -} - -func (c *UsersInsertCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.user) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.SetOpaque(req.URL) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.insert" call. -// Exactly one of *User or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *User.ServerResponse.Header or (if a response was returned at all) in -// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check -// whether the returned error was because http.StatusNotModified was -// returned. -func (c *UsersInsertCall) Do(opts ...googleapi.CallOption) (*User, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &User{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "create user.", - // "httpMethod": "POST", - // "id": "directory.users.insert", - // "path": "users", - // "request": { - // "$ref": "User" - // }, - // "response": { - // "$ref": "User" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user" - // ] - // } - -} - -// method id "directory.users.list": - -type UsersListCall struct { - s *Service - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Retrieve either deleted users or all users in a domain -// (paginated) -func (r *UsersService) List() *UsersListCall { - c := &UsersListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - return c -} - -// CustomFieldMask sets the optional parameter "customFieldMask": -// Comma-separated list of schema names. All fields from these schemas -// are fetched. This should only be set when projection=custom. -func (c *UsersListCall) CustomFieldMask(customFieldMask string) *UsersListCall { - c.urlParams_.Set("customFieldMask", customFieldMask) - return c -} - -// Customer sets the optional parameter "customer": Immutable id of the -// Google Apps account. In case of multi-domain, to fetch all users for -// a customer, fill this field instead of domain. -func (c *UsersListCall) Customer(customer string) *UsersListCall { - c.urlParams_.Set("customer", customer) - return c -} - -// Domain sets the optional parameter "domain": Name of the domain. Fill -// this field to get users from only this domain. To return all users in -// a multi-domain fill customer field instead. -func (c *UsersListCall) Domain(domain string) *UsersListCall { - c.urlParams_.Set("domain", domain) - return c -} - -// Event sets the optional parameter "event": Event on which -// subscription is intended (if subscribing) -// -// Possible values: -// "add" - User Created Event -// "delete" - User Deleted Event -// "makeAdmin" - User Admin Status Change Event -// "undelete" - User Undeleted Event -// "update" - User Updated Event -func (c *UsersListCall) Event(event string) *UsersListCall { - c.urlParams_.Set("event", event) - return c -} - -// MaxResults sets the optional parameter "maxResults": Maximum number -// of results to return. Default is 100. Max allowed is 500 -func (c *UsersListCall) MaxResults(maxResults int64) *UsersListCall { - c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) - return c -} - -// OrderBy sets the optional parameter "orderBy": Column to use for -// sorting results -// -// Possible values: -// "email" - Primary email of the user. -// "familyName" - User's family name. -// "givenName" - User's given name. -func (c *UsersListCall) OrderBy(orderBy string) *UsersListCall { - c.urlParams_.Set("orderBy", orderBy) - return c -} - -// PageToken sets the optional parameter "pageToken": Token to specify -// next page in the list -func (c *UsersListCall) PageToken(pageToken string) *UsersListCall { - c.urlParams_.Set("pageToken", pageToken) - return c -} - -// Projection sets the optional parameter "projection": What subset of -// fields to fetch for this user. -// -// Possible values: -// "basic" (default) - Do not include any custom fields for the user. -// "custom" - Include custom fields from schemas mentioned in -// customFieldMask. -// "full" - Include all fields associated with this user. -func (c *UsersListCall) Projection(projection string) *UsersListCall { - c.urlParams_.Set("projection", projection) - return c -} - -// Query sets the optional parameter "query": Query string search. -// Should be of the form "". Complete documentation is at -// https://developers.google.com/admin-sdk/directory/v1/guides/search-users -func (c *UsersListCall) Query(query string) *UsersListCall { - c.urlParams_.Set("query", query) - return c -} - -// ShowDeleted sets the optional parameter "showDeleted": If set to true -// retrieves the list of deleted users. Default is false -func (c *UsersListCall) ShowDeleted(showDeleted string) *UsersListCall { - c.urlParams_.Set("showDeleted", showDeleted) - return c -} - -// SortOrder sets the optional parameter "sortOrder": Whether to return -// results in ascending or descending order. -// -// Possible values: -// "ASCENDING" - Ascending order. -// "DESCENDING" - Descending order. -func (c *UsersListCall) SortOrder(sortOrder string) *UsersListCall { - c.urlParams_.Set("sortOrder", sortOrder) - return c -} - -// ViewType sets the optional parameter "viewType": Whether to fetch the -// ADMIN_VIEW or DOMAIN_PUBLIC view of the user. -// -// Possible values: -// "admin_view" (default) - Fetches the ADMIN_VIEW of the user. -// "domain_public" - Fetches the DOMAIN_PUBLIC view of the user. -func (c *UsersListCall) ViewType(viewType string) *UsersListCall { - c.urlParams_.Set("viewType", viewType) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersListCall) Fields(s ...googleapi.Field) *UsersListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *UsersListCall) IfNoneMatch(entityTag string) *UsersListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersListCall) Context(ctx context.Context) *UsersListCall { - c.ctx_ = ctx - return c -} - -func (c *UsersListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.SetOpaque(req.URL) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.list" call. -// Exactly one of *Users or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Users.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *UsersListCall) Do(opts ...googleapi.CallOption) (*Users, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Users{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve either deleted users or all users in a domain (paginated)", - // "httpMethod": "GET", - // "id": "directory.users.list", - // "parameters": { - // "customFieldMask": { - // "description": "Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.", - // "location": "query", - // "type": "string" - // }, - // "customer": { - // "description": "Immutable id of the Google Apps account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain.", - // "location": "query", - // "type": "string" - // }, - // "domain": { - // "description": "Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead.", - // "location": "query", - // "type": "string" - // }, - // "event": { - // "description": "Event on which subscription is intended (if subscribing)", - // "enum": [ - // "add", - // "delete", - // "makeAdmin", - // "undelete", - // "update" - // ], - // "enumDescriptions": [ - // "User Created Event", - // "User Deleted Event", - // "User Admin Status Change Event", - // "User Undeleted Event", - // "User Updated Event" - // ], - // "location": "query", - // "type": "string" - // }, - // "maxResults": { - // "description": "Maximum number of results to return. Default is 100. Max allowed is 500", - // "format": "int32", - // "location": "query", - // "maximum": "500", - // "minimum": "1", - // "type": "integer" - // }, - // "orderBy": { - // "description": "Column to use for sorting results", - // "enum": [ - // "email", - // "familyName", - // "givenName" - // ], - // "enumDescriptions": [ - // "Primary email of the user.", - // "User's family name.", - // "User's given name." - // ], - // "location": "query", - // "type": "string" - // }, - // "pageToken": { - // "description": "Token to specify next page in the list", - // "location": "query", - // "type": "string" - // }, - // "projection": { - // "default": "basic", - // "description": "What subset of fields to fetch for this user.", - // "enum": [ - // "basic", - // "custom", - // "full" - // ], - // "enumDescriptions": [ - // "Do not include any custom fields for the user.", - // "Include custom fields from schemas mentioned in customFieldMask.", - // "Include all fields associated with this user." - // ], - // "location": "query", - // "type": "string" - // }, - // "query": { - // "description": "Query string search. Should be of the form \"\". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users", - // "location": "query", - // "type": "string" - // }, - // "showDeleted": { - // "description": "If set to true retrieves the list of deleted users. Default is false", - // "location": "query", - // "type": "string" - // }, - // "sortOrder": { - // "description": "Whether to return results in ascending or descending order.", - // "enum": [ - // "ASCENDING", - // "DESCENDING" - // ], - // "enumDescriptions": [ - // "Ascending order.", - // "Descending order." - // ], - // "location": "query", - // "type": "string" - // }, - // "viewType": { - // "default": "admin_view", - // "description": "Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.", - // "enum": [ - // "admin_view", - // "domain_public" - // ], - // "enumDescriptions": [ - // "Fetches the ADMIN_VIEW of the user.", - // "Fetches the DOMAIN_PUBLIC view of the user." - // ], - // "location": "query", - // "type": "string" - // } - // }, - // "path": "users", - // "response": { - // "$ref": "Users" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user", - // "https://www.googleapis.com/auth/admin.directory.user.readonly" - // ], - // "supportsSubscription": true - // } - -} - -// Pages invokes f for each page of results. -// A non-nil error returned from f will halt the iteration. -// The provided context supersedes any context provided to the Context method. -func (c *UsersListCall) Pages(ctx context.Context, f func(*Users) error) error { - c.ctx_ = ctx - defer c.PageToken(c.urlParams_.Get("pageToken")) // reset paging to original point - for { - x, err := c.Do() - if err != nil { - return err - } - if err := f(x); err != nil { - return err - } - if x.NextPageToken == "" { - return nil - } - c.PageToken(x.NextPageToken) - } -} - -// method id "directory.users.makeAdmin": - -type UsersMakeAdminCall struct { - s *Service - userKey string - usermakeadmin *UserMakeAdmin - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// MakeAdmin: change admin status of a user -func (r *UsersService) MakeAdmin(userKey string, usermakeadmin *UserMakeAdmin) *UsersMakeAdminCall { - c := &UsersMakeAdminCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - c.usermakeadmin = usermakeadmin - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersMakeAdminCall) Fields(s ...googleapi.Field) *UsersMakeAdminCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersMakeAdminCall) Context(ctx context.Context) *UsersMakeAdminCall { - c.ctx_ = ctx - return c -} - -func (c *UsersMakeAdminCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.usermakeadmin) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/makeAdmin") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.makeAdmin" call. -func (c *UsersMakeAdminCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "change admin status of a user", - // "httpMethod": "POST", - // "id": "directory.users.makeAdmin", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Email or immutable Id of the user as admin", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/makeAdmin", - // "request": { - // "$ref": "UserMakeAdmin" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user" - // ] - // } - -} - -// method id "directory.users.patch": - -type UsersPatchCall struct { - s *Service - userKey string - user *User - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Patch: update user. This method supports patch semantics. -func (r *UsersService) Patch(userKey string, user *User) *UsersPatchCall { - c := &UsersPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - c.user = user - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersPatchCall) Fields(s ...googleapi.Field) *UsersPatchCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersPatchCall) Context(ctx context.Context) *UsersPatchCall { - c.ctx_ = ctx - return c -} - -func (c *UsersPatchCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.user) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PATCH", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.patch" call. -// Exactly one of *User or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *User.ServerResponse.Header or (if a response was returned at all) in -// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check -// whether the returned error was because http.StatusNotModified was -// returned. -func (c *UsersPatchCall) Do(opts ...googleapi.CallOption) (*User, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &User{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "update user. This method supports patch semantics.", - // "httpMethod": "PATCH", - // "id": "directory.users.patch", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Email or immutable Id of the user. If Id, it should match with id of user object", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}", - // "request": { - // "$ref": "User" - // }, - // "response": { - // "$ref": "User" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user" - // ] - // } - -} - -// method id "directory.users.undelete": - -type UsersUndeleteCall struct { - s *Service - userKey string - userundelete *UserUndelete - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Undelete: Undelete a deleted user -func (r *UsersService) Undelete(userKey string, userundelete *UserUndelete) *UsersUndeleteCall { - c := &UsersUndeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - c.userundelete = userundelete - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersUndeleteCall) Fields(s ...googleapi.Field) *UsersUndeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersUndeleteCall) Context(ctx context.Context) *UsersUndeleteCall { - c.ctx_ = ctx - return c -} - -func (c *UsersUndeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.userundelete) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/undelete") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.undelete" call. -func (c *UsersUndeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Undelete a deleted user", - // "httpMethod": "POST", - // "id": "directory.users.undelete", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "The immutable id of the user", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/undelete", - // "request": { - // "$ref": "UserUndelete" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user" - // ] - // } - -} - -// method id "directory.users.update": - -type UsersUpdateCall struct { - s *Service - userKey string - user *User - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Update: update user -func (r *UsersService) Update(userKey string, user *User) *UsersUpdateCall { - c := &UsersUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - c.user = user - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersUpdateCall) Fields(s ...googleapi.Field) *UsersUpdateCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersUpdateCall) Context(ctx context.Context) *UsersUpdateCall { - c.ctx_ = ctx - return c -} - -func (c *UsersUpdateCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.user) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PUT", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.update" call. -// Exactly one of *User or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *User.ServerResponse.Header or (if a response was returned at all) in -// error.(*googleapi.Error).Header. Use googleapi.IsNotModified to check -// whether the returned error was because http.StatusNotModified was -// returned. -func (c *UsersUpdateCall) Do(opts ...googleapi.CallOption) (*User, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &User{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "update user", - // "httpMethod": "PUT", - // "id": "directory.users.update", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Email or immutable Id of the user. If Id, it should match with id of user object", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}", - // "request": { - // "$ref": "User" - // }, - // "response": { - // "$ref": "User" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user" - // ] - // } - -} - -// method id "directory.users.watch": - -type UsersWatchCall struct { - s *Service - channel *Channel - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Watch: Watch for changes in users list -func (r *UsersService) Watch(channel *Channel) *UsersWatchCall { - c := &UsersWatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.channel = channel - return c -} - -// CustomFieldMask sets the optional parameter "customFieldMask": -// Comma-separated list of schema names. All fields from these schemas -// are fetched. This should only be set when projection=custom. -func (c *UsersWatchCall) CustomFieldMask(customFieldMask string) *UsersWatchCall { - c.urlParams_.Set("customFieldMask", customFieldMask) - return c -} - -// Customer sets the optional parameter "customer": Immutable id of the -// Google Apps account. In case of multi-domain, to fetch all users for -// a customer, fill this field instead of domain. -func (c *UsersWatchCall) Customer(customer string) *UsersWatchCall { - c.urlParams_.Set("customer", customer) - return c -} - -// Domain sets the optional parameter "domain": Name of the domain. Fill -// this field to get users from only this domain. To return all users in -// a multi-domain fill customer field instead. -func (c *UsersWatchCall) Domain(domain string) *UsersWatchCall { - c.urlParams_.Set("domain", domain) - return c -} - -// Event sets the optional parameter "event": Event on which -// subscription is intended (if subscribing) -// -// Possible values: -// "add" - User Created Event -// "delete" - User Deleted Event -// "makeAdmin" - User Admin Status Change Event -// "undelete" - User Undeleted Event -// "update" - User Updated Event -func (c *UsersWatchCall) Event(event string) *UsersWatchCall { - c.urlParams_.Set("event", event) - return c -} - -// MaxResults sets the optional parameter "maxResults": Maximum number -// of results to return. Default is 100. Max allowed is 500 -func (c *UsersWatchCall) MaxResults(maxResults int64) *UsersWatchCall { - c.urlParams_.Set("maxResults", fmt.Sprint(maxResults)) - return c -} - -// OrderBy sets the optional parameter "orderBy": Column to use for -// sorting results -// -// Possible values: -// "email" - Primary email of the user. -// "familyName" - User's family name. -// "givenName" - User's given name. -func (c *UsersWatchCall) OrderBy(orderBy string) *UsersWatchCall { - c.urlParams_.Set("orderBy", orderBy) - return c -} - -// PageToken sets the optional parameter "pageToken": Token to specify -// next page in the list -func (c *UsersWatchCall) PageToken(pageToken string) *UsersWatchCall { - c.urlParams_.Set("pageToken", pageToken) - return c -} - -// Projection sets the optional parameter "projection": What subset of -// fields to fetch for this user. -// -// Possible values: -// "basic" (default) - Do not include any custom fields for the user. -// "custom" - Include custom fields from schemas mentioned in -// customFieldMask. -// "full" - Include all fields associated with this user. -func (c *UsersWatchCall) Projection(projection string) *UsersWatchCall { - c.urlParams_.Set("projection", projection) - return c -} - -// Query sets the optional parameter "query": Query string search. -// Should be of the form "". Complete documentation is at -// https://developers.google.com/admin-sdk/directory/v1/guides/search-users -func (c *UsersWatchCall) Query(query string) *UsersWatchCall { - c.urlParams_.Set("query", query) - return c -} - -// ShowDeleted sets the optional parameter "showDeleted": If set to true -// retrieves the list of deleted users. Default is false -func (c *UsersWatchCall) ShowDeleted(showDeleted string) *UsersWatchCall { - c.urlParams_.Set("showDeleted", showDeleted) - return c -} - -// SortOrder sets the optional parameter "sortOrder": Whether to return -// results in ascending or descending order. -// -// Possible values: -// "ASCENDING" - Ascending order. -// "DESCENDING" - Descending order. -func (c *UsersWatchCall) SortOrder(sortOrder string) *UsersWatchCall { - c.urlParams_.Set("sortOrder", sortOrder) - return c -} - -// ViewType sets the optional parameter "viewType": Whether to fetch the -// ADMIN_VIEW or DOMAIN_PUBLIC view of the user. -// -// Possible values: -// "admin_view" (default) - Fetches the ADMIN_VIEW of the user. -// "domain_public" - Fetches the DOMAIN_PUBLIC view of the user. -func (c *UsersWatchCall) ViewType(viewType string) *UsersWatchCall { - c.urlParams_.Set("viewType", viewType) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersWatchCall) Fields(s ...googleapi.Field) *UsersWatchCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersWatchCall) Context(ctx context.Context) *UsersWatchCall { - c.ctx_ = ctx - return c -} - -func (c *UsersWatchCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.channel) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/watch") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.SetOpaque(req.URL) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.watch" call. -// Exactly one of *Channel or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Channel.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *UsersWatchCall) Do(opts ...googleapi.CallOption) (*Channel, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Channel{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Watch for changes in users list", - // "httpMethod": "POST", - // "id": "directory.users.watch", - // "parameters": { - // "customFieldMask": { - // "description": "Comma-separated list of schema names. All fields from these schemas are fetched. This should only be set when projection=custom.", - // "location": "query", - // "type": "string" - // }, - // "customer": { - // "description": "Immutable id of the Google Apps account. In case of multi-domain, to fetch all users for a customer, fill this field instead of domain.", - // "location": "query", - // "type": "string" - // }, - // "domain": { - // "description": "Name of the domain. Fill this field to get users from only this domain. To return all users in a multi-domain fill customer field instead.", - // "location": "query", - // "type": "string" - // }, - // "event": { - // "description": "Event on which subscription is intended (if subscribing)", - // "enum": [ - // "add", - // "delete", - // "makeAdmin", - // "undelete", - // "update" - // ], - // "enumDescriptions": [ - // "User Created Event", - // "User Deleted Event", - // "User Admin Status Change Event", - // "User Undeleted Event", - // "User Updated Event" - // ], - // "location": "query", - // "type": "string" - // }, - // "maxResults": { - // "description": "Maximum number of results to return. Default is 100. Max allowed is 500", - // "format": "int32", - // "location": "query", - // "maximum": "500", - // "minimum": "1", - // "type": "integer" - // }, - // "orderBy": { - // "description": "Column to use for sorting results", - // "enum": [ - // "email", - // "familyName", - // "givenName" - // ], - // "enumDescriptions": [ - // "Primary email of the user.", - // "User's family name.", - // "User's given name." - // ], - // "location": "query", - // "type": "string" - // }, - // "pageToken": { - // "description": "Token to specify next page in the list", - // "location": "query", - // "type": "string" - // }, - // "projection": { - // "default": "basic", - // "description": "What subset of fields to fetch for this user.", - // "enum": [ - // "basic", - // "custom", - // "full" - // ], - // "enumDescriptions": [ - // "Do not include any custom fields for the user.", - // "Include custom fields from schemas mentioned in customFieldMask.", - // "Include all fields associated with this user." - // ], - // "location": "query", - // "type": "string" - // }, - // "query": { - // "description": "Query string search. Should be of the form \"\". Complete documentation is at https://developers.google.com/admin-sdk/directory/v1/guides/search-users", - // "location": "query", - // "type": "string" - // }, - // "showDeleted": { - // "description": "If set to true retrieves the list of deleted users. Default is false", - // "location": "query", - // "type": "string" - // }, - // "sortOrder": { - // "description": "Whether to return results in ascending or descending order.", - // "enum": [ - // "ASCENDING", - // "DESCENDING" - // ], - // "enumDescriptions": [ - // "Ascending order.", - // "Descending order." - // ], - // "location": "query", - // "type": "string" - // }, - // "viewType": { - // "default": "admin_view", - // "description": "Whether to fetch the ADMIN_VIEW or DOMAIN_PUBLIC view of the user.", - // "enum": [ - // "admin_view", - // "domain_public" - // ], - // "enumDescriptions": [ - // "Fetches the ADMIN_VIEW of the user.", - // "Fetches the DOMAIN_PUBLIC view of the user." - // ], - // "location": "query", - // "type": "string" - // } - // }, - // "path": "users/watch", - // "request": { - // "$ref": "Channel", - // "parameterName": "resource" - // }, - // "response": { - // "$ref": "Channel" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user", - // "https://www.googleapis.com/auth/admin.directory.user.readonly" - // ], - // "supportsSubscription": true - // } - -} - -// method id "directory.users.aliases.delete": - -type UsersAliasesDeleteCall struct { - s *Service - userKey string - alias string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Remove a alias for the user -func (r *UsersAliasesService) Delete(userKey string, alias string) *UsersAliasesDeleteCall { - c := &UsersAliasesDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - c.alias = alias - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersAliasesDeleteCall) Fields(s ...googleapi.Field) *UsersAliasesDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersAliasesDeleteCall) Context(ctx context.Context) *UsersAliasesDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *UsersAliasesDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/aliases/{alias}") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - "alias": c.alias, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.aliases.delete" call. -func (c *UsersAliasesDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Remove a alias for the user", - // "httpMethod": "DELETE", - // "id": "directory.users.aliases.delete", - // "parameterOrder": [ - // "userKey", - // "alias" - // ], - // "parameters": { - // "alias": { - // "description": "The alias to be removed", - // "location": "path", - // "required": true, - // "type": "string" - // }, - // "userKey": { - // "description": "Email or immutable Id of the user", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/aliases/{alias}", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user", - // "https://www.googleapis.com/auth/admin.directory.user.alias" - // ] - // } - -} - -// method id "directory.users.aliases.insert": - -type UsersAliasesInsertCall struct { - s *Service - userKey string - alias *Alias - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Insert: Add a alias for the user -func (r *UsersAliasesService) Insert(userKey string, alias *Alias) *UsersAliasesInsertCall { - c := &UsersAliasesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - c.alias = alias - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersAliasesInsertCall) Fields(s ...googleapi.Field) *UsersAliasesInsertCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersAliasesInsertCall) Context(ctx context.Context) *UsersAliasesInsertCall { - c.ctx_ = ctx - return c -} - -func (c *UsersAliasesInsertCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.alias) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/aliases") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.aliases.insert" call. -// Exactly one of *Alias or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Alias.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *UsersAliasesInsertCall) Do(opts ...googleapi.CallOption) (*Alias, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Alias{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Add a alias for the user", - // "httpMethod": "POST", - // "id": "directory.users.aliases.insert", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Email or immutable Id of the user", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/aliases", - // "request": { - // "$ref": "Alias" - // }, - // "response": { - // "$ref": "Alias" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user", - // "https://www.googleapis.com/auth/admin.directory.user.alias" - // ] - // } - -} - -// method id "directory.users.aliases.list": - -type UsersAliasesListCall struct { - s *Service - userKey string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: List all aliases for a user -func (r *UsersAliasesService) List(userKey string) *UsersAliasesListCall { - c := &UsersAliasesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - return c -} - -// Event sets the optional parameter "event": Event on which -// subscription is intended (if subscribing) -// -// Possible values: -// "add" - Alias Created Event -// "delete" - Alias Deleted Event -func (c *UsersAliasesListCall) Event(event string) *UsersAliasesListCall { - c.urlParams_.Set("event", event) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersAliasesListCall) Fields(s ...googleapi.Field) *UsersAliasesListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *UsersAliasesListCall) IfNoneMatch(entityTag string) *UsersAliasesListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersAliasesListCall) Context(ctx context.Context) *UsersAliasesListCall { - c.ctx_ = ctx - return c -} - -func (c *UsersAliasesListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/aliases") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.aliases.list" call. -// Exactly one of *Aliases or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Aliases.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *UsersAliasesListCall) Do(opts ...googleapi.CallOption) (*Aliases, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Aliases{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "List all aliases for a user", - // "httpMethod": "GET", - // "id": "directory.users.aliases.list", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "event": { - // "description": "Event on which subscription is intended (if subscribing)", - // "enum": [ - // "add", - // "delete" - // ], - // "enumDescriptions": [ - // "Alias Created Event", - // "Alias Deleted Event" - // ], - // "location": "query", - // "type": "string" - // }, - // "userKey": { - // "description": "Email or immutable Id of the user", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/aliases", - // "response": { - // "$ref": "Aliases" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user", - // "https://www.googleapis.com/auth/admin.directory.user.alias", - // "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", - // "https://www.googleapis.com/auth/admin.directory.user.readonly" - // ], - // "supportsSubscription": true - // } - -} - -// method id "directory.users.aliases.watch": - -type UsersAliasesWatchCall struct { - s *Service - userKey string - channel *Channel - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Watch: Watch for changes in user aliases list -func (r *UsersAliasesService) Watch(userKey string, channel *Channel) *UsersAliasesWatchCall { - c := &UsersAliasesWatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - c.channel = channel - return c -} - -// Event sets the optional parameter "event": Event on which -// subscription is intended (if subscribing) -// -// Possible values: -// "add" - Alias Created Event -// "delete" - Alias Deleted Event -func (c *UsersAliasesWatchCall) Event(event string) *UsersAliasesWatchCall { - c.urlParams_.Set("event", event) - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersAliasesWatchCall) Fields(s ...googleapi.Field) *UsersAliasesWatchCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersAliasesWatchCall) Context(ctx context.Context) *UsersAliasesWatchCall { - c.ctx_ = ctx - return c -} - -func (c *UsersAliasesWatchCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.channel) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/aliases/watch") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.aliases.watch" call. -// Exactly one of *Channel or error will be non-nil. Any non-2xx status -// code is an error. Response headers are in either -// *Channel.ServerResponse.Header or (if a response was returned at all) -// in error.(*googleapi.Error).Header. Use googleapi.IsNotModified to -// check whether the returned error was because http.StatusNotModified -// was returned. -func (c *UsersAliasesWatchCall) Do(opts ...googleapi.CallOption) (*Channel, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &Channel{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Watch for changes in user aliases list", - // "httpMethod": "POST", - // "id": "directory.users.aliases.watch", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "event": { - // "description": "Event on which subscription is intended (if subscribing)", - // "enum": [ - // "add", - // "delete" - // ], - // "enumDescriptions": [ - // "Alias Created Event", - // "Alias Deleted Event" - // ], - // "location": "query", - // "type": "string" - // }, - // "userKey": { - // "description": "Email or immutable Id of the user", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/aliases/watch", - // "request": { - // "$ref": "Channel", - // "parameterName": "resource" - // }, - // "response": { - // "$ref": "Channel" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user", - // "https://www.googleapis.com/auth/admin.directory.user.alias", - // "https://www.googleapis.com/auth/admin.directory.user.alias.readonly", - // "https://www.googleapis.com/auth/admin.directory.user.readonly" - // ], - // "supportsSubscription": true - // } - -} - -// method id "directory.users.photos.delete": - -type UsersPhotosDeleteCall struct { - s *Service - userKey string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Delete: Remove photos for the user -func (r *UsersPhotosService) Delete(userKey string) *UsersPhotosDeleteCall { - c := &UsersPhotosDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersPhotosDeleteCall) Fields(s ...googleapi.Field) *UsersPhotosDeleteCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersPhotosDeleteCall) Context(ctx context.Context) *UsersPhotosDeleteCall { - c.ctx_ = ctx - return c -} - -func (c *UsersPhotosDeleteCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/photos/thumbnail") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("DELETE", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.photos.delete" call. -func (c *UsersPhotosDeleteCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Remove photos for the user", - // "httpMethod": "DELETE", - // "id": "directory.users.photos.delete", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Email or immutable Id of the user", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/photos/thumbnail", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user" - // ] - // } - -} - -// method id "directory.users.photos.get": - -type UsersPhotosGetCall struct { - s *Service - userKey string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// Get: Retrieve photo of a user -func (r *UsersPhotosService) Get(userKey string) *UsersPhotosGetCall { - c := &UsersPhotosGetCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersPhotosGetCall) Fields(s ...googleapi.Field) *UsersPhotosGetCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *UsersPhotosGetCall) IfNoneMatch(entityTag string) *UsersPhotosGetCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersPhotosGetCall) Context(ctx context.Context) *UsersPhotosGetCall { - c.ctx_ = ctx - return c -} - -func (c *UsersPhotosGetCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/photos/thumbnail") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.photos.get" call. -// Exactly one of *UserPhoto or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *UserPhoto.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *UsersPhotosGetCall) Do(opts ...googleapi.CallOption) (*UserPhoto, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &UserPhoto{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Retrieve photo of a user", - // "httpMethod": "GET", - // "id": "directory.users.photos.get", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Email or immutable Id of the user", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/photos/thumbnail", - // "response": { - // "$ref": "UserPhoto" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user", - // "https://www.googleapis.com/auth/admin.directory.user.readonly" - // ] - // } - -} - -// method id "directory.users.photos.patch": - -type UsersPhotosPatchCall struct { - s *Service - userKey string - userphoto *UserPhoto - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Patch: Add a photo for the user. This method supports patch -// semantics. -func (r *UsersPhotosService) Patch(userKey string, userphoto *UserPhoto) *UsersPhotosPatchCall { - c := &UsersPhotosPatchCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - c.userphoto = userphoto - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersPhotosPatchCall) Fields(s ...googleapi.Field) *UsersPhotosPatchCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersPhotosPatchCall) Context(ctx context.Context) *UsersPhotosPatchCall { - c.ctx_ = ctx - return c -} - -func (c *UsersPhotosPatchCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.userphoto) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/photos/thumbnail") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PATCH", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.photos.patch" call. -// Exactly one of *UserPhoto or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *UserPhoto.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *UsersPhotosPatchCall) Do(opts ...googleapi.CallOption) (*UserPhoto, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &UserPhoto{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Add a photo for the user. This method supports patch semantics.", - // "httpMethod": "PATCH", - // "id": "directory.users.photos.patch", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Email or immutable Id of the user", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/photos/thumbnail", - // "request": { - // "$ref": "UserPhoto" - // }, - // "response": { - // "$ref": "UserPhoto" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user" - // ] - // } - -} - -// method id "directory.users.photos.update": - -type UsersPhotosUpdateCall struct { - s *Service - userKey string - userphoto *UserPhoto - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Update: Add a photo for the user -func (r *UsersPhotosService) Update(userKey string, userphoto *UserPhoto) *UsersPhotosUpdateCall { - c := &UsersPhotosUpdateCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - c.userphoto = userphoto - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *UsersPhotosUpdateCall) Fields(s ...googleapi.Field) *UsersPhotosUpdateCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *UsersPhotosUpdateCall) Context(ctx context.Context) *UsersPhotosUpdateCall { - c.ctx_ = ctx - return c -} - -func (c *UsersPhotosUpdateCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - body, err := googleapi.WithoutDataWrapper.JSONReader(c.userphoto) - if err != nil { - return nil, err - } - ctype := "application/json" - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/photos/thumbnail") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("PUT", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("Content-Type", ctype) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.users.photos.update" call. -// Exactly one of *UserPhoto or error will be non-nil. Any non-2xx -// status code is an error. Response headers are in either -// *UserPhoto.ServerResponse.Header or (if a response was returned at -// all) in error.(*googleapi.Error).Header. Use googleapi.IsNotModified -// to check whether the returned error was because -// http.StatusNotModified was returned. -func (c *UsersPhotosUpdateCall) Do(opts ...googleapi.CallOption) (*UserPhoto, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &UserPhoto{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Add a photo for the user", - // "httpMethod": "PUT", - // "id": "directory.users.photos.update", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Email or immutable Id of the user", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/photos/thumbnail", - // "request": { - // "$ref": "UserPhoto" - // }, - // "response": { - // "$ref": "UserPhoto" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user" - // ] - // } - -} - -// method id "directory.verificationCodes.generate": - -type VerificationCodesGenerateCall struct { - s *Service - userKey string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Generate: Generate new backup verification codes for the user. -func (r *VerificationCodesService) Generate(userKey string) *VerificationCodesGenerateCall { - c := &VerificationCodesGenerateCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *VerificationCodesGenerateCall) Fields(s ...googleapi.Field) *VerificationCodesGenerateCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *VerificationCodesGenerateCall) Context(ctx context.Context) *VerificationCodesGenerateCall { - c.ctx_ = ctx - return c -} - -func (c *VerificationCodesGenerateCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/verificationCodes/generate") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.verificationCodes.generate" call. -func (c *VerificationCodesGenerateCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Generate new backup verification codes for the user.", - // "httpMethod": "POST", - // "id": "directory.verificationCodes.generate", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Email or immutable Id of the user", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/verificationCodes/generate", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user.security" - // ] - // } - -} - -// method id "directory.verificationCodes.invalidate": - -type VerificationCodesInvalidateCall struct { - s *Service - userKey string - urlParams_ gensupport.URLParams - ctx_ context.Context -} - -// Invalidate: Invalidate the current backup verification codes for the -// user. -func (r *VerificationCodesService) Invalidate(userKey string) *VerificationCodesInvalidateCall { - c := &VerificationCodesInvalidateCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *VerificationCodesInvalidateCall) Fields(s ...googleapi.Field) *VerificationCodesInvalidateCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *VerificationCodesInvalidateCall) Context(ctx context.Context) *VerificationCodesInvalidateCall { - c.ctx_ = ctx - return c -} - -func (c *VerificationCodesInvalidateCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/verificationCodes/invalidate") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("POST", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.verificationCodes.invalidate" call. -func (c *VerificationCodesInvalidateCall) Do(opts ...googleapi.CallOption) error { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if err != nil { - return err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return err - } - return nil - // { - // "description": "Invalidate the current backup verification codes for the user.", - // "httpMethod": "POST", - // "id": "directory.verificationCodes.invalidate", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Email or immutable Id of the user", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/verificationCodes/invalidate", - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user.security" - // ] - // } - -} - -// method id "directory.verificationCodes.list": - -type VerificationCodesListCall struct { - s *Service - userKey string - urlParams_ gensupport.URLParams - ifNoneMatch_ string - ctx_ context.Context -} - -// List: Returns the current set of valid backup verification codes for -// the specified user. -func (r *VerificationCodesService) List(userKey string) *VerificationCodesListCall { - c := &VerificationCodesListCall{s: r.s, urlParams_: make(gensupport.URLParams)} - c.userKey = userKey - return c -} - -// Fields allows partial responses to be retrieved. See -// https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// for more information. -func (c *VerificationCodesListCall) Fields(s ...googleapi.Field) *VerificationCodesListCall { - c.urlParams_.Set("fields", googleapi.CombineFields(s)) - return c -} - -// IfNoneMatch sets the optional parameter which makes the operation -// fail if the object's ETag matches the given value. This is useful for -// getting updates only after the object has changed since the last -// request. Use googleapi.IsNotModified to check whether the response -// error from Do is the result of In-None-Match. -func (c *VerificationCodesListCall) IfNoneMatch(entityTag string) *VerificationCodesListCall { - c.ifNoneMatch_ = entityTag - return c -} - -// Context sets the context to be used in this call's Do method. Any -// pending HTTP request will be aborted if the provided context is -// canceled. -func (c *VerificationCodesListCall) Context(ctx context.Context) *VerificationCodesListCall { - c.ctx_ = ctx - return c -} - -func (c *VerificationCodesListCall) doRequest(alt string) (*http.Response, error) { - var body io.Reader = nil - c.urlParams_.Set("alt", alt) - urls := googleapi.ResolveRelative(c.s.BasePath, "users/{userKey}/verificationCodes") - urls += "?" + c.urlParams_.Encode() - req, _ := http.NewRequest("GET", urls, body) - googleapi.Expand(req.URL, map[string]string{ - "userKey": c.userKey, - }) - req.Header.Set("User-Agent", c.s.userAgent()) - if c.ifNoneMatch_ != "" { - req.Header.Set("If-None-Match", c.ifNoneMatch_) - } - if c.ctx_ != nil { - return ctxhttp.Do(c.ctx_, c.s.client, req) - } - return c.s.client.Do(req) -} - -// Do executes the "directory.verificationCodes.list" call. -// Exactly one of *VerificationCodes or error will be non-nil. Any -// non-2xx status code is an error. Response headers are in either -// *VerificationCodes.ServerResponse.Header or (if a response was -// returned at all) in error.(*googleapi.Error).Header. Use -// googleapi.IsNotModified to check whether the returned error was -// because http.StatusNotModified was returned. -func (c *VerificationCodesListCall) Do(opts ...googleapi.CallOption) (*VerificationCodes, error) { - gensupport.SetOptions(c.urlParams_, opts...) - res, err := c.doRequest("json") - if res != nil && res.StatusCode == http.StatusNotModified { - if res.Body != nil { - res.Body.Close() - } - return nil, &googleapi.Error{ - Code: res.StatusCode, - Header: res.Header, - } - } - if err != nil { - return nil, err - } - defer googleapi.CloseBody(res) - if err := googleapi.CheckResponse(res); err != nil { - return nil, err - } - ret := &VerificationCodes{ - ServerResponse: googleapi.ServerResponse{ - Header: res.Header, - HTTPStatusCode: res.StatusCode, - }, - } - if err := json.NewDecoder(res.Body).Decode(&ret); err != nil { - return nil, err - } - return ret, nil - // { - // "description": "Returns the current set of valid backup verification codes for the specified user.", - // "httpMethod": "GET", - // "id": "directory.verificationCodes.list", - // "parameterOrder": [ - // "userKey" - // ], - // "parameters": { - // "userKey": { - // "description": "Identifies the user in the API request. The value can be the user's primary email address, alias email address, or unique user ID.", - // "location": "path", - // "required": true, - // "type": "string" - // } - // }, - // "path": "users/{userKey}/verificationCodes", - // "response": { - // "$ref": "VerificationCodes" - // }, - // "scopes": [ - // "https://www.googleapis.com/auth/admin.directory.user.security" - // ] - // } - -} diff --git a/Godeps/_workspace/src/google.golang.org/api/gensupport/backoff.go b/Godeps/_workspace/src/google.golang.org/api/gensupport/backoff.go deleted file mode 100644 index 0cc3e406b..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/gensupport/backoff.go +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gensupport - -import "time" - -type BackoffStrategy interface { - // Pause returns the duration of the next pause before a retry should be attempted. - Pause() time.Duration - - // Reset restores the strategy to its initial state. - Reset() -} - -type ExponentialBackoff struct { - BasePause time.Duration - nextPause time.Duration -} - -func (eb *ExponentialBackoff) Pause() time.Duration { - if eb.nextPause == 0 { - eb.Reset() - } - - d := eb.nextPause - eb.nextPause *= 2 - return d -} - -func (eb *ExponentialBackoff) Reset() { - eb.nextPause = eb.BasePause -} diff --git a/Godeps/_workspace/src/google.golang.org/api/gensupport/buffer.go b/Godeps/_workspace/src/google.golang.org/api/gensupport/buffer.go deleted file mode 100644 index 4b8ec1424..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/gensupport/buffer.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gensupport - -import ( - "bytes" - "io" - - "google.golang.org/api/googleapi" -) - -// ResumableBuffer buffers data from an io.Reader to support uploading media in retryable chunks. -type ResumableBuffer struct { - media io.Reader - - chunk []byte // The current chunk which is pending upload. The capacity is the chunk size. - err error // Any error generated when populating chunk by reading media. - - // The absolute position of chunk in the underlying media. - off int64 -} - -func NewResumableBuffer(media io.Reader, chunkSize int) *ResumableBuffer { - return &ResumableBuffer{media: media, chunk: make([]byte, 0, chunkSize)} -} - -// Chunk returns the current buffered chunk, the offset in the underlying media -// from which the chunk is drawn, and the size of the chunk. -// Successive calls to Chunk return the same chunk between calls to Next. -func (rb *ResumableBuffer) Chunk() (chunk io.Reader, off int64, size int, err error) { - // There may already be data in chunk if Next has not been called since the previous call to Chunk. - if rb.err == nil && len(rb.chunk) == 0 { - rb.err = rb.loadChunk() - } - return bytes.NewReader(rb.chunk), rb.off, len(rb.chunk), rb.err -} - -// loadChunk will read from media into chunk, up to the capacity of chunk. -func (rb *ResumableBuffer) loadChunk() error { - bufSize := cap(rb.chunk) - rb.chunk = rb.chunk[:bufSize] - - read := 0 - var err error - for err == nil && read < bufSize { - var n int - n, err = rb.media.Read(rb.chunk[read:]) - read += n - } - rb.chunk = rb.chunk[:read] - return err -} - -// Next advances to the next chunk, which will be returned by the next call to Chunk. -// Calls to Next without a corresponding prior call to Chunk will have no effect. -func (rb *ResumableBuffer) Next() { - rb.off += int64(len(rb.chunk)) - rb.chunk = rb.chunk[0:0] -} - -type readerTyper struct { - io.Reader - googleapi.ContentTyper -} - -// ReaderAtToReader adapts a ReaderAt to be used as a Reader. -// If ra implements googleapi.ContentTyper, then the returned reader -// will also implement googleapi.ContentTyper, delegating to ra. -func ReaderAtToReader(ra io.ReaderAt, size int64) io.Reader { - r := io.NewSectionReader(ra, 0, size) - if typer, ok := ra.(googleapi.ContentTyper); ok { - return readerTyper{r, typer} - } - return r -} diff --git a/Godeps/_workspace/src/google.golang.org/api/gensupport/doc.go b/Godeps/_workspace/src/google.golang.org/api/gensupport/doc.go deleted file mode 100644 index 752c4b411..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/gensupport/doc.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package gensupport is an internal implementation detail used by code -// generated by the google-api-go-generator tool. -// -// This package may be modified at any time without regard for backwards -// compatibility. It should not be used directly by API users. -package gensupport diff --git a/Godeps/_workspace/src/google.golang.org/api/gensupport/json.go b/Godeps/_workspace/src/google.golang.org/api/gensupport/json.go deleted file mode 100644 index dd7bcd2eb..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/gensupport/json.go +++ /dev/null @@ -1,172 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gensupport - -import ( - "encoding/json" - "fmt" - "reflect" - "strings" -) - -// MarshalJSON returns a JSON encoding of schema containing only selected fields. -// A field is selected if: -// * it has a non-empty value, or -// * its field name is present in forceSendFields, and -// * it is not a nil pointer or nil interface. -// The JSON key for each selected field is taken from the field's json: struct tag. -func MarshalJSON(schema interface{}, forceSendFields []string) ([]byte, error) { - if len(forceSendFields) == 0 { - return json.Marshal(schema) - } - - mustInclude := make(map[string]struct{}) - for _, f := range forceSendFields { - mustInclude[f] = struct{}{} - } - - dataMap, err := schemaToMap(schema, mustInclude) - if err != nil { - return nil, err - } - return json.Marshal(dataMap) -} - -func schemaToMap(schema interface{}, mustInclude map[string]struct{}) (map[string]interface{}, error) { - m := make(map[string]interface{}) - s := reflect.ValueOf(schema) - st := s.Type() - - for i := 0; i < s.NumField(); i++ { - jsonTag := st.Field(i).Tag.Get("json") - if jsonTag == "" { - continue - } - tag, err := parseJSONTag(jsonTag) - if err != nil { - return nil, err - } - if tag.ignore { - continue - } - - v := s.Field(i) - f := st.Field(i) - if !includeField(v, f, mustInclude) { - continue - } - - // nil maps are treated as empty maps. - if f.Type.Kind() == reflect.Map && v.IsNil() { - m[tag.apiName] = map[string]string{} - continue - } - - // nil slices are treated as empty slices. - if f.Type.Kind() == reflect.Slice && v.IsNil() { - m[tag.apiName] = []bool{} - continue - } - - if tag.stringFormat { - m[tag.apiName] = formatAsString(v, f.Type.Kind()) - } else { - m[tag.apiName] = v.Interface() - } - } - return m, nil -} - -// formatAsString returns a string representation of v, dereferencing it first if possible. -func formatAsString(v reflect.Value, kind reflect.Kind) string { - if kind == reflect.Ptr && !v.IsNil() { - v = v.Elem() - } - - return fmt.Sprintf("%v", v.Interface()) -} - -// jsonTag represents a restricted version of the struct tag format used by encoding/json. -// It is used to describe the JSON encoding of fields in a Schema struct. -type jsonTag struct { - apiName string - stringFormat bool - ignore bool -} - -// parseJSONTag parses a restricted version of the struct tag format used by encoding/json. -// The format of the tag must match that generated by the Schema.writeSchemaStruct method -// in the api generator. -func parseJSONTag(val string) (jsonTag, error) { - if val == "-" { - return jsonTag{ignore: true}, nil - } - - var tag jsonTag - - i := strings.Index(val, ",") - if i == -1 || val[:i] == "" { - return tag, fmt.Errorf("malformed json tag: %s", val) - } - - tag = jsonTag{ - apiName: val[:i], - } - - switch val[i+1:] { - case "omitempty": - case "omitempty,string": - tag.stringFormat = true - default: - return tag, fmt.Errorf("malformed json tag: %s", val) - } - - return tag, nil -} - -// Reports whether the struct field "f" with value "v" should be included in JSON output. -func includeField(v reflect.Value, f reflect.StructField, mustInclude map[string]struct{}) bool { - // The regular JSON encoding of a nil pointer is "null", which means "delete this field". - // Therefore, we could enable field deletion by honoring pointer fields' presence in the mustInclude set. - // However, many fields are not pointers, so there would be no way to delete these fields. - // Rather than partially supporting field deletion, we ignore mustInclude for nil pointer fields. - // Deletion will be handled by a separate mechanism. - if f.Type.Kind() == reflect.Ptr && v.IsNil() { - return false - } - - // The "any" type is represented as an interface{}. If this interface - // is nil, there is no reasonable representation to send. We ignore - // these fields, for the same reasons as given above for pointers. - if f.Type.Kind() == reflect.Interface && v.IsNil() { - return false - } - - _, ok := mustInclude[f.Name] - return ok || !isEmptyValue(v) -} - -// isEmptyValue reports whether v is the empty value for its type. This -// implementation is based on that of the encoding/json package, but its -// correctness does not depend on it being identical. What's important is that -// this function return false in situations where v should not be sent as part -// of a PATCH operation. -func isEmptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - } - return false -} diff --git a/Godeps/_workspace/src/google.golang.org/api/gensupport/media.go b/Godeps/_workspace/src/google.golang.org/api/gensupport/media.go deleted file mode 100644 index 685e08d5a..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/gensupport/media.go +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gensupport - -import ( - "fmt" - "io" - "io/ioutil" - "mime/multipart" - "net/http" - "net/textproto" - - "google.golang.org/api/googleapi" -) - -const sniffBuffSize = 512 - -func newContentSniffer(r io.Reader) *contentSniffer { - return &contentSniffer{r: r} -} - -// contentSniffer wraps a Reader, and reports the content type determined by sniffing up to 512 bytes from the Reader. -type contentSniffer struct { - r io.Reader - start []byte // buffer for the sniffed bytes. - err error // set to any error encountered while reading bytes to be sniffed. - - ctype string // set on first sniff. - sniffed bool // set to true on first sniff. -} - -func (cs *contentSniffer) Read(p []byte) (n int, err error) { - // Ensure that the content type is sniffed before any data is consumed from Reader. - _, _ = cs.ContentType() - - if len(cs.start) > 0 { - n := copy(p, cs.start) - cs.start = cs.start[n:] - return n, nil - } - - // We may have read some bytes into start while sniffing, even if the read ended in an error. - // We should first return those bytes, then the error. - if cs.err != nil { - return 0, cs.err - } - - // Now we have handled all bytes that were buffered while sniffing. Now just delegate to the underlying reader. - return cs.r.Read(p) -} - -// ContentType returns the sniffed content type, and whether the content type was succesfully sniffed. -func (cs *contentSniffer) ContentType() (string, bool) { - if cs.sniffed { - return cs.ctype, cs.ctype != "" - } - cs.sniffed = true - // If ReadAll hits EOF, it returns err==nil. - cs.start, cs.err = ioutil.ReadAll(io.LimitReader(cs.r, sniffBuffSize)) - - // Don't try to detect the content type based on possibly incomplete data. - if cs.err != nil { - return "", false - } - - cs.ctype = http.DetectContentType(cs.start) - return cs.ctype, true -} - -// DetermineContentType determines the content type of the supplied reader. -// If the content type is already known, it can be specified via ctype. -// Otherwise, the content of media will be sniffed to determine the content type. -// If media implements googleapi.ContentTyper (deprecated), this will be used -// instead of sniffing the content. -// After calling DetectContentType the caller must not perform further reads on -// media, but rather read from the Reader that is returned. -func DetermineContentType(media io.Reader, ctype string) (io.Reader, string) { - // Note: callers could avoid calling DetectContentType if ctype != "", - // but doing the check inside this function reduces the amount of - // generated code. - if ctype != "" { - return media, ctype - } - - // For backwards compatability, allow clients to set content - // type by providing a ContentTyper for media. - if typer, ok := media.(googleapi.ContentTyper); ok { - return media, typer.ContentType() - } - - sniffer := newContentSniffer(media) - if ctype, ok := sniffer.ContentType(); ok { - return sniffer, ctype - } - // If content type could not be sniffed, reads from sniffer will eventually fail with an error. - return sniffer, "" -} - -type typeReader struct { - io.Reader - typ string -} - -// multipartReader combines the contents of multiple readers to creat a multipart/related HTTP body. -// Close must be called if reads from the multipartReader are abandoned before reaching EOF. -type multipartReader struct { - pr *io.PipeReader - pipeOpen bool - ctype string -} - -func newMultipartReader(parts []typeReader) *multipartReader { - mp := &multipartReader{pipeOpen: true} - var pw *io.PipeWriter - mp.pr, pw = io.Pipe() - mpw := multipart.NewWriter(pw) - mp.ctype = "multipart/related; boundary=" + mpw.Boundary() - go func() { - for _, part := range parts { - w, err := mpw.CreatePart(typeHeader(part.typ)) - if err != nil { - mpw.Close() - pw.CloseWithError(fmt.Errorf("googleapi: CreatePart failed: %v", err)) - return - } - _, err = io.Copy(w, part.Reader) - if err != nil { - mpw.Close() - pw.CloseWithError(fmt.Errorf("googleapi: Copy failed: %v", err)) - return - } - } - - mpw.Close() - pw.Close() - }() - return mp -} - -func (mp *multipartReader) Read(data []byte) (n int, err error) { - return mp.pr.Read(data) -} - -func (mp *multipartReader) Close() error { - if !mp.pipeOpen { - return nil - } - mp.pipeOpen = false - return mp.pr.Close() -} - -// CombineBodyMedia combines a json body with media content to create a multipart/related HTTP body. -// It returns a ReadCloser containing the combined body, and the overall "multipart/related" content type, with random boundary. -// -// The caller must call Close on the returned ReadCloser if reads are abandoned before reaching EOF. -func CombineBodyMedia(body io.Reader, bodyContentType string, media io.Reader, mediaContentType string) (io.ReadCloser, string) { - mp := newMultipartReader([]typeReader{ - {body, bodyContentType}, - {media, mediaContentType}, - }) - return mp, mp.ctype -} - -func typeHeader(contentType string) textproto.MIMEHeader { - h := make(textproto.MIMEHeader) - h.Set("Content-Type", contentType) - return h -} - -// PrepareUpload determines whether the data in the supplied reader should be -// uploaded in a single request, or in sequential chunks. -// chunkSize is the size of the chunk that media should be split into. -// If chunkSize is non-zero and the contents of media do not fit in a single -// chunk (or there is an error reading media), then media will be returned as a -// ResumableBuffer. Otherwise, media will be returned as a Reader. -// -// After PrepareUpload has been called, media should no longer be used: the -// media content should be accessed via one of the return values. -func PrepareUpload(media io.Reader, chunkSize int) (io.Reader, - *ResumableBuffer) { - if chunkSize == 0 { // do not chunk - return media, nil - } - - rb := NewResumableBuffer(media, chunkSize) - rdr, _, _, err := rb.Chunk() - - if err == io.EOF { // we can upload this in a single request - return rdr, nil - } - // err might be a non-EOF error. If it is, the next call to rb.Chunk will - // return the same error. Returning a ResumableBuffer ensures that this error - // will be handled at some point. - - return nil, rb -} diff --git a/Godeps/_workspace/src/google.golang.org/api/gensupport/params.go b/Godeps/_workspace/src/google.golang.org/api/gensupport/params.go deleted file mode 100644 index 3b3c74396..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/gensupport/params.go +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gensupport - -import ( - "net/url" - - "google.golang.org/api/googleapi" -) - -// URLParams is a simplified replacement for url.Values -// that safely builds up URL parameters for encoding. -type URLParams map[string][]string - -// Get returns the first value for the given key, or "". -func (u URLParams) Get(key string) string { - vs := u[key] - if len(vs) == 0 { - return "" - } - return vs[0] -} - -// Set sets the key to value. -// It replaces any existing values. -func (u URLParams) Set(key, value string) { - u[key] = []string{value} -} - -// SetMulti sets the key to an array of values. -// It replaces any existing values. -// Note that values must not be modified after calling SetMulti -// so the caller is responsible for making a copy if necessary. -func (u URLParams) SetMulti(key string, values []string) { - u[key] = values -} - -// Encode encodes the values into ``URL encoded'' form -// ("bar=baz&foo=quux") sorted by key. -func (u URLParams) Encode() string { - return url.Values(u).Encode() -} - -func SetOptions(u URLParams, opts ...googleapi.CallOption) { - for _, o := range opts { - u.Set(o.Get()) - } -} diff --git a/Godeps/_workspace/src/google.golang.org/api/gensupport/resumable.go b/Godeps/_workspace/src/google.golang.org/api/gensupport/resumable.go deleted file mode 100644 index adefc8897..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/gensupport/resumable.go +++ /dev/null @@ -1,177 +0,0 @@ -// Copyright 2016 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gensupport - -import ( - "fmt" - "io" - "net/http" - "sync" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/context/ctxhttp" -) - -const ( - // statusResumeIncomplete is the code returned by the Google uploader when the transfer is not yet complete. - statusResumeIncomplete = 308 -) - -// DefaultBackoffStrategy returns a default strategy to use for retrying failed upload requests. -func DefaultBackoffStrategy() BackoffStrategy { - return &ExponentialBackoff{BasePause: time.Second} -} - -// ResumableUpload is used by the generated APIs to provide resumable uploads. -// It is not used by developers directly. -type ResumableUpload struct { - Client *http.Client - // URI is the resumable resource destination provided by the server after specifying "&uploadType=resumable". - URI string - UserAgent string // User-Agent for header of the request - // Media is the object being uploaded. - Media *ResumableBuffer - // MediaType defines the media type, e.g. "image/jpeg". - MediaType string - - mu sync.Mutex // guards progress - progress int64 // number of bytes uploaded so far - - // Callback is an optional function that will be periodically called with the cumulative number of bytes uploaded. - Callback func(int64) - - // If not specified, a default exponential backoff strategy will be used. - Backoff BackoffStrategy -} - -// Progress returns the number of bytes uploaded at this point. -func (rx *ResumableUpload) Progress() int64 { - rx.mu.Lock() - defer rx.mu.Unlock() - return rx.progress -} - -// doUploadRequest performs a single HTTP request to upload data. -// off specifies the offset in rx.Media from which data is drawn. -// size is the number of bytes in data. -// final specifies whether data is the final chunk to be uploaded. -func (rx *ResumableUpload) doUploadRequest(ctx context.Context, data io.Reader, off, size int64, final bool) (*http.Response, error) { - req, err := http.NewRequest("POST", rx.URI, data) - if err != nil { - return nil, err - } - - req.ContentLength = size - var contentRange string - if final { - if size == 0 { - contentRange = fmt.Sprintf("bytes */%v", off) - } else { - contentRange = fmt.Sprintf("bytes %v-%v/%v", off, off+size-1, off+size) - } - } else { - contentRange = fmt.Sprintf("bytes %v-%v/*", off, off+size-1) - } - req.Header.Set("Content-Range", contentRange) - req.Header.Set("Content-Type", rx.MediaType) - req.Header.Set("User-Agent", rx.UserAgent) - return ctxhttp.Do(ctx, rx.Client, req) - -} - -// reportProgress calls a user-supplied callback to report upload progress. -// If old==updated, the callback is not called. -func (rx *ResumableUpload) reportProgress(old, updated int64) { - if updated-old == 0 { - return - } - rx.mu.Lock() - rx.progress = updated - rx.mu.Unlock() - if rx.Callback != nil { - rx.Callback(updated) - } -} - -// transferChunk performs a single HTTP request to upload a single chunk from rx.Media. -func (rx *ResumableUpload) transferChunk(ctx context.Context) (*http.Response, error) { - chunk, off, size, err := rx.Media.Chunk() - - done := err == io.EOF - if !done && err != nil { - return nil, err - } - - res, err := rx.doUploadRequest(ctx, chunk, off, int64(size), done) - if err != nil { - return res, err - } - - if res.StatusCode == statusResumeIncomplete || res.StatusCode == http.StatusOK { - rx.reportProgress(off, off+int64(size)) - } - - if res.StatusCode == statusResumeIncomplete { - rx.Media.Next() - } - return res, nil -} - -func contextDone(ctx context.Context) bool { - select { - case <-ctx.Done(): - return true - default: - return false - } -} - -// Upload starts the process of a resumable upload with a cancellable context. -// It retries indefinitely (using exponential backoff) until cancelled. -// It is called from the auto-generated API code and is not visible to the user. -// rx is private to the auto-generated API code. -// Exactly one of resp or err will be nil. If resp is non-nil, the caller must call resp.Body.Close. -func (rx *ResumableUpload) Upload(ctx context.Context) (resp *http.Response, err error) { - var pause time.Duration - backoff := rx.Backoff - if backoff == nil { - backoff = DefaultBackoffStrategy() - } - - for { - // Ensure that we return in the case of cancelled context, even if pause is 0. - if contextDone(ctx) { - return nil, ctx.Err() - } - select { - case <-ctx.Done(): - return nil, ctx.Err() - case <-time.After(pause): - } - - resp, err = rx.transferChunk(ctx) - // It's possible for err and resp to both be non-nil here, but we expose a simpler - // contract to our callers: exactly one of resp and err will be non-nil. This means - // that any response body must be closed here before returning a non-nil error. - if err != nil { - if resp != nil && resp.Body != nil { - resp.Body.Close() - } - return nil, err - } - if resp.StatusCode == http.StatusCreated || resp.StatusCode == http.StatusOK { - return resp, nil - } - resp.Body.Close() - - if resp.StatusCode == statusResumeIncomplete { - pause = 0 - backoff.Reset() - } else { - pause = backoff.Pause() - } - } -} diff --git a/Godeps/_workspace/src/google.golang.org/api/googleapi/googleapi.go b/Godeps/_workspace/src/google.golang.org/api/googleapi/googleapi.go deleted file mode 100644 index 8796e3e09..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/googleapi/googleapi.go +++ /dev/null @@ -1,418 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package googleapi contains the common code shared by all Google API -// libraries. -package googleapi - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "strings" - - "google.golang.org/api/googleapi/internal/uritemplates" -) - -// ContentTyper is an interface for Readers which know (or would like -// to override) their Content-Type. If a media body doesn't implement -// ContentTyper, the type is sniffed from the content using -// http.DetectContentType. -type ContentTyper interface { - ContentType() string -} - -// A SizeReaderAt is a ReaderAt with a Size method. -// An io.SectionReader implements SizeReaderAt. -type SizeReaderAt interface { - io.ReaderAt - Size() int64 -} - -// ServerResponse is embedded in each Do response and -// provides the HTTP status code and header sent by the server. -type ServerResponse struct { - // HTTPStatusCode is the server's response status code. - // When using a resource method's Do call, this will always be in the 2xx range. - HTTPStatusCode int - // Header contains the response header fields from the server. - Header http.Header -} - -const ( - Version = "0.5" - - // UserAgent is the header string used to identify this package. - UserAgent = "google-api-go-client/" + Version - - // The default chunk size to use for resumable uplods if not specified by the user. - DefaultUploadChunkSize = 8 * 1024 * 1024 - - // The minimum chunk size that can be used for resumable uploads. All - // user-specified chunk sizes must be multiple of this value. - MinUploadChunkSize = 256 * 1024 -) - -// Error contains an error response from the server. -type Error struct { - // Code is the HTTP response status code and will always be populated. - Code int `json:"code"` - // Message is the server response message and is only populated when - // explicitly referenced by the JSON server response. - Message string `json:"message"` - // Body is the raw response returned by the server. - // It is often but not always JSON, depending on how the request fails. - Body string - // Header contains the response header fields from the server. - Header http.Header - - Errors []ErrorItem -} - -// ErrorItem is a detailed error code & message from the Google API frontend. -type ErrorItem struct { - // Reason is the typed error code. For example: "some_example". - Reason string `json:"reason"` - // Message is the human-readable description of the error. - Message string `json:"message"` -} - -func (e *Error) Error() string { - if len(e.Errors) == 0 && e.Message == "" { - return fmt.Sprintf("googleapi: got HTTP response code %d with body: %v", e.Code, e.Body) - } - var buf bytes.Buffer - fmt.Fprintf(&buf, "googleapi: Error %d: ", e.Code) - if e.Message != "" { - fmt.Fprintf(&buf, "%s", e.Message) - } - if len(e.Errors) == 0 { - return strings.TrimSpace(buf.String()) - } - if len(e.Errors) == 1 && e.Errors[0].Message == e.Message { - fmt.Fprintf(&buf, ", %s", e.Errors[0].Reason) - return buf.String() - } - fmt.Fprintln(&buf, "\nMore details:") - for _, v := range e.Errors { - fmt.Fprintf(&buf, "Reason: %s, Message: %s\n", v.Reason, v.Message) - } - return buf.String() -} - -type errorReply struct { - Error *Error `json:"error"` -} - -// CheckResponse returns an error (of type *Error) if the response -// status code is not 2xx. -func CheckResponse(res *http.Response) error { - if res.StatusCode >= 200 && res.StatusCode <= 299 { - return nil - } - slurp, err := ioutil.ReadAll(res.Body) - if err == nil { - jerr := new(errorReply) - err = json.Unmarshal(slurp, jerr) - if err == nil && jerr.Error != nil { - if jerr.Error.Code == 0 { - jerr.Error.Code = res.StatusCode - } - jerr.Error.Body = string(slurp) - return jerr.Error - } - } - return &Error{ - Code: res.StatusCode, - Body: string(slurp), - Header: res.Header, - } -} - -// IsNotModified reports whether err is the result of the -// server replying with http.StatusNotModified. -// Such error values are sometimes returned by "Do" methods -// on calls when If-None-Match is used. -func IsNotModified(err error) bool { - if err == nil { - return false - } - ae, ok := err.(*Error) - return ok && ae.Code == http.StatusNotModified -} - -// CheckMediaResponse returns an error (of type *Error) if the response -// status code is not 2xx. Unlike CheckResponse it does not assume the -// body is a JSON error document. -func CheckMediaResponse(res *http.Response) error { - if res.StatusCode >= 200 && res.StatusCode <= 299 { - return nil - } - slurp, _ := ioutil.ReadAll(io.LimitReader(res.Body, 1<<20)) - res.Body.Close() - return &Error{ - Code: res.StatusCode, - Body: string(slurp), - } -} - -type MarshalStyle bool - -var WithDataWrapper = MarshalStyle(true) -var WithoutDataWrapper = MarshalStyle(false) - -func (wrap MarshalStyle) JSONReader(v interface{}) (io.Reader, error) { - buf := new(bytes.Buffer) - if wrap { - buf.Write([]byte(`{"data": `)) - } - err := json.NewEncoder(buf).Encode(v) - if err != nil { - return nil, err - } - if wrap { - buf.Write([]byte(`}`)) - } - return buf, nil -} - -// endingWithErrorReader from r until it returns an error. If the -// final error from r is io.EOF and e is non-nil, e is used instead. -type endingWithErrorReader struct { - r io.Reader - e error -} - -func (er endingWithErrorReader) Read(p []byte) (n int, err error) { - n, err = er.r.Read(p) - if err == io.EOF && er.e != nil { - err = er.e - } - return -} - -// countingWriter counts the number of bytes it receives to write, but -// discards them. -type countingWriter struct { - n *int64 -} - -func (w countingWriter) Write(p []byte) (int, error) { - *w.n += int64(len(p)) - return len(p), nil -} - -// ProgressUpdater is a function that is called upon every progress update of a resumable upload. -// This is the only part of a resumable upload (from googleapi) that is usable by the developer. -// The remaining usable pieces of resumable uploads is exposed in each auto-generated API. -type ProgressUpdater func(current, total int64) - -type MediaOption interface { - setOptions(o *MediaOptions) -} - -type contentTypeOption string - -func (ct contentTypeOption) setOptions(o *MediaOptions) { - o.ContentType = string(ct) -} - -// ContentType returns a MediaOption which sets the content type of data to be uploaded. -func ContentType(ctype string) MediaOption { - return contentTypeOption(ctype) -} - -type chunkSizeOption int - -func (cs chunkSizeOption) setOptions(o *MediaOptions) { - size := int(cs) - if size%MinUploadChunkSize != 0 { - size += MinUploadChunkSize - (size % MinUploadChunkSize) - } - o.ChunkSize = size -} - -// ChunkSize returns a MediaOption which sets the chunk size for media uploads. -// size will be rounded up to the nearest multiple of 256K. -// Media which contains fewer than size bytes will be uploaded in a single request. -// Media which contains size bytes or more will be uploaded in separate chunks. -// If size is zero, media will be uploaded in a single request. -func ChunkSize(size int) MediaOption { - return chunkSizeOption(size) -} - -// MediaOptions stores options for customizing media upload. It is not used by developers directly. -type MediaOptions struct { - ContentType string - ChunkSize int -} - -// ProcessMediaOptions stores options from opts in a MediaOptions. -// It is not used by developers directly. -func ProcessMediaOptions(opts []MediaOption) *MediaOptions { - mo := &MediaOptions{ChunkSize: DefaultUploadChunkSize} - for _, o := range opts { - o.setOptions(mo) - } - return mo -} - -func ResolveRelative(basestr, relstr string) string { - u, _ := url.Parse(basestr) - rel, _ := url.Parse(relstr) - u = u.ResolveReference(rel) - us := u.String() - us = strings.Replace(us, "%7B", "{", -1) - us = strings.Replace(us, "%7D", "}", -1) - return us -} - -// has4860Fix is whether this Go environment contains the fix for -// http://golang.org/issue/4860 -var has4860Fix bool - -// init initializes has4860Fix by checking the behavior of the net/http package. -func init() { - r := http.Request{ - URL: &url.URL{ - Scheme: "http", - Opaque: "//opaque", - }, - } - b := &bytes.Buffer{} - r.Write(b) - has4860Fix = bytes.HasPrefix(b.Bytes(), []byte("GET http")) -} - -// SetOpaque sets u.Opaque from u.Path such that HTTP requests to it -// don't alter any hex-escaped characters in u.Path. -func SetOpaque(u *url.URL) { - u.Opaque = "//" + u.Host + u.Path - if !has4860Fix { - u.Opaque = u.Scheme + ":" + u.Opaque - } -} - -// Expand subsitutes any {encoded} strings in the URL passed in using -// the map supplied. -// -// This calls SetOpaque to avoid encoding of the parameters in the URL path. -func Expand(u *url.URL, expansions map[string]string) { - expanded, err := uritemplates.Expand(u.Path, expansions) - if err == nil { - u.Path = expanded - SetOpaque(u) - } -} - -// CloseBody is used to close res.Body. -// Prior to calling Close, it also tries to Read a small amount to see an EOF. -// Not seeing an EOF can prevent HTTP Transports from reusing connections. -func CloseBody(res *http.Response) { - if res == nil || res.Body == nil { - return - } - // Justification for 3 byte reads: two for up to "\r\n" after - // a JSON/XML document, and then 1 to see EOF if we haven't yet. - // TODO(bradfitz): detect Go 1.3+ and skip these reads. - // See https://codereview.appspot.com/58240043 - // and https://codereview.appspot.com/49570044 - buf := make([]byte, 1) - for i := 0; i < 3; i++ { - _, err := res.Body.Read(buf) - if err != nil { - break - } - } - res.Body.Close() - -} - -// VariantType returns the type name of the given variant. -// If the map doesn't contain the named key or the value is not a []interface{}, "" is returned. -// This is used to support "variant" APIs that can return one of a number of different types. -func VariantType(t map[string]interface{}) string { - s, _ := t["type"].(string) - return s -} - -// ConvertVariant uses the JSON encoder/decoder to fill in the struct 'dst' with the fields found in variant 'v'. -// This is used to support "variant" APIs that can return one of a number of different types. -// It reports whether the conversion was successful. -func ConvertVariant(v map[string]interface{}, dst interface{}) bool { - var buf bytes.Buffer - err := json.NewEncoder(&buf).Encode(v) - if err != nil { - return false - } - return json.Unmarshal(buf.Bytes(), dst) == nil -} - -// A Field names a field to be retrieved with a partial response. -// See https://developers.google.com/gdata/docs/2.0/basics#PartialResponse -// -// Partial responses can dramatically reduce the amount of data that must be sent to your application. -// In order to request partial responses, you can specify the full list of fields -// that your application needs by adding the Fields option to your request. -// -// Field strings use camelCase with leading lower-case characters to identify fields within the response. -// -// For example, if your response has a "NextPageToken" and a slice of "Items" with "Id" fields, -// you could request just those fields like this: -// -// svc.Events.List().Fields("nextPageToken", "items/id").Do() -// -// or if you were also interested in each Item's "Updated" field, you can combine them like this: -// -// svc.Events.List().Fields("nextPageToken", "items(id,updated)").Do() -// -// More information about field formatting can be found here: -// https://developers.google.com/+/api/#fields-syntax -// -// Another way to find field names is through the Google API explorer: -// https://developers.google.com/apis-explorer/#p/ -type Field string - -// CombineFields combines fields into a single string. -func CombineFields(s []Field) string { - r := make([]string, len(s)) - for i, v := range s { - r[i] = string(v) - } - return strings.Join(r, ",") -} - -// A CallOption is an optional argument to an API call. -// It should be treated as an opaque value by users of Google APIs. -// -// A CallOption is something that configures an API call in a way that is -// not specific to that API; for instance, controlling the quota user for -// an API call is common across many APIs, and is thus a CallOption. -type CallOption interface { - Get() (key, value string) -} - -// QuotaUser returns a CallOption that will set the quota user for a call. -// The quota user can be used by server-side applications to control accounting. -// It can be an arbitrary string up to 40 characters, and will override UserIP -// if both are provided. -func QuotaUser(u string) CallOption { return quotaUser(u) } - -type quotaUser string - -func (q quotaUser) Get() (string, string) { return "quotaUser", string(q) } - -// UserIP returns a CallOption that will set the "userIp" parameter of a call. -// This should be the IP address of the originating request. -func UserIP(ip string) CallOption { return userIP(ip) } - -type userIP string - -func (i userIP) Get() (string, string) { return "userIp", string(i) } - -// TODO: Fields too diff --git a/Godeps/_workspace/src/google.golang.org/api/googleapi/internal/uritemplates/LICENSE b/Godeps/_workspace/src/google.golang.org/api/googleapi/internal/uritemplates/LICENSE deleted file mode 100644 index de9c88cb6..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/googleapi/internal/uritemplates/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -Copyright (c) 2013 Joshua Tacoma - -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/Godeps/_workspace/src/google.golang.org/api/googleapi/internal/uritemplates/uritemplates.go b/Godeps/_workspace/src/google.golang.org/api/googleapi/internal/uritemplates/uritemplates.go deleted file mode 100644 index 8a84813fe..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/googleapi/internal/uritemplates/uritemplates.go +++ /dev/null @@ -1,359 +0,0 @@ -// Copyright 2013 Joshua Tacoma. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package uritemplates is a level 4 implementation of RFC 6570 (URI -// Template, http://tools.ietf.org/html/rfc6570). -// -// To use uritemplates, parse a template string and expand it with a value -// map: -// -// template, _ := uritemplates.Parse("https://api.github.com/repos{/user,repo}") -// values := make(map[string]interface{}) -// values["user"] = "jtacoma" -// values["repo"] = "uritemplates" -// expanded, _ := template.ExpandString(values) -// fmt.Printf(expanded) -// -package uritemplates - -import ( - "bytes" - "errors" - "fmt" - "reflect" - "regexp" - "strconv" - "strings" -) - -var ( - unreserved = regexp.MustCompile("[^A-Za-z0-9\\-._~]") - reserved = regexp.MustCompile("[^A-Za-z0-9\\-._~:/?#[\\]@!$&'()*+,;=]") - validname = regexp.MustCompile("^([A-Za-z0-9_\\.]|%[0-9A-Fa-f][0-9A-Fa-f])+$") - hex = []byte("0123456789ABCDEF") -) - -func pctEncode(src []byte) []byte { - dst := make([]byte, len(src)*3) - for i, b := range src { - buf := dst[i*3 : i*3+3] - buf[0] = 0x25 - buf[1] = hex[b/16] - buf[2] = hex[b%16] - } - return dst -} - -func escape(s string, allowReserved bool) (escaped string) { - if allowReserved { - escaped = string(reserved.ReplaceAllFunc([]byte(s), pctEncode)) - } else { - escaped = string(unreserved.ReplaceAllFunc([]byte(s), pctEncode)) - } - return escaped -} - -// A UriTemplate is a parsed representation of a URI template. -type UriTemplate struct { - raw string - parts []templatePart -} - -// Parse parses a URI template string into a UriTemplate object. -func Parse(rawtemplate string) (template *UriTemplate, err error) { - template = new(UriTemplate) - template.raw = rawtemplate - split := strings.Split(rawtemplate, "{") - template.parts = make([]templatePart, len(split)*2-1) - for i, s := range split { - if i == 0 { - if strings.Contains(s, "}") { - err = errors.New("unexpected }") - break - } - template.parts[i].raw = s - } else { - subsplit := strings.Split(s, "}") - if len(subsplit) != 2 { - err = errors.New("malformed template") - break - } - expression := subsplit[0] - template.parts[i*2-1], err = parseExpression(expression) - if err != nil { - break - } - template.parts[i*2].raw = subsplit[1] - } - } - if err != nil { - template = nil - } - return template, err -} - -type templatePart struct { - raw string - terms []templateTerm - first string - sep string - named bool - ifemp string - allowReserved bool -} - -type templateTerm struct { - name string - explode bool - truncate int -} - -func parseExpression(expression string) (result templatePart, err error) { - switch expression[0] { - case '+': - result.sep = "," - result.allowReserved = true - expression = expression[1:] - case '.': - result.first = "." - result.sep = "." - expression = expression[1:] - case '/': - result.first = "/" - result.sep = "/" - expression = expression[1:] - case ';': - result.first = ";" - result.sep = ";" - result.named = true - expression = expression[1:] - case '?': - result.first = "?" - result.sep = "&" - result.named = true - result.ifemp = "=" - expression = expression[1:] - case '&': - result.first = "&" - result.sep = "&" - result.named = true - result.ifemp = "=" - expression = expression[1:] - case '#': - result.first = "#" - result.sep = "," - result.allowReserved = true - expression = expression[1:] - default: - result.sep = "," - } - rawterms := strings.Split(expression, ",") - result.terms = make([]templateTerm, len(rawterms)) - for i, raw := range rawterms { - result.terms[i], err = parseTerm(raw) - if err != nil { - break - } - } - return result, err -} - -func parseTerm(term string) (result templateTerm, err error) { - if strings.HasSuffix(term, "*") { - result.explode = true - term = term[:len(term)-1] - } - split := strings.Split(term, ":") - if len(split) == 1 { - result.name = term - } else if len(split) == 2 { - result.name = split[0] - var parsed int64 - parsed, err = strconv.ParseInt(split[1], 10, 0) - result.truncate = int(parsed) - } else { - err = errors.New("multiple colons in same term") - } - if !validname.MatchString(result.name) { - err = errors.New("not a valid name: " + result.name) - } - if result.explode && result.truncate > 0 { - err = errors.New("both explode and prefix modifers on same term") - } - return result, err -} - -// Expand expands a URI template with a set of values to produce a string. -func (self *UriTemplate) Expand(value interface{}) (string, error) { - values, ismap := value.(map[string]interface{}) - if !ismap { - if m, ismap := struct2map(value); !ismap { - return "", errors.New("expected map[string]interface{}, struct, or pointer to struct.") - } else { - return self.Expand(m) - } - } - var buf bytes.Buffer - for _, p := range self.parts { - err := p.expand(&buf, values) - if err != nil { - return "", err - } - } - return buf.String(), nil -} - -func (self *templatePart) expand(buf *bytes.Buffer, values map[string]interface{}) error { - if len(self.raw) > 0 { - buf.WriteString(self.raw) - return nil - } - var zeroLen = buf.Len() - buf.WriteString(self.first) - var firstLen = buf.Len() - for _, term := range self.terms { - value, exists := values[term.name] - if !exists { - continue - } - if buf.Len() != firstLen { - buf.WriteString(self.sep) - } - switch v := value.(type) { - case string: - self.expandString(buf, term, v) - case []interface{}: - self.expandArray(buf, term, v) - case map[string]interface{}: - if term.truncate > 0 { - return errors.New("cannot truncate a map expansion") - } - self.expandMap(buf, term, v) - default: - if m, ismap := struct2map(value); ismap { - if term.truncate > 0 { - return errors.New("cannot truncate a map expansion") - } - self.expandMap(buf, term, m) - } else { - str := fmt.Sprintf("%v", value) - self.expandString(buf, term, str) - } - } - } - if buf.Len() == firstLen { - original := buf.Bytes()[:zeroLen] - buf.Reset() - buf.Write(original) - } - return nil -} - -func (self *templatePart) expandName(buf *bytes.Buffer, name string, empty bool) { - if self.named { - buf.WriteString(name) - if empty { - buf.WriteString(self.ifemp) - } else { - buf.WriteString("=") - } - } -} - -func (self *templatePart) expandString(buf *bytes.Buffer, t templateTerm, s string) { - if len(s) > t.truncate && t.truncate > 0 { - s = s[:t.truncate] - } - self.expandName(buf, t.name, len(s) == 0) - buf.WriteString(escape(s, self.allowReserved)) -} - -func (self *templatePart) expandArray(buf *bytes.Buffer, t templateTerm, a []interface{}) { - if len(a) == 0 { - return - } else if !t.explode { - self.expandName(buf, t.name, false) - } - for i, value := range a { - if t.explode && i > 0 { - buf.WriteString(self.sep) - } else if i > 0 { - buf.WriteString(",") - } - var s string - switch v := value.(type) { - case string: - s = v - default: - s = fmt.Sprintf("%v", v) - } - if len(s) > t.truncate && t.truncate > 0 { - s = s[:t.truncate] - } - if self.named && t.explode { - self.expandName(buf, t.name, len(s) == 0) - } - buf.WriteString(escape(s, self.allowReserved)) - } -} - -func (self *templatePart) expandMap(buf *bytes.Buffer, t templateTerm, m map[string]interface{}) { - if len(m) == 0 { - return - } - if !t.explode { - self.expandName(buf, t.name, len(m) == 0) - } - var firstLen = buf.Len() - for k, value := range m { - if firstLen != buf.Len() { - if t.explode { - buf.WriteString(self.sep) - } else { - buf.WriteString(",") - } - } - var s string - switch v := value.(type) { - case string: - s = v - default: - s = fmt.Sprintf("%v", v) - } - if t.explode { - buf.WriteString(escape(k, self.allowReserved)) - buf.WriteRune('=') - buf.WriteString(escape(s, self.allowReserved)) - } else { - buf.WriteString(escape(k, self.allowReserved)) - buf.WriteRune(',') - buf.WriteString(escape(s, self.allowReserved)) - } - } -} - -func struct2map(v interface{}) (map[string]interface{}, bool) { - value := reflect.ValueOf(v) - switch value.Type().Kind() { - case reflect.Ptr: - return struct2map(value.Elem().Interface()) - case reflect.Struct: - m := make(map[string]interface{}) - for i := 0; i < value.NumField(); i++ { - tag := value.Type().Field(i).Tag - var name string - if strings.Contains(string(tag), ":") { - name = tag.Get("uri") - } else { - name = strings.TrimSpace(string(tag)) - } - if len(name) == 0 { - name = value.Type().Field(i).Name - } - m[name] = value.Field(i).Interface() - } - return m, true - } - return nil, false -} diff --git a/Godeps/_workspace/src/google.golang.org/api/googleapi/internal/uritemplates/utils.go b/Godeps/_workspace/src/google.golang.org/api/googleapi/internal/uritemplates/utils.go deleted file mode 100644 index 399ef4623..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/googleapi/internal/uritemplates/utils.go +++ /dev/null @@ -1,13 +0,0 @@ -package uritemplates - -func Expand(path string, expansions map[string]string) (string, error) { - template, err := Parse(path) - if err != nil { - return "", err - } - values := make(map[string]interface{}) - for k, v := range expansions { - values[k] = v - } - return template.Expand(values) -} diff --git a/Godeps/_workspace/src/google.golang.org/api/googleapi/types.go b/Godeps/_workspace/src/google.golang.org/api/googleapi/types.go deleted file mode 100644 index a02b4b071..000000000 --- a/Godeps/_workspace/src/google.golang.org/api/googleapi/types.go +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2013 Google Inc. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package googleapi - -import ( - "encoding/json" - "strconv" -) - -// Int64s is a slice of int64s that marshal as quoted strings in JSON. -type Int64s []int64 - -func (q *Int64s) UnmarshalJSON(raw []byte) error { - *q = (*q)[:0] - var ss []string - if err := json.Unmarshal(raw, &ss); err != nil { - return err - } - for _, s := range ss { - v, err := strconv.ParseInt(s, 10, 64) - if err != nil { - return err - } - *q = append(*q, int64(v)) - } - return nil -} - -// Int32s is a slice of int32s that marshal as quoted strings in JSON. -type Int32s []int32 - -func (q *Int32s) UnmarshalJSON(raw []byte) error { - *q = (*q)[:0] - var ss []string - if err := json.Unmarshal(raw, &ss); err != nil { - return err - } - for _, s := range ss { - v, err := strconv.ParseInt(s, 10, 32) - if err != nil { - return err - } - *q = append(*q, int32(v)) - } - return nil -} - -// Uint64s is a slice of uint64s that marshal as quoted strings in JSON. -type Uint64s []uint64 - -func (q *Uint64s) UnmarshalJSON(raw []byte) error { - *q = (*q)[:0] - var ss []string - if err := json.Unmarshal(raw, &ss); err != nil { - return err - } - for _, s := range ss { - v, err := strconv.ParseUint(s, 10, 64) - if err != nil { - return err - } - *q = append(*q, uint64(v)) - } - return nil -} - -// Uint32s is a slice of uint32s that marshal as quoted strings in JSON. -type Uint32s []uint32 - -func (q *Uint32s) UnmarshalJSON(raw []byte) error { - *q = (*q)[:0] - var ss []string - if err := json.Unmarshal(raw, &ss); err != nil { - return err - } - for _, s := range ss { - v, err := strconv.ParseUint(s, 10, 32) - if err != nil { - return err - } - *q = append(*q, uint32(v)) - } - return nil -} - -// Float64s is a slice of float64s that marshal as quoted strings in JSON. -type Float64s []float64 - -func (q *Float64s) UnmarshalJSON(raw []byte) error { - *q = (*q)[:0] - var ss []string - if err := json.Unmarshal(raw, &ss); err != nil { - return err - } - for _, s := range ss { - v, err := strconv.ParseFloat(s, 64) - if err != nil { - return err - } - *q = append(*q, float64(v)) - } - return nil -} - -func quotedList(n int, fn func(dst []byte, i int) []byte) ([]byte, error) { - dst := make([]byte, 0, 2+n*10) // somewhat arbitrary - dst = append(dst, '[') - for i := 0; i < n; i++ { - if i > 0 { - dst = append(dst, ',') - } - dst = append(dst, '"') - dst = fn(dst, i) - dst = append(dst, '"') - } - dst = append(dst, ']') - return dst, nil -} - -func (s Int64s) MarshalJSON() ([]byte, error) { - return quotedList(len(s), func(dst []byte, i int) []byte { - return strconv.AppendInt(dst, s[i], 10) - }) -} - -func (s Int32s) MarshalJSON() ([]byte, error) { - return quotedList(len(s), func(dst []byte, i int) []byte { - return strconv.AppendInt(dst, int64(s[i]), 10) - }) -} - -func (s Uint64s) MarshalJSON() ([]byte, error) { - return quotedList(len(s), func(dst []byte, i int) []byte { - return strconv.AppendUint(dst, s[i], 10) - }) -} - -func (s Uint32s) MarshalJSON() ([]byte, error) { - return quotedList(len(s), func(dst []byte, i int) []byte { - return strconv.AppendUint(dst, uint64(s[i]), 10) - }) -} - -func (s Float64s) MarshalJSON() ([]byte, error) { - return quotedList(len(s), func(dst []byte, i int) []byte { - return strconv.AppendFloat(dst, s[i], 'g', -1, 64) - }) -} - -/* - * Helper routines for simplifying the creation of optional fields of basic type. - */ - -// Bool is a helper routine that allocates a new bool value -// to store v and returns a pointer to it. -func Bool(v bool) *bool { return &v } - -// Int32 is a helper routine that allocates a new int32 value -// to store v and returns a pointer to it. -func Int32(v int32) *int32 { return &v } - -// Int64 is a helper routine that allocates a new int64 value -// to store v and returns a pointer to it. -func Int64(v int64) *int64 { return &v } - -// Float64 is a helper routine that allocates a new float64 value -// to store v and returns a pointer to it. -func Float64(v float64) *float64 { return &v } - -// Uint32 is a helper routine that allocates a new uint32 value -// to store v and returns a pointer to it. -func Uint32(v uint32) *uint32 { return &v } - -// Uint64 is a helper routine that allocates a new uint64 value -// to store v and returns a pointer to it. -func Uint64(v uint64) *uint64 { return &v } - -// String is a helper routine that allocates a new string value -// to store v and returns a pointer to it. -func String(v string) *string { return &v } diff --git a/Godeps/_workspace/src/google.golang.org/appengine/.travis.yml b/Godeps/_workspace/src/google.golang.org/appengine/.travis.yml deleted file mode 100644 index 771520977..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -language: go -sudo: false - -go: - - 1.4 - -install: - - go get -v -t -d google.golang.org/appengine/... - - mkdir sdk - - curl -o sdk.zip "https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.24.zip" - - unzip sdk.zip -d sdk - - export APPENGINE_DEV_APPSERVER=$(pwd)/sdk/go_appengine/dev_appserver.py - -script: - - go version - - go test -v google.golang.org/appengine/... - - go test -v -race google.golang.org/appengine/... - - sdk/go_appengine/goapp test -v google.golang.org/appengine/... diff --git a/Godeps/_workspace/src/google.golang.org/appengine/LICENSE b/Godeps/_workspace/src/google.golang.org/appengine/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (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/Godeps/_workspace/src/google.golang.org/appengine/README.md b/Godeps/_workspace/src/google.golang.org/appengine/README.md deleted file mode 100644 index 168245fb7..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/README.md +++ /dev/null @@ -1,75 +0,0 @@ -# Go App Engine packages - -[![Build Status](https://travis-ci.org/golang/appengine.svg)](https://travis-ci.org/golang/appengine) - -This repository supports the Go runtime on App Engine, -including both the standard App Engine and the -"App Engine flexible environment" (formerly known as "Managed VMs"). -It provides APIs for interacting with App Engine services. -Its canonical import path is `google.golang.org/appengine`. - -See https://cloud.google.com/appengine/docs/go/ -for more information. - -File issue reports and feature requests on the [Google App Engine issue -tracker](https://code.google.com/p/googleappengine/issues/entry?template=Go%20defect). - -## Directory structure -The top level directory of this repository is the `appengine` package. It -contains the -basic APIs (e.g. `appengine.NewContext`) that apply across APIs. Specific API -packages are in subdirectories (e.g. `datastore`). - -There is an `internal` subdirectory that contains service protocol buffers, -plus packages required for connectivity to make API calls. App Engine apps -should not directly import any package under `internal`. - -## Updating a Go App Engine app - -This section describes how to update a traditional Go App Engine app to use -these packages. - -### 1. Update YAML files (App Engine flexible environment / Managed VMs only) - -The `app.yaml` file (and YAML files for modules) should have these new lines added: -``` -vm: true -``` -See https://cloud.google.com/appengine/docs/go/modules/#Go_Instance_scaling_and_class for details. - -### 2. Update import paths - -The import paths for App Engine packages are now fully qualified, based at `google.golang.org/appengine`. -You will need to update your code to use import paths starting with that; for instance, -code importing `appengine/datastore` will now need to import `google.golang.org/appengine/datastore`. -You can do that manually, or by running this command to recursively update all Go source files in the current directory: -(may require GNU sed) -``` -sed -i '/"appengine/{s,"appengine,"google.golang.org/appengine,;s,appengine_,appengine/,}' \ - $(find . -name '*.go') -``` - -### 3. Update code using deprecated, removed or modified APIs - -Most App Engine services are available with exactly the same API. -A few APIs were cleaned up, and some are not available yet. -This list summarises the differences: - -* `appengine.Context` has been replaced with the `Context` type from `golang.org/x/net/context`. -* Logging methods that were on `appengine.Context` are now functions in `google.golang.org/appengine/log`. -* `appengine.Timeout` has been removed. Use `context.WithTimeout` instead. -* `appengine.Datacenter` now takes a `context.Context` argument. -* `datastore.PropertyLoadSaver` has been simplified to use slices in place of channels. -* `delay.Call` now returns an error. -* `search.FieldLoadSaver` now handles document metadata. -* `urlfetch.Transport` no longer has a Deadline field; set a deadline on the - `context.Context` instead. -* `aetest` no longer declares its own Context type, and uses the standard one instead. -* `taskqueue.QueueStats` no longer takes a maxTasks argument. That argument has been - deprecated and unused for a long time. -* `appengine.BackendHostname` and `appengine.BackendInstance` were for the deprecated backends feature. - Use `appengine.ModuleHostname`and `appengine.ModuleName` instead. -* Most of `appengine/file` and parts of `appengine/blobstore` are deprecated. - Use [Google Cloud Storage](https://godoc.org/google.golang.org/cloud/storage) instead. -* `appengine/socket` is not required on App Engine flexible environment / Managed VMs. - Use the standard `net` package instead. diff --git a/Godeps/_workspace/src/google.golang.org/appengine/appengine.go b/Godeps/_workspace/src/google.golang.org/appengine/appengine.go deleted file mode 100644 index be0b5f2bc..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/appengine.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// Package appengine provides basic functionality for Google App Engine. -// -// For more information on how to write Go apps for Google App Engine, see: -// https://cloud.google.com/appengine/docs/go/ -package appengine - -import ( - "net/http" - - "github.com/golang/protobuf/proto" - "golang.org/x/net/context" - - "google.golang.org/appengine/internal" -) - -// IsDevAppServer reports whether the App Engine app is running in the -// development App Server. -func IsDevAppServer() bool { - return internal.IsDevAppServer() -} - -// NewContext returns a context for an in-flight HTTP request. -// This function is cheap. -func NewContext(req *http.Request) context.Context { - return WithContext(context.Background(), req) -} - -// WithContext returns a copy of the parent context -// and associates it with an in-flight HTTP request. -// This function is cheap. -func WithContext(parent context.Context, req *http.Request) context.Context { - return internal.WithContext(parent, req) -} - -// TODO(dsymonds): Add a Call function here? Otherwise other packages can't access internal.Call. - -// BlobKey is a key for a blobstore blob. -// -// Conceptually, this type belongs in the blobstore package, but it lives in -// the appengine package to avoid a circular dependency: blobstore depends on -// datastore, and datastore needs to refer to the BlobKey type. -type BlobKey string - -// GeoPoint represents a location as latitude/longitude in degrees. -type GeoPoint struct { - Lat, Lng float64 -} - -// Valid returns whether a GeoPoint is within [-90, 90] latitude and [-180, 180] longitude. -func (g GeoPoint) Valid() bool { - return -90 <= g.Lat && g.Lat <= 90 && -180 <= g.Lng && g.Lng <= 180 -} - -// APICallFunc defines a function type for handling an API call. -// See WithCallOverride. -type APICallFunc func(ctx context.Context, service, method string, in, out proto.Message) error - -// WithAPICallFunc returns a copy of the parent context -// that will cause API calls to invoke f instead of their normal operation. -// -// This is intended for advanced users only. -func WithAPICallFunc(ctx context.Context, f APICallFunc) context.Context { - return internal.WithCallOverride(ctx, internal.CallOverrideFunc(f)) -} - -// APICall performs an API call. -// -// This is not intended for general use; it is exported for use in conjunction -// with WithAPICallFunc. -func APICall(ctx context.Context, service, method string, in, out proto.Message) error { - return internal.Call(ctx, service, method, in, out) -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/appengine_vm.go b/Godeps/_workspace/src/google.golang.org/appengine/appengine_vm.go deleted file mode 100644 index e4399ed7d..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/appengine_vm.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build !appengine - -package appengine - -import ( - "golang.org/x/net/context" - - "google.golang.org/appengine/internal" -) - -// The comment below must not be changed. -// It is used by go-app-builder to recognise that this package has -// the Main function to use in the synthetic main. -// The gophers party all night; the rabbits provide the beats. - -// Main is the principal entry point for an app running in App Engine "flexible environment". -// It installs a trivial health checker if one isn't already registered, -// and starts listening on port 8080 (overridden by the $PORT environment -// variable). -// -// See https://cloud.google.com/appengine/docs/flexible/custom-runtimes#health_check_requests -// for details on how to do your own health checking. -// -// Main never returns. -// -// Main is designed so that the app's main package looks like this: -// -// package main -// -// import ( -// "google.golang.org/appengine" -// -// _ "myapp/package0" -// _ "myapp/package1" -// ) -// -// func main() { -// appengine.Main() -// } -// -// The "myapp/packageX" packages are expected to register HTTP handlers -// in their init functions. -func Main() { - internal.Main() -} - -// BackgroundContext returns a context not associated with a request. -// This should only be used when not servicing a request. -// This only works in App Engine "flexible environment". -func BackgroundContext() context.Context { - return internal.BackgroundContext() -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/errors.go b/Godeps/_workspace/src/google.golang.org/appengine/errors.go deleted file mode 100644 index 16d0772e2..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/errors.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// This file provides error functions for common API failure modes. - -package appengine - -import ( - "fmt" - - "google.golang.org/appengine/internal" -) - -// IsOverQuota reports whether err represents an API call failure -// due to insufficient available quota. -func IsOverQuota(err error) bool { - callErr, ok := err.(*internal.CallError) - return ok && callErr.Code == 4 -} - -// MultiError is returned by batch operations when there are errors with -// particular elements. Errors will be in a one-to-one correspondence with -// the input elements; successful elements will have a nil entry. -type MultiError []error - -func (m MultiError) Error() string { - s, n := "", 0 - for _, e := range m { - if e != nil { - if n == 0 { - s = e.Error() - } - n++ - } - } - switch n { - case 0: - return "(0 errors)" - case 1: - return s - case 2: - return s + " (and 1 other error)" - } - return fmt.Sprintf("%s (and %d other errors)", s, n-1) -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/identity.go b/Godeps/_workspace/src/google.golang.org/appengine/identity.go deleted file mode 100644 index b8dcf8f36..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/identity.go +++ /dev/null @@ -1,142 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package appengine - -import ( - "time" - - "golang.org/x/net/context" - - "google.golang.org/appengine/internal" - pb "google.golang.org/appengine/internal/app_identity" - modpb "google.golang.org/appengine/internal/modules" -) - -// AppID returns the application ID for the current application. -// The string will be a plain application ID (e.g. "appid"), with a -// domain prefix for custom domain deployments (e.g. "example.com:appid"). -func AppID(c context.Context) string { return internal.AppID(c) } - -// DefaultVersionHostname returns the standard hostname of the default version -// of the current application (e.g. "my-app.appspot.com"). This is suitable for -// use in constructing URLs. -func DefaultVersionHostname(c context.Context) string { - return internal.DefaultVersionHostname(c) -} - -// ModuleName returns the module name of the current instance. -func ModuleName(c context.Context) string { - return internal.ModuleName(c) -} - -// ModuleHostname returns a hostname of a module instance. -// If module is the empty string, it refers to the module of the current instance. -// If version is empty, it refers to the version of the current instance if valid, -// or the default version of the module of the current instance. -// If instance is empty, ModuleHostname returns the load-balancing hostname. -func ModuleHostname(c context.Context, module, version, instance string) (string, error) { - req := &modpb.GetHostnameRequest{} - if module != "" { - req.Module = &module - } - if version != "" { - req.Version = &version - } - if instance != "" { - req.Instance = &instance - } - res := &modpb.GetHostnameResponse{} - if err := internal.Call(c, "modules", "GetHostname", req, res); err != nil { - return "", err - } - return *res.Hostname, nil -} - -// VersionID returns the version ID for the current application. -// It will be of the form "X.Y", where X is specified in app.yaml, -// and Y is a number generated when each version of the app is uploaded. -// It does not include a module name. -func VersionID(c context.Context) string { return internal.VersionID(c) } - -// InstanceID returns a mostly-unique identifier for this instance. -func InstanceID() string { return internal.InstanceID() } - -// Datacenter returns an identifier for the datacenter that the instance is running in. -func Datacenter(c context.Context) string { return internal.Datacenter(c) } - -// ServerSoftware returns the App Engine release version. -// In production, it looks like "Google App Engine/X.Y.Z". -// In the development appserver, it looks like "Development/X.Y". -func ServerSoftware() string { return internal.ServerSoftware() } - -// RequestID returns a string that uniquely identifies the request. -func RequestID(c context.Context) string { return internal.RequestID(c) } - -// AccessToken generates an OAuth2 access token for the specified scopes on -// behalf of service account of this application. This token will expire after -// the returned time. -func AccessToken(c context.Context, scopes ...string) (token string, expiry time.Time, err error) { - req := &pb.GetAccessTokenRequest{Scope: scopes} - res := &pb.GetAccessTokenResponse{} - - err = internal.Call(c, "app_identity_service", "GetAccessToken", req, res) - if err != nil { - return "", time.Time{}, err - } - return res.GetAccessToken(), time.Unix(res.GetExpirationTime(), 0), nil -} - -// Certificate represents a public certificate for the app. -type Certificate struct { - KeyName string - Data []byte // PEM-encoded X.509 certificate -} - -// PublicCertificates retrieves the public certificates for the app. -// They can be used to verify a signature returned by SignBytes. -func PublicCertificates(c context.Context) ([]Certificate, error) { - req := &pb.GetPublicCertificateForAppRequest{} - res := &pb.GetPublicCertificateForAppResponse{} - if err := internal.Call(c, "app_identity_service", "GetPublicCertificatesForApp", req, res); err != nil { - return nil, err - } - var cs []Certificate - for _, pc := range res.PublicCertificateList { - cs = append(cs, Certificate{ - KeyName: pc.GetKeyName(), - Data: []byte(pc.GetX509CertificatePem()), - }) - } - return cs, nil -} - -// ServiceAccount returns a string representing the service account name, in -// the form of an email address (typically app_id@appspot.gserviceaccount.com). -func ServiceAccount(c context.Context) (string, error) { - req := &pb.GetServiceAccountNameRequest{} - res := &pb.GetServiceAccountNameResponse{} - - err := internal.Call(c, "app_identity_service", "GetServiceAccountName", req, res) - if err != nil { - return "", err - } - return res.GetServiceAccountName(), err -} - -// SignBytes signs bytes using a private key unique to your application. -func SignBytes(c context.Context, bytes []byte) (keyName string, signature []byte, err error) { - req := &pb.SignForAppRequest{BytesToSign: bytes} - res := &pb.SignForAppResponse{} - - if err := internal.Call(c, "app_identity_service", "SignForApp", req, res); err != nil { - return "", nil, err - } - return res.GetKeyName(), res.GetSignatureBytes(), nil -} - -func init() { - internal.RegisterErrorCodeMap("app_identity_service", pb.AppIdentityServiceError_ErrorCode_name) - internal.RegisterErrorCodeMap("modules", modpb.ModulesServiceError_ErrorCode_name) -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/api.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/api.go deleted file mode 100644 index aa139d4d5..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/api.go +++ /dev/null @@ -1,640 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build !appengine - -package internal - -import ( - "bytes" - "errors" - "fmt" - "io/ioutil" - "log" - "net" - "net/http" - "net/url" - "os" - "runtime" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" - - "github.com/golang/protobuf/proto" - netcontext "golang.org/x/net/context" - - basepb "google.golang.org/appengine/internal/base" - logpb "google.golang.org/appengine/internal/log" - remotepb "google.golang.org/appengine/internal/remote_api" -) - -const ( - apiPath = "/rpc_http" -) - -var ( - // Incoming headers. - ticketHeader = http.CanonicalHeaderKey("X-AppEngine-API-Ticket") - dapperHeader = http.CanonicalHeaderKey("X-Google-DapperTraceInfo") - traceHeader = http.CanonicalHeaderKey("X-Cloud-Trace-Context") - curNamespaceHeader = http.CanonicalHeaderKey("X-AppEngine-Current-Namespace") - userIPHeader = http.CanonicalHeaderKey("X-AppEngine-User-IP") - remoteAddrHeader = http.CanonicalHeaderKey("X-AppEngine-Remote-Addr") - - // Outgoing headers. - apiEndpointHeader = http.CanonicalHeaderKey("X-Google-RPC-Service-Endpoint") - apiEndpointHeaderValue = []string{"app-engine-apis"} - apiMethodHeader = http.CanonicalHeaderKey("X-Google-RPC-Service-Method") - apiMethodHeaderValue = []string{"/VMRemoteAPI.CallRemoteAPI"} - apiDeadlineHeader = http.CanonicalHeaderKey("X-Google-RPC-Service-Deadline") - apiContentType = http.CanonicalHeaderKey("Content-Type") - apiContentTypeValue = []string{"application/octet-stream"} - logFlushHeader = http.CanonicalHeaderKey("X-AppEngine-Log-Flush-Count") - - apiHTTPClient = &http.Client{ - Transport: &http.Transport{ - Proxy: http.ProxyFromEnvironment, - Dial: limitDial, - }, - } -) - -func apiURL() *url.URL { - host, port := "appengine.googleapis.internal", "10001" - if h := os.Getenv("API_HOST"); h != "" { - host = h - } - if p := os.Getenv("API_PORT"); p != "" { - port = p - } - return &url.URL{ - Scheme: "http", - Host: host + ":" + port, - Path: apiPath, - } -} - -func handleHTTP(w http.ResponseWriter, r *http.Request) { - c := &context{ - req: r, - outHeader: w.Header(), - apiURL: apiURL(), - } - stopFlushing := make(chan int) - - ctxs.Lock() - ctxs.m[r] = c - ctxs.Unlock() - defer func() { - ctxs.Lock() - delete(ctxs.m, r) - ctxs.Unlock() - }() - - // Patch up RemoteAddr so it looks reasonable. - if addr := r.Header.Get(userIPHeader); addr != "" { - r.RemoteAddr = addr - } else if addr = r.Header.Get(remoteAddrHeader); addr != "" { - r.RemoteAddr = addr - } else { - // Should not normally reach here, but pick a sensible default anyway. - r.RemoteAddr = "127.0.0.1" - } - // The address in the headers will most likely be of these forms: - // 123.123.123.123 - // 2001:db8::1 - // net/http.Request.RemoteAddr is specified to be in "IP:port" form. - if _, _, err := net.SplitHostPort(r.RemoteAddr); err != nil { - // Assume the remote address is only a host; add a default port. - r.RemoteAddr = net.JoinHostPort(r.RemoteAddr, "80") - } - - // Start goroutine responsible for flushing app logs. - // This is done after adding c to ctx.m (and stopped before removing it) - // because flushing logs requires making an API call. - go c.logFlusher(stopFlushing) - - executeRequestSafely(c, r) - c.outHeader = nil // make sure header changes aren't respected any more - - stopFlushing <- 1 // any logging beyond this point will be dropped - - // Flush any pending logs asynchronously. - c.pendingLogs.Lock() - flushes := c.pendingLogs.flushes - if len(c.pendingLogs.lines) > 0 { - flushes++ - } - c.pendingLogs.Unlock() - go c.flushLog(false) - w.Header().Set(logFlushHeader, strconv.Itoa(flushes)) - - // Avoid nil Write call if c.Write is never called. - if c.outCode != 0 { - w.WriteHeader(c.outCode) - } - if c.outBody != nil { - w.Write(c.outBody) - } -} - -func executeRequestSafely(c *context, r *http.Request) { - defer func() { - if x := recover(); x != nil { - logf(c, 4, "%s", renderPanic(x)) // 4 == critical - c.outCode = 500 - } - }() - - http.DefaultServeMux.ServeHTTP(c, r) -} - -func renderPanic(x interface{}) string { - buf := make([]byte, 16<<10) // 16 KB should be plenty - buf = buf[:runtime.Stack(buf, false)] - - // Remove the first few stack frames: - // this func - // the recover closure in the caller - // That will root the stack trace at the site of the panic. - const ( - skipStart = "internal.renderPanic" - skipFrames = 2 - ) - start := bytes.Index(buf, []byte(skipStart)) - p := start - for i := 0; i < skipFrames*2 && p+1 < len(buf); i++ { - p = bytes.IndexByte(buf[p+1:], '\n') + p + 1 - if p < 0 { - break - } - } - if p >= 0 { - // buf[start:p+1] is the block to remove. - // Copy buf[p+1:] over buf[start:] and shrink buf. - copy(buf[start:], buf[p+1:]) - buf = buf[:len(buf)-(p+1-start)] - } - - // Add panic heading. - head := fmt.Sprintf("panic: %v\n\n", x) - if len(head) > len(buf) { - // Extremely unlikely to happen. - return head - } - copy(buf[len(head):], buf) - copy(buf, head) - - return string(buf) -} - -var ctxs = struct { - sync.Mutex - m map[*http.Request]*context - bg *context // background context, lazily initialized - // dec is used by tests to decorate the netcontext.Context returned - // for a given request. This allows tests to add overrides (such as - // WithAppIDOverride) to the context. The map is nil outside tests. - dec map[*http.Request]func(netcontext.Context) netcontext.Context -}{ - m: make(map[*http.Request]*context), -} - -// context represents the context of an in-flight HTTP request. -// It implements the appengine.Context and http.ResponseWriter interfaces. -type context struct { - req *http.Request - - outCode int - outHeader http.Header - outBody []byte - - pendingLogs struct { - sync.Mutex - lines []*logpb.UserAppLogLine - flushes int - } - - apiURL *url.URL -} - -var contextKey = "holds a *context" - -func fromContext(ctx netcontext.Context) *context { - c, _ := ctx.Value(&contextKey).(*context) - return c -} - -func withContext(parent netcontext.Context, c *context) netcontext.Context { - ctx := netcontext.WithValue(parent, &contextKey, c) - if ns := c.req.Header.Get(curNamespaceHeader); ns != "" { - ctx = withNamespace(ctx, ns) - } - return ctx -} - -func toContext(c *context) netcontext.Context { - return withContext(netcontext.Background(), c) -} - -func IncomingHeaders(ctx netcontext.Context) http.Header { - if c := fromContext(ctx); c != nil { - return c.req.Header - } - return nil -} - -func WithContext(parent netcontext.Context, req *http.Request) netcontext.Context { - ctxs.Lock() - c := ctxs.m[req] - d := ctxs.dec[req] - ctxs.Unlock() - - if d != nil { - parent = d(parent) - } - - if c == nil { - // Someone passed in an http.Request that is not in-flight. - // We panic here rather than panicking at a later point - // so that stack traces will be more sensible. - log.Panic("appengine: NewContext passed an unknown http.Request") - } - return withContext(parent, c) -} - -func BackgroundContext() netcontext.Context { - ctxs.Lock() - defer ctxs.Unlock() - - if ctxs.bg != nil { - return toContext(ctxs.bg) - } - - // Compute background security ticket. - appID := partitionlessAppID() - escAppID := strings.Replace(strings.Replace(appID, ":", "_", -1), ".", "_", -1) - majVersion := VersionID(nil) - if i := strings.Index(majVersion, "."); i > 0 { - majVersion = majVersion[:i] - } - ticket := fmt.Sprintf("%s/%s.%s.%s", escAppID, ModuleName(nil), majVersion, InstanceID()) - - ctxs.bg = &context{ - req: &http.Request{ - Header: http.Header{ - ticketHeader: []string{ticket}, - }, - }, - apiURL: apiURL(), - } - - // TODO(dsymonds): Wire up the shutdown handler to do a final flush. - go ctxs.bg.logFlusher(make(chan int)) - - return toContext(ctxs.bg) -} - -// RegisterTestRequest registers the HTTP request req for testing, such that -// any API calls are sent to the provided URL. It returns a closure to delete -// the registration. -// It should only be used by aetest package. -func RegisterTestRequest(req *http.Request, apiURL *url.URL, decorate func(netcontext.Context) netcontext.Context) func() { - c := &context{ - req: req, - apiURL: apiURL, - } - ctxs.Lock() - defer ctxs.Unlock() - if _, ok := ctxs.m[req]; ok { - log.Panic("req already associated with context") - } - if _, ok := ctxs.dec[req]; ok { - log.Panic("req already associated with context") - } - if ctxs.dec == nil { - ctxs.dec = make(map[*http.Request]func(netcontext.Context) netcontext.Context) - } - ctxs.m[req] = c - ctxs.dec[req] = decorate - - return func() { - ctxs.Lock() - delete(ctxs.m, req) - delete(ctxs.dec, req) - ctxs.Unlock() - } -} - -var errTimeout = &CallError{ - Detail: "Deadline exceeded", - Code: int32(remotepb.RpcError_CANCELLED), - Timeout: true, -} - -func (c *context) Header() http.Header { return c.outHeader } - -// Copied from $GOROOT/src/pkg/net/http/transfer.go. Some response status -// codes do not permit a response body (nor response entity headers such as -// Content-Length, Content-Type, etc). -func bodyAllowedForStatus(status int) bool { - switch { - case status >= 100 && status <= 199: - return false - case status == 204: - return false - case status == 304: - return false - } - return true -} - -func (c *context) Write(b []byte) (int, error) { - if c.outCode == 0 { - c.WriteHeader(http.StatusOK) - } - if len(b) > 0 && !bodyAllowedForStatus(c.outCode) { - return 0, http.ErrBodyNotAllowed - } - c.outBody = append(c.outBody, b...) - return len(b), nil -} - -func (c *context) WriteHeader(code int) { - if c.outCode != 0 { - logf(c, 3, "WriteHeader called multiple times on request.") // error level - return - } - c.outCode = code -} - -func (c *context) post(body []byte, timeout time.Duration) (b []byte, err error) { - hreq := &http.Request{ - Method: "POST", - URL: c.apiURL, - Header: http.Header{ - apiEndpointHeader: apiEndpointHeaderValue, - apiMethodHeader: apiMethodHeaderValue, - apiContentType: apiContentTypeValue, - apiDeadlineHeader: []string{strconv.FormatFloat(timeout.Seconds(), 'f', -1, 64)}, - }, - Body: ioutil.NopCloser(bytes.NewReader(body)), - ContentLength: int64(len(body)), - Host: c.apiURL.Host, - } - if info := c.req.Header.Get(dapperHeader); info != "" { - hreq.Header.Set(dapperHeader, info) - } - if info := c.req.Header.Get(traceHeader); info != "" { - hreq.Header.Set(traceHeader, info) - } - - tr := apiHTTPClient.Transport.(*http.Transport) - - var timedOut int32 // atomic; set to 1 if timed out - t := time.AfterFunc(timeout, func() { - atomic.StoreInt32(&timedOut, 1) - tr.CancelRequest(hreq) - }) - defer t.Stop() - defer func() { - // Check if timeout was exceeded. - if atomic.LoadInt32(&timedOut) != 0 { - err = errTimeout - } - }() - - hresp, err := apiHTTPClient.Do(hreq) - if err != nil { - return nil, &CallError{ - Detail: fmt.Sprintf("service bridge HTTP failed: %v", err), - Code: int32(remotepb.RpcError_UNKNOWN), - } - } - defer hresp.Body.Close() - hrespBody, err := ioutil.ReadAll(hresp.Body) - if hresp.StatusCode != 200 { - return nil, &CallError{ - Detail: fmt.Sprintf("service bridge returned HTTP %d (%q)", hresp.StatusCode, hrespBody), - Code: int32(remotepb.RpcError_UNKNOWN), - } - } - if err != nil { - return nil, &CallError{ - Detail: fmt.Sprintf("service bridge response bad: %v", err), - Code: int32(remotepb.RpcError_UNKNOWN), - } - } - return hrespBody, nil -} - -func Call(ctx netcontext.Context, service, method string, in, out proto.Message) error { - if f, ctx, ok := callOverrideFromContext(ctx); ok { - return f(ctx, service, method, in, out) - } - - // Handle already-done contexts quickly. - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - c := fromContext(ctx) - if c == nil { - // Give a good error message rather than a panic lower down. - return errors.New("not an App Engine context") - } - - // Apply transaction modifications if we're in a transaction. - if t := transactionFromContext(ctx); t != nil { - if t.finished { - return errors.New("transaction context has expired") - } - applyTransaction(in, &t.transaction) - } - - // Default RPC timeout is 60s. - timeout := 60 * time.Second - if deadline, ok := ctx.Deadline(); ok { - timeout = deadline.Sub(time.Now()) - } - - data, err := proto.Marshal(in) - if err != nil { - return err - } - - ticket := c.req.Header.Get(ticketHeader) - req := &remotepb.Request{ - ServiceName: &service, - Method: &method, - Request: data, - RequestId: &ticket, - } - hreqBody, err := proto.Marshal(req) - if err != nil { - return err - } - - hrespBody, err := c.post(hreqBody, timeout) - if err != nil { - return err - } - - res := &remotepb.Response{} - if err := proto.Unmarshal(hrespBody, res); err != nil { - return err - } - if res.RpcError != nil { - ce := &CallError{ - Detail: res.RpcError.GetDetail(), - Code: *res.RpcError.Code, - } - switch remotepb.RpcError_ErrorCode(ce.Code) { - case remotepb.RpcError_CANCELLED, remotepb.RpcError_DEADLINE_EXCEEDED: - ce.Timeout = true - } - return ce - } - if res.ApplicationError != nil { - return &APIError{ - Service: *req.ServiceName, - Detail: res.ApplicationError.GetDetail(), - Code: *res.ApplicationError.Code, - } - } - if res.Exception != nil || res.JavaException != nil { - // This shouldn't happen, but let's be defensive. - return &CallError{ - Detail: "service bridge returned exception", - Code: int32(remotepb.RpcError_UNKNOWN), - } - } - return proto.Unmarshal(res.Response, out) -} - -func (c *context) Request() *http.Request { - return c.req -} - -func (c *context) addLogLine(ll *logpb.UserAppLogLine) { - // Truncate long log lines. - // TODO(dsymonds): Check if this is still necessary. - const lim = 8 << 10 - if len(*ll.Message) > lim { - suffix := fmt.Sprintf("...(length %d)", len(*ll.Message)) - ll.Message = proto.String((*ll.Message)[:lim-len(suffix)] + suffix) - } - - c.pendingLogs.Lock() - c.pendingLogs.lines = append(c.pendingLogs.lines, ll) - c.pendingLogs.Unlock() -} - -var logLevelName = map[int64]string{ - 0: "DEBUG", - 1: "INFO", - 2: "WARNING", - 3: "ERROR", - 4: "CRITICAL", -} - -func logf(c *context, level int64, format string, args ...interface{}) { - s := fmt.Sprintf(format, args...) - s = strings.TrimRight(s, "\n") // Remove any trailing newline characters. - c.addLogLine(&logpb.UserAppLogLine{ - TimestampUsec: proto.Int64(time.Now().UnixNano() / 1e3), - Level: &level, - Message: &s, - }) - log.Print(logLevelName[level] + ": " + s) -} - -// flushLog attempts to flush any pending logs to the appserver. -// It should not be called concurrently. -func (c *context) flushLog(force bool) (flushed bool) { - c.pendingLogs.Lock() - // Grab up to 30 MB. We can get away with up to 32 MB, but let's be cautious. - n, rem := 0, 30<<20 - for ; n < len(c.pendingLogs.lines); n++ { - ll := c.pendingLogs.lines[n] - // Each log line will require about 3 bytes of overhead. - nb := proto.Size(ll) + 3 - if nb > rem { - break - } - rem -= nb - } - lines := c.pendingLogs.lines[:n] - c.pendingLogs.lines = c.pendingLogs.lines[n:] - c.pendingLogs.Unlock() - - if len(lines) == 0 && !force { - // Nothing to flush. - return false - } - - rescueLogs := false - defer func() { - if rescueLogs { - c.pendingLogs.Lock() - c.pendingLogs.lines = append(lines, c.pendingLogs.lines...) - c.pendingLogs.Unlock() - } - }() - - buf, err := proto.Marshal(&logpb.UserAppLogGroup{ - LogLine: lines, - }) - if err != nil { - log.Printf("internal.flushLog: marshaling UserAppLogGroup: %v", err) - rescueLogs = true - return false - } - - req := &logpb.FlushRequest{ - Logs: buf, - } - res := &basepb.VoidProto{} - c.pendingLogs.Lock() - c.pendingLogs.flushes++ - c.pendingLogs.Unlock() - if err := Call(toContext(c), "logservice", "Flush", req, res); err != nil { - log.Printf("internal.flushLog: Flush RPC: %v", err) - rescueLogs = true - return false - } - return true -} - -const ( - // Log flushing parameters. - flushInterval = 1 * time.Second - forceFlushInterval = 60 * time.Second -) - -func (c *context) logFlusher(stop <-chan int) { - lastFlush := time.Now() - tick := time.NewTicker(flushInterval) - for { - select { - case <-stop: - // Request finished. - tick.Stop() - return - case <-tick.C: - force := time.Now().Sub(lastFlush) > forceFlushInterval - if c.flushLog(force) { - lastFlush = time.Now() - } - } - } -} - -func ContextForTesting(req *http.Request) netcontext.Context { - return toContext(&context{req: req}) -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/api_classic.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/api_classic.go deleted file mode 100644 index 1c072e9db..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/api_classic.go +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build appengine - -package internal - -import ( - "errors" - "net/http" - "time" - - "appengine" - "appengine_internal" - basepb "appengine_internal/base" - - "github.com/golang/protobuf/proto" - netcontext "golang.org/x/net/context" -) - -var contextKey = "holds an appengine.Context" - -func fromContext(ctx netcontext.Context) appengine.Context { - c, _ := ctx.Value(&contextKey).(appengine.Context) - return c -} - -// This is only for classic App Engine adapters. -func ClassicContextFromContext(ctx netcontext.Context) appengine.Context { - return fromContext(ctx) -} - -func withContext(parent netcontext.Context, c appengine.Context) netcontext.Context { - ctx := netcontext.WithValue(parent, &contextKey, c) - - s := &basepb.StringProto{} - c.Call("__go__", "GetNamespace", &basepb.VoidProto{}, s, nil) - if ns := s.GetValue(); ns != "" { - ctx = NamespacedContext(ctx, ns) - } - - return ctx -} - -func IncomingHeaders(ctx netcontext.Context) http.Header { - if c := fromContext(ctx); c != nil { - if req, ok := c.Request().(*http.Request); ok { - return req.Header - } - } - return nil -} - -func WithContext(parent netcontext.Context, req *http.Request) netcontext.Context { - c := appengine.NewContext(req) - return withContext(parent, c) -} - -func Call(ctx netcontext.Context, service, method string, in, out proto.Message) error { - if f, ctx, ok := callOverrideFromContext(ctx); ok { - return f(ctx, service, method, in, out) - } - - // Handle already-done contexts quickly. - select { - case <-ctx.Done(): - return ctx.Err() - default: - } - - c := fromContext(ctx) - if c == nil { - // Give a good error message rather than a panic lower down. - return errors.New("not an App Engine context") - } - - // Apply transaction modifications if we're in a transaction. - if t := transactionFromContext(ctx); t != nil { - if t.finished { - return errors.New("transaction context has expired") - } - applyTransaction(in, &t.transaction) - } - - var opts *appengine_internal.CallOptions - if d, ok := ctx.Deadline(); ok { - opts = &appengine_internal.CallOptions{ - Timeout: d.Sub(time.Now()), - } - } - - err := c.Call(service, method, in, out, opts) - switch v := err.(type) { - case *appengine_internal.APIError: - return &APIError{ - Service: v.Service, - Detail: v.Detail, - Code: v.Code, - } - case *appengine_internal.CallError: - return &CallError{ - Detail: v.Detail, - Code: v.Code, - Timeout: v.Timeout, - } - } - return err -} - -func handleHTTP(w http.ResponseWriter, r *http.Request) { - panic("handleHTTP called; this should be impossible") -} - -func logf(c appengine.Context, level int64, format string, args ...interface{}) { - var fn func(format string, args ...interface{}) - switch level { - case 0: - fn = c.Debugf - case 1: - fn = c.Infof - case 2: - fn = c.Warningf - case 3: - fn = c.Errorf - case 4: - fn = c.Criticalf - default: - // This shouldn't happen. - fn = c.Criticalf - } - fn(format, args...) -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/api_common.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/api_common.go deleted file mode 100644 index ec5383e66..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/api_common.go +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package internal - -import ( - "github.com/golang/protobuf/proto" - netcontext "golang.org/x/net/context" -) - -type CallOverrideFunc func(ctx netcontext.Context, service, method string, in, out proto.Message) error - -var callOverrideKey = "holds []CallOverrideFunc" - -func WithCallOverride(ctx netcontext.Context, f CallOverrideFunc) netcontext.Context { - // We avoid appending to any existing call override - // so we don't risk overwriting a popped stack below. - var cofs []CallOverrideFunc - if uf, ok := ctx.Value(&callOverrideKey).([]CallOverrideFunc); ok { - cofs = append(cofs, uf...) - } - cofs = append(cofs, f) - return netcontext.WithValue(ctx, &callOverrideKey, cofs) -} - -func callOverrideFromContext(ctx netcontext.Context) (CallOverrideFunc, netcontext.Context, bool) { - cofs, _ := ctx.Value(&callOverrideKey).([]CallOverrideFunc) - if len(cofs) == 0 { - return nil, nil, false - } - // We found a list of overrides; grab the last, and reconstitute a - // context that will hide it. - f := cofs[len(cofs)-1] - ctx = netcontext.WithValue(ctx, &callOverrideKey, cofs[:len(cofs)-1]) - return f, ctx, true -} - -type logOverrideFunc func(level int64, format string, args ...interface{}) - -var logOverrideKey = "holds a logOverrideFunc" - -func WithLogOverride(ctx netcontext.Context, f logOverrideFunc) netcontext.Context { - return netcontext.WithValue(ctx, &logOverrideKey, f) -} - -var appIDOverrideKey = "holds a string, being the full app ID" - -func WithAppIDOverride(ctx netcontext.Context, appID string) netcontext.Context { - return netcontext.WithValue(ctx, &appIDOverrideKey, appID) -} - -var namespaceKey = "holds the namespace string" - -func withNamespace(ctx netcontext.Context, ns string) netcontext.Context { - return netcontext.WithValue(ctx, &namespaceKey, ns) -} - -func NamespaceFromContext(ctx netcontext.Context) string { - // If there's no namespace, return the empty string. - ns, _ := ctx.Value(&namespaceKey).(string) - return ns -} - -// FullyQualifiedAppID returns the fully-qualified application ID. -// This may contain a partition prefix (e.g. "s~" for High Replication apps), -// or a domain prefix (e.g. "example.com:"). -func FullyQualifiedAppID(ctx netcontext.Context) string { - if id, ok := ctx.Value(&appIDOverrideKey).(string); ok { - return id - } - return fullyQualifiedAppID(ctx) -} - -func Logf(ctx netcontext.Context, level int64, format string, args ...interface{}) { - if f, ok := ctx.Value(&logOverrideKey).(logOverrideFunc); ok { - f(level, format, args...) - return - } - logf(fromContext(ctx), level, format, args...) -} - -// NamespacedContext wraps a Context to support namespaces. -func NamespacedContext(ctx netcontext.Context, namespace string) netcontext.Context { - n := &namespacedContext{ - namespace: namespace, - } - return withNamespace(WithCallOverride(ctx, n.call), namespace) -} - -type namespacedContext struct { - namespace string -} - -func (n *namespacedContext) call(ctx netcontext.Context, service, method string, in, out proto.Message) error { - // Apply any namespace mods. - if mod, ok := NamespaceMods[service]; ok { - mod(in, n.namespace) - } - return Call(ctx, service, method, in, out) -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/app_id.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/app_id.go deleted file mode 100644 index 11df8c07b..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/app_id.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package internal - -import ( - "strings" -) - -func parseFullAppID(appid string) (partition, domain, displayID string) { - if i := strings.Index(appid, "~"); i != -1 { - partition, appid = appid[:i], appid[i+1:] - } - if i := strings.Index(appid, ":"); i != -1 { - domain, appid = appid[:i], appid[i+1:] - } - return partition, domain, appid -} - -// appID returns "appid" or "domain.com:appid". -func appID(fullAppID string) string { - _, dom, dis := parseFullAppID(fullAppID) - if dom != "" { - return dom + ":" + dis - } - return dis -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/app_identity/app_identity_service.pb.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/app_identity/app_identity_service.pb.go deleted file mode 100644 index 87d9701b8..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/app_identity/app_identity_service.pb.go +++ /dev/null @@ -1,296 +0,0 @@ -// Code generated by protoc-gen-go. -// source: google.golang.org/appengine/internal/app_identity/app_identity_service.proto -// DO NOT EDIT! - -/* -Package app_identity is a generated protocol buffer package. - -It is generated from these files: - google.golang.org/appengine/internal/app_identity/app_identity_service.proto - -It has these top-level messages: - AppIdentityServiceError - SignForAppRequest - SignForAppResponse - GetPublicCertificateForAppRequest - PublicCertificate - GetPublicCertificateForAppResponse - GetServiceAccountNameRequest - GetServiceAccountNameResponse - GetAccessTokenRequest - GetAccessTokenResponse - GetDefaultGcsBucketNameRequest - GetDefaultGcsBucketNameResponse -*/ -package app_identity - -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 - -type AppIdentityServiceError_ErrorCode int32 - -const ( - AppIdentityServiceError_SUCCESS AppIdentityServiceError_ErrorCode = 0 - AppIdentityServiceError_UNKNOWN_SCOPE AppIdentityServiceError_ErrorCode = 9 - AppIdentityServiceError_BLOB_TOO_LARGE AppIdentityServiceError_ErrorCode = 1000 - AppIdentityServiceError_DEADLINE_EXCEEDED AppIdentityServiceError_ErrorCode = 1001 - AppIdentityServiceError_NOT_A_VALID_APP AppIdentityServiceError_ErrorCode = 1002 - AppIdentityServiceError_UNKNOWN_ERROR AppIdentityServiceError_ErrorCode = 1003 - AppIdentityServiceError_NOT_ALLOWED AppIdentityServiceError_ErrorCode = 1005 - AppIdentityServiceError_NOT_IMPLEMENTED AppIdentityServiceError_ErrorCode = 1006 -) - -var AppIdentityServiceError_ErrorCode_name = map[int32]string{ - 0: "SUCCESS", - 9: "UNKNOWN_SCOPE", - 1000: "BLOB_TOO_LARGE", - 1001: "DEADLINE_EXCEEDED", - 1002: "NOT_A_VALID_APP", - 1003: "UNKNOWN_ERROR", - 1005: "NOT_ALLOWED", - 1006: "NOT_IMPLEMENTED", -} -var AppIdentityServiceError_ErrorCode_value = map[string]int32{ - "SUCCESS": 0, - "UNKNOWN_SCOPE": 9, - "BLOB_TOO_LARGE": 1000, - "DEADLINE_EXCEEDED": 1001, - "NOT_A_VALID_APP": 1002, - "UNKNOWN_ERROR": 1003, - "NOT_ALLOWED": 1005, - "NOT_IMPLEMENTED": 1006, -} - -func (x AppIdentityServiceError_ErrorCode) Enum() *AppIdentityServiceError_ErrorCode { - p := new(AppIdentityServiceError_ErrorCode) - *p = x - return p -} -func (x AppIdentityServiceError_ErrorCode) String() string { - return proto.EnumName(AppIdentityServiceError_ErrorCode_name, int32(x)) -} -func (x *AppIdentityServiceError_ErrorCode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(AppIdentityServiceError_ErrorCode_value, data, "AppIdentityServiceError_ErrorCode") - if err != nil { - return err - } - *x = AppIdentityServiceError_ErrorCode(value) - return nil -} - -type AppIdentityServiceError struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *AppIdentityServiceError) Reset() { *m = AppIdentityServiceError{} } -func (m *AppIdentityServiceError) String() string { return proto.CompactTextString(m) } -func (*AppIdentityServiceError) ProtoMessage() {} - -type SignForAppRequest struct { - BytesToSign []byte `protobuf:"bytes,1,opt,name=bytes_to_sign" json:"bytes_to_sign,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SignForAppRequest) Reset() { *m = SignForAppRequest{} } -func (m *SignForAppRequest) String() string { return proto.CompactTextString(m) } -func (*SignForAppRequest) ProtoMessage() {} - -func (m *SignForAppRequest) GetBytesToSign() []byte { - if m != nil { - return m.BytesToSign - } - return nil -} - -type SignForAppResponse struct { - KeyName *string `protobuf:"bytes,1,opt,name=key_name" json:"key_name,omitempty"` - SignatureBytes []byte `protobuf:"bytes,2,opt,name=signature_bytes" json:"signature_bytes,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SignForAppResponse) Reset() { *m = SignForAppResponse{} } -func (m *SignForAppResponse) String() string { return proto.CompactTextString(m) } -func (*SignForAppResponse) ProtoMessage() {} - -func (m *SignForAppResponse) GetKeyName() string { - if m != nil && m.KeyName != nil { - return *m.KeyName - } - return "" -} - -func (m *SignForAppResponse) GetSignatureBytes() []byte { - if m != nil { - return m.SignatureBytes - } - return nil -} - -type GetPublicCertificateForAppRequest struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetPublicCertificateForAppRequest) Reset() { *m = GetPublicCertificateForAppRequest{} } -func (m *GetPublicCertificateForAppRequest) String() string { return proto.CompactTextString(m) } -func (*GetPublicCertificateForAppRequest) ProtoMessage() {} - -type PublicCertificate struct { - KeyName *string `protobuf:"bytes,1,opt,name=key_name" json:"key_name,omitempty"` - X509CertificatePem *string `protobuf:"bytes,2,opt,name=x509_certificate_pem" json:"x509_certificate_pem,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PublicCertificate) Reset() { *m = PublicCertificate{} } -func (m *PublicCertificate) String() string { return proto.CompactTextString(m) } -func (*PublicCertificate) ProtoMessage() {} - -func (m *PublicCertificate) GetKeyName() string { - if m != nil && m.KeyName != nil { - return *m.KeyName - } - return "" -} - -func (m *PublicCertificate) GetX509CertificatePem() string { - if m != nil && m.X509CertificatePem != nil { - return *m.X509CertificatePem - } - return "" -} - -type GetPublicCertificateForAppResponse struct { - PublicCertificateList []*PublicCertificate `protobuf:"bytes,1,rep,name=public_certificate_list" json:"public_certificate_list,omitempty"` - MaxClientCacheTimeInSecond *int64 `protobuf:"varint,2,opt,name=max_client_cache_time_in_second" json:"max_client_cache_time_in_second,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetPublicCertificateForAppResponse) Reset() { *m = GetPublicCertificateForAppResponse{} } -func (m *GetPublicCertificateForAppResponse) String() string { return proto.CompactTextString(m) } -func (*GetPublicCertificateForAppResponse) ProtoMessage() {} - -func (m *GetPublicCertificateForAppResponse) GetPublicCertificateList() []*PublicCertificate { - if m != nil { - return m.PublicCertificateList - } - return nil -} - -func (m *GetPublicCertificateForAppResponse) GetMaxClientCacheTimeInSecond() int64 { - if m != nil && m.MaxClientCacheTimeInSecond != nil { - return *m.MaxClientCacheTimeInSecond - } - return 0 -} - -type GetServiceAccountNameRequest struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetServiceAccountNameRequest) Reset() { *m = GetServiceAccountNameRequest{} } -func (m *GetServiceAccountNameRequest) String() string { return proto.CompactTextString(m) } -func (*GetServiceAccountNameRequest) ProtoMessage() {} - -type GetServiceAccountNameResponse struct { - ServiceAccountName *string `protobuf:"bytes,1,opt,name=service_account_name" json:"service_account_name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetServiceAccountNameResponse) Reset() { *m = GetServiceAccountNameResponse{} } -func (m *GetServiceAccountNameResponse) String() string { return proto.CompactTextString(m) } -func (*GetServiceAccountNameResponse) ProtoMessage() {} - -func (m *GetServiceAccountNameResponse) GetServiceAccountName() string { - if m != nil && m.ServiceAccountName != nil { - return *m.ServiceAccountName - } - return "" -} - -type GetAccessTokenRequest struct { - Scope []string `protobuf:"bytes,1,rep,name=scope" json:"scope,omitempty"` - ServiceAccountId *int64 `protobuf:"varint,2,opt,name=service_account_id" json:"service_account_id,omitempty"` - ServiceAccountName *string `protobuf:"bytes,3,opt,name=service_account_name" json:"service_account_name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetAccessTokenRequest) Reset() { *m = GetAccessTokenRequest{} } -func (m *GetAccessTokenRequest) String() string { return proto.CompactTextString(m) } -func (*GetAccessTokenRequest) ProtoMessage() {} - -func (m *GetAccessTokenRequest) GetScope() []string { - if m != nil { - return m.Scope - } - return nil -} - -func (m *GetAccessTokenRequest) GetServiceAccountId() int64 { - if m != nil && m.ServiceAccountId != nil { - return *m.ServiceAccountId - } - return 0 -} - -func (m *GetAccessTokenRequest) GetServiceAccountName() string { - if m != nil && m.ServiceAccountName != nil { - return *m.ServiceAccountName - } - return "" -} - -type GetAccessTokenResponse struct { - AccessToken *string `protobuf:"bytes,1,opt,name=access_token" json:"access_token,omitempty"` - ExpirationTime *int64 `protobuf:"varint,2,opt,name=expiration_time" json:"expiration_time,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetAccessTokenResponse) Reset() { *m = GetAccessTokenResponse{} } -func (m *GetAccessTokenResponse) String() string { return proto.CompactTextString(m) } -func (*GetAccessTokenResponse) ProtoMessage() {} - -func (m *GetAccessTokenResponse) GetAccessToken() string { - if m != nil && m.AccessToken != nil { - return *m.AccessToken - } - return "" -} - -func (m *GetAccessTokenResponse) GetExpirationTime() int64 { - if m != nil && m.ExpirationTime != nil { - return *m.ExpirationTime - } - return 0 -} - -type GetDefaultGcsBucketNameRequest struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetDefaultGcsBucketNameRequest) Reset() { *m = GetDefaultGcsBucketNameRequest{} } -func (m *GetDefaultGcsBucketNameRequest) String() string { return proto.CompactTextString(m) } -func (*GetDefaultGcsBucketNameRequest) ProtoMessage() {} - -type GetDefaultGcsBucketNameResponse struct { - DefaultGcsBucketName *string `protobuf:"bytes,1,opt,name=default_gcs_bucket_name" json:"default_gcs_bucket_name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetDefaultGcsBucketNameResponse) Reset() { *m = GetDefaultGcsBucketNameResponse{} } -func (m *GetDefaultGcsBucketNameResponse) String() string { return proto.CompactTextString(m) } -func (*GetDefaultGcsBucketNameResponse) ProtoMessage() {} - -func (m *GetDefaultGcsBucketNameResponse) GetDefaultGcsBucketName() string { - if m != nil && m.DefaultGcsBucketName != nil { - return *m.DefaultGcsBucketName - } - return "" -} - -func init() { -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/app_identity/app_identity_service.proto b/Godeps/_workspace/src/google.golang.org/appengine/internal/app_identity/app_identity_service.proto deleted file mode 100644 index 19610ca5b..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/app_identity/app_identity_service.proto +++ /dev/null @@ -1,64 +0,0 @@ -syntax = "proto2"; -option go_package = "app_identity"; - -package appengine; - -message AppIdentityServiceError { - enum ErrorCode { - SUCCESS = 0; - UNKNOWN_SCOPE = 9; - BLOB_TOO_LARGE = 1000; - DEADLINE_EXCEEDED = 1001; - NOT_A_VALID_APP = 1002; - UNKNOWN_ERROR = 1003; - NOT_ALLOWED = 1005; - NOT_IMPLEMENTED = 1006; - } -} - -message SignForAppRequest { - optional bytes bytes_to_sign = 1; -} - -message SignForAppResponse { - optional string key_name = 1; - optional bytes signature_bytes = 2; -} - -message GetPublicCertificateForAppRequest { -} - -message PublicCertificate { - optional string key_name = 1; - optional string x509_certificate_pem = 2; -} - -message GetPublicCertificateForAppResponse { - repeated PublicCertificate public_certificate_list = 1; - optional int64 max_client_cache_time_in_second = 2; -} - -message GetServiceAccountNameRequest { -} - -message GetServiceAccountNameResponse { - optional string service_account_name = 1; -} - -message GetAccessTokenRequest { - repeated string scope = 1; - optional int64 service_account_id = 2; - optional string service_account_name = 3; -} - -message GetAccessTokenResponse { - optional string access_token = 1; - optional int64 expiration_time = 2; -} - -message GetDefaultGcsBucketNameRequest { -} - -message GetDefaultGcsBucketNameResponse { - optional string default_gcs_bucket_name = 1; -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/base/api_base.pb.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/base/api_base.pb.go deleted file mode 100644 index 36a195650..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/base/api_base.pb.go +++ /dev/null @@ -1,133 +0,0 @@ -// Code generated by protoc-gen-go. -// source: google.golang.org/appengine/internal/base/api_base.proto -// DO NOT EDIT! - -/* -Package base is a generated protocol buffer package. - -It is generated from these files: - google.golang.org/appengine/internal/base/api_base.proto - -It has these top-level messages: - StringProto - Integer32Proto - Integer64Proto - BoolProto - DoubleProto - BytesProto - VoidProto -*/ -package base - -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 - -type StringProto struct { - Value *string `protobuf:"bytes,1,req,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *StringProto) Reset() { *m = StringProto{} } -func (m *StringProto) String() string { return proto.CompactTextString(m) } -func (*StringProto) ProtoMessage() {} - -func (m *StringProto) GetValue() string { - if m != nil && m.Value != nil { - return *m.Value - } - return "" -} - -type Integer32Proto struct { - Value *int32 `protobuf:"varint,1,req,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Integer32Proto) Reset() { *m = Integer32Proto{} } -func (m *Integer32Proto) String() string { return proto.CompactTextString(m) } -func (*Integer32Proto) ProtoMessage() {} - -func (m *Integer32Proto) GetValue() int32 { - if m != nil && m.Value != nil { - return *m.Value - } - return 0 -} - -type Integer64Proto struct { - Value *int64 `protobuf:"varint,1,req,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Integer64Proto) Reset() { *m = Integer64Proto{} } -func (m *Integer64Proto) String() string { return proto.CompactTextString(m) } -func (*Integer64Proto) ProtoMessage() {} - -func (m *Integer64Proto) GetValue() int64 { - if m != nil && m.Value != nil { - return *m.Value - } - return 0 -} - -type BoolProto struct { - Value *bool `protobuf:"varint,1,req,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *BoolProto) Reset() { *m = BoolProto{} } -func (m *BoolProto) String() string { return proto.CompactTextString(m) } -func (*BoolProto) ProtoMessage() {} - -func (m *BoolProto) GetValue() bool { - if m != nil && m.Value != nil { - return *m.Value - } - return false -} - -type DoubleProto struct { - Value *float64 `protobuf:"fixed64,1,req,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *DoubleProto) Reset() { *m = DoubleProto{} } -func (m *DoubleProto) String() string { return proto.CompactTextString(m) } -func (*DoubleProto) ProtoMessage() {} - -func (m *DoubleProto) GetValue() float64 { - if m != nil && m.Value != nil { - return *m.Value - } - return 0 -} - -type BytesProto struct { - Value []byte `protobuf:"bytes,1,req,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *BytesProto) Reset() { *m = BytesProto{} } -func (m *BytesProto) String() string { return proto.CompactTextString(m) } -func (*BytesProto) ProtoMessage() {} - -func (m *BytesProto) GetValue() []byte { - if m != nil { - return m.Value - } - return nil -} - -type VoidProto struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *VoidProto) Reset() { *m = VoidProto{} } -func (m *VoidProto) String() string { return proto.CompactTextString(m) } -func (*VoidProto) ProtoMessage() {} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/base/api_base.proto b/Godeps/_workspace/src/google.golang.org/appengine/internal/base/api_base.proto deleted file mode 100644 index 56cd7a3ca..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/base/api_base.proto +++ /dev/null @@ -1,33 +0,0 @@ -// Built-in base types for API calls. Primarily useful as return types. - -syntax = "proto2"; -option go_package = "base"; - -package appengine.base; - -message StringProto { - required string value = 1; -} - -message Integer32Proto { - required int32 value = 1; -} - -message Integer64Proto { - required int64 value = 1; -} - -message BoolProto { - required bool value = 1; -} - -message DoubleProto { - required double value = 1; -} - -message BytesProto { - required bytes value = 1 [ctype=CORD]; -} - -message VoidProto { -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/datastore/datastore_v3.pb.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/datastore/datastore_v3.pb.go deleted file mode 100644 index 8613cb731..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/datastore/datastore_v3.pb.go +++ /dev/null @@ -1,2778 +0,0 @@ -// Code generated by protoc-gen-go. -// source: google.golang.org/appengine/internal/datastore/datastore_v3.proto -// DO NOT EDIT! - -/* -Package datastore is a generated protocol buffer package. - -It is generated from these files: - google.golang.org/appengine/internal/datastore/datastore_v3.proto - -It has these top-level messages: - Action - PropertyValue - Property - Path - Reference - User - EntityProto - CompositeProperty - Index - CompositeIndex - IndexPostfix - IndexPosition - Snapshot - InternalHeader - Transaction - Query - CompiledQuery - CompiledCursor - Cursor - Error - Cost - GetRequest - GetResponse - PutRequest - PutResponse - TouchRequest - TouchResponse - DeleteRequest - DeleteResponse - NextRequest - QueryResult - AllocateIdsRequest - AllocateIdsResponse - CompositeIndices - AddActionsRequest - AddActionsResponse - BeginTransactionRequest - CommitResponse -*/ -package datastore - -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 - -type Property_Meaning int32 - -const ( - Property_NO_MEANING Property_Meaning = 0 - Property_BLOB Property_Meaning = 14 - Property_TEXT Property_Meaning = 15 - Property_BYTESTRING Property_Meaning = 16 - Property_ATOM_CATEGORY Property_Meaning = 1 - Property_ATOM_LINK Property_Meaning = 2 - Property_ATOM_TITLE Property_Meaning = 3 - Property_ATOM_CONTENT Property_Meaning = 4 - Property_ATOM_SUMMARY Property_Meaning = 5 - Property_ATOM_AUTHOR Property_Meaning = 6 - Property_GD_WHEN Property_Meaning = 7 - Property_GD_EMAIL Property_Meaning = 8 - Property_GEORSS_POINT Property_Meaning = 9 - Property_GD_IM Property_Meaning = 10 - Property_GD_PHONENUMBER Property_Meaning = 11 - Property_GD_POSTALADDRESS Property_Meaning = 12 - Property_GD_RATING Property_Meaning = 13 - Property_BLOBKEY Property_Meaning = 17 - Property_ENTITY_PROTO Property_Meaning = 19 - Property_INDEX_VALUE Property_Meaning = 18 -) - -var Property_Meaning_name = map[int32]string{ - 0: "NO_MEANING", - 14: "BLOB", - 15: "TEXT", - 16: "BYTESTRING", - 1: "ATOM_CATEGORY", - 2: "ATOM_LINK", - 3: "ATOM_TITLE", - 4: "ATOM_CONTENT", - 5: "ATOM_SUMMARY", - 6: "ATOM_AUTHOR", - 7: "GD_WHEN", - 8: "GD_EMAIL", - 9: "GEORSS_POINT", - 10: "GD_IM", - 11: "GD_PHONENUMBER", - 12: "GD_POSTALADDRESS", - 13: "GD_RATING", - 17: "BLOBKEY", - 19: "ENTITY_PROTO", - 18: "INDEX_VALUE", -} -var Property_Meaning_value = map[string]int32{ - "NO_MEANING": 0, - "BLOB": 14, - "TEXT": 15, - "BYTESTRING": 16, - "ATOM_CATEGORY": 1, - "ATOM_LINK": 2, - "ATOM_TITLE": 3, - "ATOM_CONTENT": 4, - "ATOM_SUMMARY": 5, - "ATOM_AUTHOR": 6, - "GD_WHEN": 7, - "GD_EMAIL": 8, - "GEORSS_POINT": 9, - "GD_IM": 10, - "GD_PHONENUMBER": 11, - "GD_POSTALADDRESS": 12, - "GD_RATING": 13, - "BLOBKEY": 17, - "ENTITY_PROTO": 19, - "INDEX_VALUE": 18, -} - -func (x Property_Meaning) Enum() *Property_Meaning { - p := new(Property_Meaning) - *p = x - return p -} -func (x Property_Meaning) String() string { - return proto.EnumName(Property_Meaning_name, int32(x)) -} -func (x *Property_Meaning) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Property_Meaning_value, data, "Property_Meaning") - if err != nil { - return err - } - *x = Property_Meaning(value) - return nil -} - -type Property_FtsTokenizationOption int32 - -const ( - Property_HTML Property_FtsTokenizationOption = 1 - Property_ATOM Property_FtsTokenizationOption = 2 -) - -var Property_FtsTokenizationOption_name = map[int32]string{ - 1: "HTML", - 2: "ATOM", -} -var Property_FtsTokenizationOption_value = map[string]int32{ - "HTML": 1, - "ATOM": 2, -} - -func (x Property_FtsTokenizationOption) Enum() *Property_FtsTokenizationOption { - p := new(Property_FtsTokenizationOption) - *p = x - return p -} -func (x Property_FtsTokenizationOption) String() string { - return proto.EnumName(Property_FtsTokenizationOption_name, int32(x)) -} -func (x *Property_FtsTokenizationOption) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Property_FtsTokenizationOption_value, data, "Property_FtsTokenizationOption") - if err != nil { - return err - } - *x = Property_FtsTokenizationOption(value) - return nil -} - -type EntityProto_Kind int32 - -const ( - EntityProto_GD_CONTACT EntityProto_Kind = 1 - EntityProto_GD_EVENT EntityProto_Kind = 2 - EntityProto_GD_MESSAGE EntityProto_Kind = 3 -) - -var EntityProto_Kind_name = map[int32]string{ - 1: "GD_CONTACT", - 2: "GD_EVENT", - 3: "GD_MESSAGE", -} -var EntityProto_Kind_value = map[string]int32{ - "GD_CONTACT": 1, - "GD_EVENT": 2, - "GD_MESSAGE": 3, -} - -func (x EntityProto_Kind) Enum() *EntityProto_Kind { - p := new(EntityProto_Kind) - *p = x - return p -} -func (x EntityProto_Kind) String() string { - return proto.EnumName(EntityProto_Kind_name, int32(x)) -} -func (x *EntityProto_Kind) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(EntityProto_Kind_value, data, "EntityProto_Kind") - if err != nil { - return err - } - *x = EntityProto_Kind(value) - return nil -} - -type Index_Property_Direction int32 - -const ( - Index_Property_ASCENDING Index_Property_Direction = 1 - Index_Property_DESCENDING Index_Property_Direction = 2 -) - -var Index_Property_Direction_name = map[int32]string{ - 1: "ASCENDING", - 2: "DESCENDING", -} -var Index_Property_Direction_value = map[string]int32{ - "ASCENDING": 1, - "DESCENDING": 2, -} - -func (x Index_Property_Direction) Enum() *Index_Property_Direction { - p := new(Index_Property_Direction) - *p = x - return p -} -func (x Index_Property_Direction) String() string { - return proto.EnumName(Index_Property_Direction_name, int32(x)) -} -func (x *Index_Property_Direction) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Index_Property_Direction_value, data, "Index_Property_Direction") - if err != nil { - return err - } - *x = Index_Property_Direction(value) - return nil -} - -type CompositeIndex_State int32 - -const ( - CompositeIndex_WRITE_ONLY CompositeIndex_State = 1 - CompositeIndex_READ_WRITE CompositeIndex_State = 2 - CompositeIndex_DELETED CompositeIndex_State = 3 - CompositeIndex_ERROR CompositeIndex_State = 4 -) - -var CompositeIndex_State_name = map[int32]string{ - 1: "WRITE_ONLY", - 2: "READ_WRITE", - 3: "DELETED", - 4: "ERROR", -} -var CompositeIndex_State_value = map[string]int32{ - "WRITE_ONLY": 1, - "READ_WRITE": 2, - "DELETED": 3, - "ERROR": 4, -} - -func (x CompositeIndex_State) Enum() *CompositeIndex_State { - p := new(CompositeIndex_State) - *p = x - return p -} -func (x CompositeIndex_State) String() string { - return proto.EnumName(CompositeIndex_State_name, int32(x)) -} -func (x *CompositeIndex_State) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(CompositeIndex_State_value, data, "CompositeIndex_State") - if err != nil { - return err - } - *x = CompositeIndex_State(value) - return nil -} - -type Snapshot_Status int32 - -const ( - Snapshot_INACTIVE Snapshot_Status = 0 - Snapshot_ACTIVE Snapshot_Status = 1 -) - -var Snapshot_Status_name = map[int32]string{ - 0: "INACTIVE", - 1: "ACTIVE", -} -var Snapshot_Status_value = map[string]int32{ - "INACTIVE": 0, - "ACTIVE": 1, -} - -func (x Snapshot_Status) Enum() *Snapshot_Status { - p := new(Snapshot_Status) - *p = x - return p -} -func (x Snapshot_Status) String() string { - return proto.EnumName(Snapshot_Status_name, int32(x)) -} -func (x *Snapshot_Status) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Snapshot_Status_value, data, "Snapshot_Status") - if err != nil { - return err - } - *x = Snapshot_Status(value) - return nil -} - -type Query_Hint int32 - -const ( - Query_ORDER_FIRST Query_Hint = 1 - Query_ANCESTOR_FIRST Query_Hint = 2 - Query_FILTER_FIRST Query_Hint = 3 -) - -var Query_Hint_name = map[int32]string{ - 1: "ORDER_FIRST", - 2: "ANCESTOR_FIRST", - 3: "FILTER_FIRST", -} -var Query_Hint_value = map[string]int32{ - "ORDER_FIRST": 1, - "ANCESTOR_FIRST": 2, - "FILTER_FIRST": 3, -} - -func (x Query_Hint) Enum() *Query_Hint { - p := new(Query_Hint) - *p = x - return p -} -func (x Query_Hint) String() string { - return proto.EnumName(Query_Hint_name, int32(x)) -} -func (x *Query_Hint) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Query_Hint_value, data, "Query_Hint") - if err != nil { - return err - } - *x = Query_Hint(value) - return nil -} - -type Query_Filter_Operator int32 - -const ( - Query_Filter_LESS_THAN Query_Filter_Operator = 1 - Query_Filter_LESS_THAN_OR_EQUAL Query_Filter_Operator = 2 - Query_Filter_GREATER_THAN Query_Filter_Operator = 3 - Query_Filter_GREATER_THAN_OR_EQUAL Query_Filter_Operator = 4 - Query_Filter_EQUAL Query_Filter_Operator = 5 - Query_Filter_IN Query_Filter_Operator = 6 - Query_Filter_EXISTS Query_Filter_Operator = 7 -) - -var Query_Filter_Operator_name = map[int32]string{ - 1: "LESS_THAN", - 2: "LESS_THAN_OR_EQUAL", - 3: "GREATER_THAN", - 4: "GREATER_THAN_OR_EQUAL", - 5: "EQUAL", - 6: "IN", - 7: "EXISTS", -} -var Query_Filter_Operator_value = map[string]int32{ - "LESS_THAN": 1, - "LESS_THAN_OR_EQUAL": 2, - "GREATER_THAN": 3, - "GREATER_THAN_OR_EQUAL": 4, - "EQUAL": 5, - "IN": 6, - "EXISTS": 7, -} - -func (x Query_Filter_Operator) Enum() *Query_Filter_Operator { - p := new(Query_Filter_Operator) - *p = x - return p -} -func (x Query_Filter_Operator) String() string { - return proto.EnumName(Query_Filter_Operator_name, int32(x)) -} -func (x *Query_Filter_Operator) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Query_Filter_Operator_value, data, "Query_Filter_Operator") - if err != nil { - return err - } - *x = Query_Filter_Operator(value) - return nil -} - -type Query_Order_Direction int32 - -const ( - Query_Order_ASCENDING Query_Order_Direction = 1 - Query_Order_DESCENDING Query_Order_Direction = 2 -) - -var Query_Order_Direction_name = map[int32]string{ - 1: "ASCENDING", - 2: "DESCENDING", -} -var Query_Order_Direction_value = map[string]int32{ - "ASCENDING": 1, - "DESCENDING": 2, -} - -func (x Query_Order_Direction) Enum() *Query_Order_Direction { - p := new(Query_Order_Direction) - *p = x - return p -} -func (x Query_Order_Direction) String() string { - return proto.EnumName(Query_Order_Direction_name, int32(x)) -} -func (x *Query_Order_Direction) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Query_Order_Direction_value, data, "Query_Order_Direction") - if err != nil { - return err - } - *x = Query_Order_Direction(value) - return nil -} - -type Error_ErrorCode int32 - -const ( - Error_BAD_REQUEST Error_ErrorCode = 1 - Error_CONCURRENT_TRANSACTION Error_ErrorCode = 2 - Error_INTERNAL_ERROR Error_ErrorCode = 3 - Error_NEED_INDEX Error_ErrorCode = 4 - Error_TIMEOUT Error_ErrorCode = 5 - Error_PERMISSION_DENIED Error_ErrorCode = 6 - Error_BIGTABLE_ERROR Error_ErrorCode = 7 - Error_COMMITTED_BUT_STILL_APPLYING Error_ErrorCode = 8 - Error_CAPABILITY_DISABLED Error_ErrorCode = 9 - Error_TRY_ALTERNATE_BACKEND Error_ErrorCode = 10 - Error_SAFE_TIME_TOO_OLD Error_ErrorCode = 11 -) - -var Error_ErrorCode_name = map[int32]string{ - 1: "BAD_REQUEST", - 2: "CONCURRENT_TRANSACTION", - 3: "INTERNAL_ERROR", - 4: "NEED_INDEX", - 5: "TIMEOUT", - 6: "PERMISSION_DENIED", - 7: "BIGTABLE_ERROR", - 8: "COMMITTED_BUT_STILL_APPLYING", - 9: "CAPABILITY_DISABLED", - 10: "TRY_ALTERNATE_BACKEND", - 11: "SAFE_TIME_TOO_OLD", -} -var Error_ErrorCode_value = map[string]int32{ - "BAD_REQUEST": 1, - "CONCURRENT_TRANSACTION": 2, - "INTERNAL_ERROR": 3, - "NEED_INDEX": 4, - "TIMEOUT": 5, - "PERMISSION_DENIED": 6, - "BIGTABLE_ERROR": 7, - "COMMITTED_BUT_STILL_APPLYING": 8, - "CAPABILITY_DISABLED": 9, - "TRY_ALTERNATE_BACKEND": 10, - "SAFE_TIME_TOO_OLD": 11, -} - -func (x Error_ErrorCode) Enum() *Error_ErrorCode { - p := new(Error_ErrorCode) - *p = x - return p -} -func (x Error_ErrorCode) String() string { - return proto.EnumName(Error_ErrorCode_name, int32(x)) -} -func (x *Error_ErrorCode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(Error_ErrorCode_value, data, "Error_ErrorCode") - if err != nil { - return err - } - *x = Error_ErrorCode(value) - return nil -} - -type PutRequest_AutoIdPolicy int32 - -const ( - PutRequest_CURRENT PutRequest_AutoIdPolicy = 0 - PutRequest_SEQUENTIAL PutRequest_AutoIdPolicy = 1 -) - -var PutRequest_AutoIdPolicy_name = map[int32]string{ - 0: "CURRENT", - 1: "SEQUENTIAL", -} -var PutRequest_AutoIdPolicy_value = map[string]int32{ - "CURRENT": 0, - "SEQUENTIAL": 1, -} - -func (x PutRequest_AutoIdPolicy) Enum() *PutRequest_AutoIdPolicy { - p := new(PutRequest_AutoIdPolicy) - *p = x - return p -} -func (x PutRequest_AutoIdPolicy) String() string { - return proto.EnumName(PutRequest_AutoIdPolicy_name, int32(x)) -} -func (x *PutRequest_AutoIdPolicy) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(PutRequest_AutoIdPolicy_value, data, "PutRequest_AutoIdPolicy") - if err != nil { - return err - } - *x = PutRequest_AutoIdPolicy(value) - return nil -} - -type Action struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *Action) Reset() { *m = Action{} } -func (m *Action) String() string { return proto.CompactTextString(m) } -func (*Action) ProtoMessage() {} - -type PropertyValue struct { - Int64Value *int64 `protobuf:"varint,1,opt,name=int64Value" json:"int64Value,omitempty"` - BooleanValue *bool `protobuf:"varint,2,opt,name=booleanValue" json:"booleanValue,omitempty"` - StringValue *string `protobuf:"bytes,3,opt,name=stringValue" json:"stringValue,omitempty"` - DoubleValue *float64 `protobuf:"fixed64,4,opt,name=doubleValue" json:"doubleValue,omitempty"` - Pointvalue *PropertyValue_PointValue `protobuf:"group,5,opt,name=PointValue" json:"pointvalue,omitempty"` - Uservalue *PropertyValue_UserValue `protobuf:"group,8,opt,name=UserValue" json:"uservalue,omitempty"` - Referencevalue *PropertyValue_ReferenceValue `protobuf:"group,12,opt,name=ReferenceValue" json:"referencevalue,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PropertyValue) Reset() { *m = PropertyValue{} } -func (m *PropertyValue) String() string { return proto.CompactTextString(m) } -func (*PropertyValue) ProtoMessage() {} - -func (m *PropertyValue) GetInt64Value() int64 { - if m != nil && m.Int64Value != nil { - return *m.Int64Value - } - return 0 -} - -func (m *PropertyValue) GetBooleanValue() bool { - if m != nil && m.BooleanValue != nil { - return *m.BooleanValue - } - return false -} - -func (m *PropertyValue) GetStringValue() string { - if m != nil && m.StringValue != nil { - return *m.StringValue - } - return "" -} - -func (m *PropertyValue) GetDoubleValue() float64 { - if m != nil && m.DoubleValue != nil { - return *m.DoubleValue - } - return 0 -} - -func (m *PropertyValue) GetPointvalue() *PropertyValue_PointValue { - if m != nil { - return m.Pointvalue - } - return nil -} - -func (m *PropertyValue) GetUservalue() *PropertyValue_UserValue { - if m != nil { - return m.Uservalue - } - return nil -} - -func (m *PropertyValue) GetReferencevalue() *PropertyValue_ReferenceValue { - if m != nil { - return m.Referencevalue - } - return nil -} - -type PropertyValue_PointValue struct { - X *float64 `protobuf:"fixed64,6,req,name=x" json:"x,omitempty"` - Y *float64 `protobuf:"fixed64,7,req,name=y" json:"y,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PropertyValue_PointValue) Reset() { *m = PropertyValue_PointValue{} } -func (m *PropertyValue_PointValue) String() string { return proto.CompactTextString(m) } -func (*PropertyValue_PointValue) ProtoMessage() {} - -func (m *PropertyValue_PointValue) GetX() float64 { - if m != nil && m.X != nil { - return *m.X - } - return 0 -} - -func (m *PropertyValue_PointValue) GetY() float64 { - if m != nil && m.Y != nil { - return *m.Y - } - return 0 -} - -type PropertyValue_UserValue struct { - Email *string `protobuf:"bytes,9,req,name=email" json:"email,omitempty"` - AuthDomain *string `protobuf:"bytes,10,req,name=auth_domain" json:"auth_domain,omitempty"` - Nickname *string `protobuf:"bytes,11,opt,name=nickname" json:"nickname,omitempty"` - FederatedIdentity *string `protobuf:"bytes,21,opt,name=federated_identity" json:"federated_identity,omitempty"` - FederatedProvider *string `protobuf:"bytes,22,opt,name=federated_provider" json:"federated_provider,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PropertyValue_UserValue) Reset() { *m = PropertyValue_UserValue{} } -func (m *PropertyValue_UserValue) String() string { return proto.CompactTextString(m) } -func (*PropertyValue_UserValue) ProtoMessage() {} - -func (m *PropertyValue_UserValue) GetEmail() string { - if m != nil && m.Email != nil { - return *m.Email - } - return "" -} - -func (m *PropertyValue_UserValue) GetAuthDomain() string { - if m != nil && m.AuthDomain != nil { - return *m.AuthDomain - } - return "" -} - -func (m *PropertyValue_UserValue) GetNickname() string { - if m != nil && m.Nickname != nil { - return *m.Nickname - } - return "" -} - -func (m *PropertyValue_UserValue) GetFederatedIdentity() string { - if m != nil && m.FederatedIdentity != nil { - return *m.FederatedIdentity - } - return "" -} - -func (m *PropertyValue_UserValue) GetFederatedProvider() string { - if m != nil && m.FederatedProvider != nil { - return *m.FederatedProvider - } - return "" -} - -type PropertyValue_ReferenceValue struct { - App *string `protobuf:"bytes,13,req,name=app" json:"app,omitempty"` - NameSpace *string `protobuf:"bytes,20,opt,name=name_space" json:"name_space,omitempty"` - Pathelement []*PropertyValue_ReferenceValue_PathElement `protobuf:"group,14,rep,name=PathElement" json:"pathelement,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PropertyValue_ReferenceValue) Reset() { *m = PropertyValue_ReferenceValue{} } -func (m *PropertyValue_ReferenceValue) String() string { return proto.CompactTextString(m) } -func (*PropertyValue_ReferenceValue) ProtoMessage() {} - -func (m *PropertyValue_ReferenceValue) GetApp() string { - if m != nil && m.App != nil { - return *m.App - } - return "" -} - -func (m *PropertyValue_ReferenceValue) GetNameSpace() string { - if m != nil && m.NameSpace != nil { - return *m.NameSpace - } - return "" -} - -func (m *PropertyValue_ReferenceValue) GetPathelement() []*PropertyValue_ReferenceValue_PathElement { - if m != nil { - return m.Pathelement - } - return nil -} - -type PropertyValue_ReferenceValue_PathElement struct { - Type *string `protobuf:"bytes,15,req,name=type" json:"type,omitempty"` - Id *int64 `protobuf:"varint,16,opt,name=id" json:"id,omitempty"` - Name *string `protobuf:"bytes,17,opt,name=name" json:"name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PropertyValue_ReferenceValue_PathElement) Reset() { - *m = PropertyValue_ReferenceValue_PathElement{} -} -func (m *PropertyValue_ReferenceValue_PathElement) String() string { return proto.CompactTextString(m) } -func (*PropertyValue_ReferenceValue_PathElement) ProtoMessage() {} - -func (m *PropertyValue_ReferenceValue_PathElement) GetType() string { - if m != nil && m.Type != nil { - return *m.Type - } - return "" -} - -func (m *PropertyValue_ReferenceValue_PathElement) GetId() int64 { - if m != nil && m.Id != nil { - return *m.Id - } - return 0 -} - -func (m *PropertyValue_ReferenceValue_PathElement) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -type Property struct { - Meaning *Property_Meaning `protobuf:"varint,1,opt,name=meaning,enum=appengine.Property_Meaning,def=0" json:"meaning,omitempty"` - MeaningUri *string `protobuf:"bytes,2,opt,name=meaning_uri" json:"meaning_uri,omitempty"` - Name *string `protobuf:"bytes,3,req,name=name" json:"name,omitempty"` - Value *PropertyValue `protobuf:"bytes,5,req,name=value" json:"value,omitempty"` - Multiple *bool `protobuf:"varint,4,req,name=multiple" json:"multiple,omitempty"` - Searchable *bool `protobuf:"varint,6,opt,name=searchable,def=0" json:"searchable,omitempty"` - FtsTokenizationOption *Property_FtsTokenizationOption `protobuf:"varint,8,opt,name=fts_tokenization_option,enum=appengine.Property_FtsTokenizationOption" json:"fts_tokenization_option,omitempty"` - Locale *string `protobuf:"bytes,9,opt,name=locale,def=en" json:"locale,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Property) Reset() { *m = Property{} } -func (m *Property) String() string { return proto.CompactTextString(m) } -func (*Property) ProtoMessage() {} - -const Default_Property_Meaning Property_Meaning = Property_NO_MEANING -const Default_Property_Searchable bool = false -const Default_Property_Locale string = "en" - -func (m *Property) GetMeaning() Property_Meaning { - if m != nil && m.Meaning != nil { - return *m.Meaning - } - return Default_Property_Meaning -} - -func (m *Property) GetMeaningUri() string { - if m != nil && m.MeaningUri != nil { - return *m.MeaningUri - } - return "" -} - -func (m *Property) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *Property) GetValue() *PropertyValue { - if m != nil { - return m.Value - } - return nil -} - -func (m *Property) GetMultiple() bool { - if m != nil && m.Multiple != nil { - return *m.Multiple - } - return false -} - -func (m *Property) GetSearchable() bool { - if m != nil && m.Searchable != nil { - return *m.Searchable - } - return Default_Property_Searchable -} - -func (m *Property) GetFtsTokenizationOption() Property_FtsTokenizationOption { - if m != nil && m.FtsTokenizationOption != nil { - return *m.FtsTokenizationOption - } - return Property_HTML -} - -func (m *Property) GetLocale() string { - if m != nil && m.Locale != nil { - return *m.Locale - } - return Default_Property_Locale -} - -type Path struct { - Element []*Path_Element `protobuf:"group,1,rep,name=Element" json:"element,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Path) Reset() { *m = Path{} } -func (m *Path) String() string { return proto.CompactTextString(m) } -func (*Path) ProtoMessage() {} - -func (m *Path) GetElement() []*Path_Element { - if m != nil { - return m.Element - } - return nil -} - -type Path_Element struct { - Type *string `protobuf:"bytes,2,req,name=type" json:"type,omitempty"` - Id *int64 `protobuf:"varint,3,opt,name=id" json:"id,omitempty"` - Name *string `protobuf:"bytes,4,opt,name=name" json:"name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Path_Element) Reset() { *m = Path_Element{} } -func (m *Path_Element) String() string { return proto.CompactTextString(m) } -func (*Path_Element) ProtoMessage() {} - -func (m *Path_Element) GetType() string { - if m != nil && m.Type != nil { - return *m.Type - } - return "" -} - -func (m *Path_Element) GetId() int64 { - if m != nil && m.Id != nil { - return *m.Id - } - return 0 -} - -func (m *Path_Element) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -type Reference struct { - App *string `protobuf:"bytes,13,req,name=app" json:"app,omitempty"` - NameSpace *string `protobuf:"bytes,20,opt,name=name_space" json:"name_space,omitempty"` - Path *Path `protobuf:"bytes,14,req,name=path" json:"path,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Reference) Reset() { *m = Reference{} } -func (m *Reference) String() string { return proto.CompactTextString(m) } -func (*Reference) ProtoMessage() {} - -func (m *Reference) GetApp() string { - if m != nil && m.App != nil { - return *m.App - } - return "" -} - -func (m *Reference) GetNameSpace() string { - if m != nil && m.NameSpace != nil { - return *m.NameSpace - } - return "" -} - -func (m *Reference) GetPath() *Path { - if m != nil { - return m.Path - } - return nil -} - -type User struct { - Email *string `protobuf:"bytes,1,req,name=email" json:"email,omitempty"` - AuthDomain *string `protobuf:"bytes,2,req,name=auth_domain" json:"auth_domain,omitempty"` - Nickname *string `protobuf:"bytes,3,opt,name=nickname" json:"nickname,omitempty"` - FederatedIdentity *string `protobuf:"bytes,6,opt,name=federated_identity" json:"federated_identity,omitempty"` - FederatedProvider *string `protobuf:"bytes,7,opt,name=federated_provider" json:"federated_provider,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *User) Reset() { *m = User{} } -func (m *User) String() string { return proto.CompactTextString(m) } -func (*User) ProtoMessage() {} - -func (m *User) GetEmail() string { - if m != nil && m.Email != nil { - return *m.Email - } - return "" -} - -func (m *User) GetAuthDomain() string { - if m != nil && m.AuthDomain != nil { - return *m.AuthDomain - } - return "" -} - -func (m *User) GetNickname() string { - if m != nil && m.Nickname != nil { - return *m.Nickname - } - return "" -} - -func (m *User) GetFederatedIdentity() string { - if m != nil && m.FederatedIdentity != nil { - return *m.FederatedIdentity - } - return "" -} - -func (m *User) GetFederatedProvider() string { - if m != nil && m.FederatedProvider != nil { - return *m.FederatedProvider - } - return "" -} - -type EntityProto struct { - Key *Reference `protobuf:"bytes,13,req,name=key" json:"key,omitempty"` - EntityGroup *Path `protobuf:"bytes,16,req,name=entity_group" json:"entity_group,omitempty"` - Owner *User `protobuf:"bytes,17,opt,name=owner" json:"owner,omitempty"` - Kind *EntityProto_Kind `protobuf:"varint,4,opt,name=kind,enum=appengine.EntityProto_Kind" json:"kind,omitempty"` - KindUri *string `protobuf:"bytes,5,opt,name=kind_uri" json:"kind_uri,omitempty"` - Property []*Property `protobuf:"bytes,14,rep,name=property" json:"property,omitempty"` - RawProperty []*Property `protobuf:"bytes,15,rep,name=raw_property" json:"raw_property,omitempty"` - Rank *int32 `protobuf:"varint,18,opt,name=rank" json:"rank,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *EntityProto) Reset() { *m = EntityProto{} } -func (m *EntityProto) String() string { return proto.CompactTextString(m) } -func (*EntityProto) ProtoMessage() {} - -func (m *EntityProto) GetKey() *Reference { - if m != nil { - return m.Key - } - return nil -} - -func (m *EntityProto) GetEntityGroup() *Path { - if m != nil { - return m.EntityGroup - } - return nil -} - -func (m *EntityProto) GetOwner() *User { - if m != nil { - return m.Owner - } - return nil -} - -func (m *EntityProto) GetKind() EntityProto_Kind { - if m != nil && m.Kind != nil { - return *m.Kind - } - return EntityProto_GD_CONTACT -} - -func (m *EntityProto) GetKindUri() string { - if m != nil && m.KindUri != nil { - return *m.KindUri - } - return "" -} - -func (m *EntityProto) GetProperty() []*Property { - if m != nil { - return m.Property - } - return nil -} - -func (m *EntityProto) GetRawProperty() []*Property { - if m != nil { - return m.RawProperty - } - return nil -} - -func (m *EntityProto) GetRank() int32 { - if m != nil && m.Rank != nil { - return *m.Rank - } - return 0 -} - -type CompositeProperty struct { - IndexId *int64 `protobuf:"varint,1,req,name=index_id" json:"index_id,omitempty"` - Value []string `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CompositeProperty) Reset() { *m = CompositeProperty{} } -func (m *CompositeProperty) String() string { return proto.CompactTextString(m) } -func (*CompositeProperty) ProtoMessage() {} - -func (m *CompositeProperty) GetIndexId() int64 { - if m != nil && m.IndexId != nil { - return *m.IndexId - } - return 0 -} - -func (m *CompositeProperty) GetValue() []string { - if m != nil { - return m.Value - } - return nil -} - -type Index struct { - EntityType *string `protobuf:"bytes,1,req,name=entity_type" json:"entity_type,omitempty"` - Ancestor *bool `protobuf:"varint,5,req,name=ancestor" json:"ancestor,omitempty"` - Property []*Index_Property `protobuf:"group,2,rep,name=Property" json:"property,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Index) Reset() { *m = Index{} } -func (m *Index) String() string { return proto.CompactTextString(m) } -func (*Index) ProtoMessage() {} - -func (m *Index) GetEntityType() string { - if m != nil && m.EntityType != nil { - return *m.EntityType - } - return "" -} - -func (m *Index) GetAncestor() bool { - if m != nil && m.Ancestor != nil { - return *m.Ancestor - } - return false -} - -func (m *Index) GetProperty() []*Index_Property { - if m != nil { - return m.Property - } - return nil -} - -type Index_Property struct { - Name *string `protobuf:"bytes,3,req,name=name" json:"name,omitempty"` - Direction *Index_Property_Direction `protobuf:"varint,4,opt,name=direction,enum=appengine.Index_Property_Direction,def=1" json:"direction,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Index_Property) Reset() { *m = Index_Property{} } -func (m *Index_Property) String() string { return proto.CompactTextString(m) } -func (*Index_Property) ProtoMessage() {} - -const Default_Index_Property_Direction Index_Property_Direction = Index_Property_ASCENDING - -func (m *Index_Property) GetName() string { - if m != nil && m.Name != nil { - return *m.Name - } - return "" -} - -func (m *Index_Property) GetDirection() Index_Property_Direction { - if m != nil && m.Direction != nil { - return *m.Direction - } - return Default_Index_Property_Direction -} - -type CompositeIndex struct { - AppId *string `protobuf:"bytes,1,req,name=app_id" json:"app_id,omitempty"` - Id *int64 `protobuf:"varint,2,req,name=id" json:"id,omitempty"` - Definition *Index `protobuf:"bytes,3,req,name=definition" json:"definition,omitempty"` - State *CompositeIndex_State `protobuf:"varint,4,req,name=state,enum=appengine.CompositeIndex_State" json:"state,omitempty"` - OnlyUseIfRequired *bool `protobuf:"varint,6,opt,name=only_use_if_required,def=0" json:"only_use_if_required,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CompositeIndex) Reset() { *m = CompositeIndex{} } -func (m *CompositeIndex) String() string { return proto.CompactTextString(m) } -func (*CompositeIndex) ProtoMessage() {} - -const Default_CompositeIndex_OnlyUseIfRequired bool = false - -func (m *CompositeIndex) GetAppId() string { - if m != nil && m.AppId != nil { - return *m.AppId - } - return "" -} - -func (m *CompositeIndex) GetId() int64 { - if m != nil && m.Id != nil { - return *m.Id - } - return 0 -} - -func (m *CompositeIndex) GetDefinition() *Index { - if m != nil { - return m.Definition - } - return nil -} - -func (m *CompositeIndex) GetState() CompositeIndex_State { - if m != nil && m.State != nil { - return *m.State - } - return CompositeIndex_WRITE_ONLY -} - -func (m *CompositeIndex) GetOnlyUseIfRequired() bool { - if m != nil && m.OnlyUseIfRequired != nil { - return *m.OnlyUseIfRequired - } - return Default_CompositeIndex_OnlyUseIfRequired -} - -type IndexPostfix struct { - IndexValue []*IndexPostfix_IndexValue `protobuf:"bytes,1,rep,name=index_value" json:"index_value,omitempty"` - Key *Reference `protobuf:"bytes,2,opt,name=key" json:"key,omitempty"` - Before *bool `protobuf:"varint,3,opt,name=before,def=1" json:"before,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *IndexPostfix) Reset() { *m = IndexPostfix{} } -func (m *IndexPostfix) String() string { return proto.CompactTextString(m) } -func (*IndexPostfix) ProtoMessage() {} - -const Default_IndexPostfix_Before bool = true - -func (m *IndexPostfix) GetIndexValue() []*IndexPostfix_IndexValue { - if m != nil { - return m.IndexValue - } - return nil -} - -func (m *IndexPostfix) GetKey() *Reference { - if m != nil { - return m.Key - } - return nil -} - -func (m *IndexPostfix) GetBefore() bool { - if m != nil && m.Before != nil { - return *m.Before - } - return Default_IndexPostfix_Before -} - -type IndexPostfix_IndexValue struct { - PropertyName *string `protobuf:"bytes,1,req,name=property_name" json:"property_name,omitempty"` - Value *PropertyValue `protobuf:"bytes,2,req,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *IndexPostfix_IndexValue) Reset() { *m = IndexPostfix_IndexValue{} } -func (m *IndexPostfix_IndexValue) String() string { return proto.CompactTextString(m) } -func (*IndexPostfix_IndexValue) ProtoMessage() {} - -func (m *IndexPostfix_IndexValue) GetPropertyName() string { - if m != nil && m.PropertyName != nil { - return *m.PropertyName - } - return "" -} - -func (m *IndexPostfix_IndexValue) GetValue() *PropertyValue { - if m != nil { - return m.Value - } - return nil -} - -type IndexPosition struct { - Key *string `protobuf:"bytes,1,opt,name=key" json:"key,omitempty"` - Before *bool `protobuf:"varint,2,opt,name=before,def=1" json:"before,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *IndexPosition) Reset() { *m = IndexPosition{} } -func (m *IndexPosition) String() string { return proto.CompactTextString(m) } -func (*IndexPosition) ProtoMessage() {} - -const Default_IndexPosition_Before bool = true - -func (m *IndexPosition) GetKey() string { - if m != nil && m.Key != nil { - return *m.Key - } - return "" -} - -func (m *IndexPosition) GetBefore() bool { - if m != nil && m.Before != nil { - return *m.Before - } - return Default_IndexPosition_Before -} - -type Snapshot struct { - Ts *int64 `protobuf:"varint,1,req,name=ts" json:"ts,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Snapshot) Reset() { *m = Snapshot{} } -func (m *Snapshot) String() string { return proto.CompactTextString(m) } -func (*Snapshot) ProtoMessage() {} - -func (m *Snapshot) GetTs() int64 { - if m != nil && m.Ts != nil { - return *m.Ts - } - return 0 -} - -type InternalHeader struct { - Qos *string `protobuf:"bytes,1,opt,name=qos" json:"qos,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *InternalHeader) Reset() { *m = InternalHeader{} } -func (m *InternalHeader) String() string { return proto.CompactTextString(m) } -func (*InternalHeader) ProtoMessage() {} - -func (m *InternalHeader) GetQos() string { - if m != nil && m.Qos != nil { - return *m.Qos - } - return "" -} - -type Transaction struct { - Header *InternalHeader `protobuf:"bytes,4,opt,name=header" json:"header,omitempty"` - Handle *uint64 `protobuf:"fixed64,1,req,name=handle" json:"handle,omitempty"` - App *string `protobuf:"bytes,2,req,name=app" json:"app,omitempty"` - MarkChanges *bool `protobuf:"varint,3,opt,name=mark_changes,def=0" json:"mark_changes,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Transaction) Reset() { *m = Transaction{} } -func (m *Transaction) String() string { return proto.CompactTextString(m) } -func (*Transaction) ProtoMessage() {} - -const Default_Transaction_MarkChanges bool = false - -func (m *Transaction) GetHeader() *InternalHeader { - if m != nil { - return m.Header - } - return nil -} - -func (m *Transaction) GetHandle() uint64 { - if m != nil && m.Handle != nil { - return *m.Handle - } - return 0 -} - -func (m *Transaction) GetApp() string { - if m != nil && m.App != nil { - return *m.App - } - return "" -} - -func (m *Transaction) GetMarkChanges() bool { - if m != nil && m.MarkChanges != nil { - return *m.MarkChanges - } - return Default_Transaction_MarkChanges -} - -type Query struct { - Header *InternalHeader `protobuf:"bytes,39,opt,name=header" json:"header,omitempty"` - App *string `protobuf:"bytes,1,req,name=app" json:"app,omitempty"` - NameSpace *string `protobuf:"bytes,29,opt,name=name_space" json:"name_space,omitempty"` - Kind *string `protobuf:"bytes,3,opt,name=kind" json:"kind,omitempty"` - Ancestor *Reference `protobuf:"bytes,17,opt,name=ancestor" json:"ancestor,omitempty"` - Filter []*Query_Filter `protobuf:"group,4,rep,name=Filter" json:"filter,omitempty"` - SearchQuery *string `protobuf:"bytes,8,opt,name=search_query" json:"search_query,omitempty"` - Order []*Query_Order `protobuf:"group,9,rep,name=Order" json:"order,omitempty"` - Hint *Query_Hint `protobuf:"varint,18,opt,name=hint,enum=appengine.Query_Hint" json:"hint,omitempty"` - Count *int32 `protobuf:"varint,23,opt,name=count" json:"count,omitempty"` - Offset *int32 `protobuf:"varint,12,opt,name=offset,def=0" json:"offset,omitempty"` - Limit *int32 `protobuf:"varint,16,opt,name=limit" json:"limit,omitempty"` - CompiledCursor *CompiledCursor `protobuf:"bytes,30,opt,name=compiled_cursor" json:"compiled_cursor,omitempty"` - EndCompiledCursor *CompiledCursor `protobuf:"bytes,31,opt,name=end_compiled_cursor" json:"end_compiled_cursor,omitempty"` - CompositeIndex []*CompositeIndex `protobuf:"bytes,19,rep,name=composite_index" json:"composite_index,omitempty"` - RequirePerfectPlan *bool `protobuf:"varint,20,opt,name=require_perfect_plan,def=0" json:"require_perfect_plan,omitempty"` - KeysOnly *bool `protobuf:"varint,21,opt,name=keys_only,def=0" json:"keys_only,omitempty"` - Transaction *Transaction `protobuf:"bytes,22,opt,name=transaction" json:"transaction,omitempty"` - Compile *bool `protobuf:"varint,25,opt,name=compile,def=0" json:"compile,omitempty"` - FailoverMs *int64 `protobuf:"varint,26,opt,name=failover_ms" json:"failover_ms,omitempty"` - Strong *bool `protobuf:"varint,32,opt,name=strong" json:"strong,omitempty"` - PropertyName []string `protobuf:"bytes,33,rep,name=property_name" json:"property_name,omitempty"` - GroupByPropertyName []string `protobuf:"bytes,34,rep,name=group_by_property_name" json:"group_by_property_name,omitempty"` - Distinct *bool `protobuf:"varint,24,opt,name=distinct" json:"distinct,omitempty"` - MinSafeTimeSeconds *int64 `protobuf:"varint,35,opt,name=min_safe_time_seconds" json:"min_safe_time_seconds,omitempty"` - SafeReplicaName []string `protobuf:"bytes,36,rep,name=safe_replica_name" json:"safe_replica_name,omitempty"` - PersistOffset *bool `protobuf:"varint,37,opt,name=persist_offset,def=0" json:"persist_offset,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Query) Reset() { *m = Query{} } -func (m *Query) String() string { return proto.CompactTextString(m) } -func (*Query) ProtoMessage() {} - -const Default_Query_Offset int32 = 0 -const Default_Query_RequirePerfectPlan bool = false -const Default_Query_KeysOnly bool = false -const Default_Query_Compile bool = false -const Default_Query_PersistOffset bool = false - -func (m *Query) GetHeader() *InternalHeader { - if m != nil { - return m.Header - } - return nil -} - -func (m *Query) GetApp() string { - if m != nil && m.App != nil { - return *m.App - } - return "" -} - -func (m *Query) GetNameSpace() string { - if m != nil && m.NameSpace != nil { - return *m.NameSpace - } - return "" -} - -func (m *Query) GetKind() string { - if m != nil && m.Kind != nil { - return *m.Kind - } - return "" -} - -func (m *Query) GetAncestor() *Reference { - if m != nil { - return m.Ancestor - } - return nil -} - -func (m *Query) GetFilter() []*Query_Filter { - if m != nil { - return m.Filter - } - return nil -} - -func (m *Query) GetSearchQuery() string { - if m != nil && m.SearchQuery != nil { - return *m.SearchQuery - } - return "" -} - -func (m *Query) GetOrder() []*Query_Order { - if m != nil { - return m.Order - } - return nil -} - -func (m *Query) GetHint() Query_Hint { - if m != nil && m.Hint != nil { - return *m.Hint - } - return Query_ORDER_FIRST -} - -func (m *Query) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -func (m *Query) GetOffset() int32 { - if m != nil && m.Offset != nil { - return *m.Offset - } - return Default_Query_Offset -} - -func (m *Query) GetLimit() int32 { - if m != nil && m.Limit != nil { - return *m.Limit - } - return 0 -} - -func (m *Query) GetCompiledCursor() *CompiledCursor { - if m != nil { - return m.CompiledCursor - } - return nil -} - -func (m *Query) GetEndCompiledCursor() *CompiledCursor { - if m != nil { - return m.EndCompiledCursor - } - return nil -} - -func (m *Query) GetCompositeIndex() []*CompositeIndex { - if m != nil { - return m.CompositeIndex - } - return nil -} - -func (m *Query) GetRequirePerfectPlan() bool { - if m != nil && m.RequirePerfectPlan != nil { - return *m.RequirePerfectPlan - } - return Default_Query_RequirePerfectPlan -} - -func (m *Query) GetKeysOnly() bool { - if m != nil && m.KeysOnly != nil { - return *m.KeysOnly - } - return Default_Query_KeysOnly -} - -func (m *Query) GetTransaction() *Transaction { - if m != nil { - return m.Transaction - } - return nil -} - -func (m *Query) GetCompile() bool { - if m != nil && m.Compile != nil { - return *m.Compile - } - return Default_Query_Compile -} - -func (m *Query) GetFailoverMs() int64 { - if m != nil && m.FailoverMs != nil { - return *m.FailoverMs - } - return 0 -} - -func (m *Query) GetStrong() bool { - if m != nil && m.Strong != nil { - return *m.Strong - } - return false -} - -func (m *Query) GetPropertyName() []string { - if m != nil { - return m.PropertyName - } - return nil -} - -func (m *Query) GetGroupByPropertyName() []string { - if m != nil { - return m.GroupByPropertyName - } - return nil -} - -func (m *Query) GetDistinct() bool { - if m != nil && m.Distinct != nil { - return *m.Distinct - } - return false -} - -func (m *Query) GetMinSafeTimeSeconds() int64 { - if m != nil && m.MinSafeTimeSeconds != nil { - return *m.MinSafeTimeSeconds - } - return 0 -} - -func (m *Query) GetSafeReplicaName() []string { - if m != nil { - return m.SafeReplicaName - } - return nil -} - -func (m *Query) GetPersistOffset() bool { - if m != nil && m.PersistOffset != nil { - return *m.PersistOffset - } - return Default_Query_PersistOffset -} - -type Query_Filter struct { - Op *Query_Filter_Operator `protobuf:"varint,6,req,name=op,enum=appengine.Query_Filter_Operator" json:"op,omitempty"` - Property []*Property `protobuf:"bytes,14,rep,name=property" json:"property,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Query_Filter) Reset() { *m = Query_Filter{} } -func (m *Query_Filter) String() string { return proto.CompactTextString(m) } -func (*Query_Filter) ProtoMessage() {} - -func (m *Query_Filter) GetOp() Query_Filter_Operator { - if m != nil && m.Op != nil { - return *m.Op - } - return Query_Filter_LESS_THAN -} - -func (m *Query_Filter) GetProperty() []*Property { - if m != nil { - return m.Property - } - return nil -} - -type Query_Order struct { - Property *string `protobuf:"bytes,10,req,name=property" json:"property,omitempty"` - Direction *Query_Order_Direction `protobuf:"varint,11,opt,name=direction,enum=appengine.Query_Order_Direction,def=1" json:"direction,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Query_Order) Reset() { *m = Query_Order{} } -func (m *Query_Order) String() string { return proto.CompactTextString(m) } -func (*Query_Order) ProtoMessage() {} - -const Default_Query_Order_Direction Query_Order_Direction = Query_Order_ASCENDING - -func (m *Query_Order) GetProperty() string { - if m != nil && m.Property != nil { - return *m.Property - } - return "" -} - -func (m *Query_Order) GetDirection() Query_Order_Direction { - if m != nil && m.Direction != nil { - return *m.Direction - } - return Default_Query_Order_Direction -} - -type CompiledQuery struct { - Primaryscan *CompiledQuery_PrimaryScan `protobuf:"group,1,req,name=PrimaryScan" json:"primaryscan,omitempty"` - Mergejoinscan []*CompiledQuery_MergeJoinScan `protobuf:"group,7,rep,name=MergeJoinScan" json:"mergejoinscan,omitempty"` - IndexDef *Index `protobuf:"bytes,21,opt,name=index_def" json:"index_def,omitempty"` - Offset *int32 `protobuf:"varint,10,opt,name=offset,def=0" json:"offset,omitempty"` - Limit *int32 `protobuf:"varint,11,opt,name=limit" json:"limit,omitempty"` - KeysOnly *bool `protobuf:"varint,12,req,name=keys_only" json:"keys_only,omitempty"` - PropertyName []string `protobuf:"bytes,24,rep,name=property_name" json:"property_name,omitempty"` - DistinctInfixSize *int32 `protobuf:"varint,25,opt,name=distinct_infix_size" json:"distinct_infix_size,omitempty"` - Entityfilter *CompiledQuery_EntityFilter `protobuf:"group,13,opt,name=EntityFilter" json:"entityfilter,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CompiledQuery) Reset() { *m = CompiledQuery{} } -func (m *CompiledQuery) String() string { return proto.CompactTextString(m) } -func (*CompiledQuery) ProtoMessage() {} - -const Default_CompiledQuery_Offset int32 = 0 - -func (m *CompiledQuery) GetPrimaryscan() *CompiledQuery_PrimaryScan { - if m != nil { - return m.Primaryscan - } - return nil -} - -func (m *CompiledQuery) GetMergejoinscan() []*CompiledQuery_MergeJoinScan { - if m != nil { - return m.Mergejoinscan - } - return nil -} - -func (m *CompiledQuery) GetIndexDef() *Index { - if m != nil { - return m.IndexDef - } - return nil -} - -func (m *CompiledQuery) GetOffset() int32 { - if m != nil && m.Offset != nil { - return *m.Offset - } - return Default_CompiledQuery_Offset -} - -func (m *CompiledQuery) GetLimit() int32 { - if m != nil && m.Limit != nil { - return *m.Limit - } - return 0 -} - -func (m *CompiledQuery) GetKeysOnly() bool { - if m != nil && m.KeysOnly != nil { - return *m.KeysOnly - } - return false -} - -func (m *CompiledQuery) GetPropertyName() []string { - if m != nil { - return m.PropertyName - } - return nil -} - -func (m *CompiledQuery) GetDistinctInfixSize() int32 { - if m != nil && m.DistinctInfixSize != nil { - return *m.DistinctInfixSize - } - return 0 -} - -func (m *CompiledQuery) GetEntityfilter() *CompiledQuery_EntityFilter { - if m != nil { - return m.Entityfilter - } - return nil -} - -type CompiledQuery_PrimaryScan struct { - IndexName *string `protobuf:"bytes,2,opt,name=index_name" json:"index_name,omitempty"` - StartKey *string `protobuf:"bytes,3,opt,name=start_key" json:"start_key,omitempty"` - StartInclusive *bool `protobuf:"varint,4,opt,name=start_inclusive" json:"start_inclusive,omitempty"` - EndKey *string `protobuf:"bytes,5,opt,name=end_key" json:"end_key,omitempty"` - EndInclusive *bool `protobuf:"varint,6,opt,name=end_inclusive" json:"end_inclusive,omitempty"` - StartPostfixValue []string `protobuf:"bytes,22,rep,name=start_postfix_value" json:"start_postfix_value,omitempty"` - EndPostfixValue []string `protobuf:"bytes,23,rep,name=end_postfix_value" json:"end_postfix_value,omitempty"` - EndUnappliedLogTimestampUs *int64 `protobuf:"varint,19,opt,name=end_unapplied_log_timestamp_us" json:"end_unapplied_log_timestamp_us,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CompiledQuery_PrimaryScan) Reset() { *m = CompiledQuery_PrimaryScan{} } -func (m *CompiledQuery_PrimaryScan) String() string { return proto.CompactTextString(m) } -func (*CompiledQuery_PrimaryScan) ProtoMessage() {} - -func (m *CompiledQuery_PrimaryScan) GetIndexName() string { - if m != nil && m.IndexName != nil { - return *m.IndexName - } - return "" -} - -func (m *CompiledQuery_PrimaryScan) GetStartKey() string { - if m != nil && m.StartKey != nil { - return *m.StartKey - } - return "" -} - -func (m *CompiledQuery_PrimaryScan) GetStartInclusive() bool { - if m != nil && m.StartInclusive != nil { - return *m.StartInclusive - } - return false -} - -func (m *CompiledQuery_PrimaryScan) GetEndKey() string { - if m != nil && m.EndKey != nil { - return *m.EndKey - } - return "" -} - -func (m *CompiledQuery_PrimaryScan) GetEndInclusive() bool { - if m != nil && m.EndInclusive != nil { - return *m.EndInclusive - } - return false -} - -func (m *CompiledQuery_PrimaryScan) GetStartPostfixValue() []string { - if m != nil { - return m.StartPostfixValue - } - return nil -} - -func (m *CompiledQuery_PrimaryScan) GetEndPostfixValue() []string { - if m != nil { - return m.EndPostfixValue - } - return nil -} - -func (m *CompiledQuery_PrimaryScan) GetEndUnappliedLogTimestampUs() int64 { - if m != nil && m.EndUnappliedLogTimestampUs != nil { - return *m.EndUnappliedLogTimestampUs - } - return 0 -} - -type CompiledQuery_MergeJoinScan struct { - IndexName *string `protobuf:"bytes,8,req,name=index_name" json:"index_name,omitempty"` - PrefixValue []string `protobuf:"bytes,9,rep,name=prefix_value" json:"prefix_value,omitempty"` - ValuePrefix *bool `protobuf:"varint,20,opt,name=value_prefix,def=0" json:"value_prefix,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CompiledQuery_MergeJoinScan) Reset() { *m = CompiledQuery_MergeJoinScan{} } -func (m *CompiledQuery_MergeJoinScan) String() string { return proto.CompactTextString(m) } -func (*CompiledQuery_MergeJoinScan) ProtoMessage() {} - -const Default_CompiledQuery_MergeJoinScan_ValuePrefix bool = false - -func (m *CompiledQuery_MergeJoinScan) GetIndexName() string { - if m != nil && m.IndexName != nil { - return *m.IndexName - } - return "" -} - -func (m *CompiledQuery_MergeJoinScan) GetPrefixValue() []string { - if m != nil { - return m.PrefixValue - } - return nil -} - -func (m *CompiledQuery_MergeJoinScan) GetValuePrefix() bool { - if m != nil && m.ValuePrefix != nil { - return *m.ValuePrefix - } - return Default_CompiledQuery_MergeJoinScan_ValuePrefix -} - -type CompiledQuery_EntityFilter struct { - Distinct *bool `protobuf:"varint,14,opt,name=distinct,def=0" json:"distinct,omitempty"` - Kind *string `protobuf:"bytes,17,opt,name=kind" json:"kind,omitempty"` - Ancestor *Reference `protobuf:"bytes,18,opt,name=ancestor" json:"ancestor,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CompiledQuery_EntityFilter) Reset() { *m = CompiledQuery_EntityFilter{} } -func (m *CompiledQuery_EntityFilter) String() string { return proto.CompactTextString(m) } -func (*CompiledQuery_EntityFilter) ProtoMessage() {} - -const Default_CompiledQuery_EntityFilter_Distinct bool = false - -func (m *CompiledQuery_EntityFilter) GetDistinct() bool { - if m != nil && m.Distinct != nil { - return *m.Distinct - } - return Default_CompiledQuery_EntityFilter_Distinct -} - -func (m *CompiledQuery_EntityFilter) GetKind() string { - if m != nil && m.Kind != nil { - return *m.Kind - } - return "" -} - -func (m *CompiledQuery_EntityFilter) GetAncestor() *Reference { - if m != nil { - return m.Ancestor - } - return nil -} - -type CompiledCursor struct { - Position *CompiledCursor_Position `protobuf:"group,2,opt,name=Position" json:"position,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CompiledCursor) Reset() { *m = CompiledCursor{} } -func (m *CompiledCursor) String() string { return proto.CompactTextString(m) } -func (*CompiledCursor) ProtoMessage() {} - -func (m *CompiledCursor) GetPosition() *CompiledCursor_Position { - if m != nil { - return m.Position - } - return nil -} - -type CompiledCursor_Position struct { - StartKey *string `protobuf:"bytes,27,opt,name=start_key" json:"start_key,omitempty"` - Indexvalue []*CompiledCursor_Position_IndexValue `protobuf:"group,29,rep,name=IndexValue" json:"indexvalue,omitempty"` - Key *Reference `protobuf:"bytes,32,opt,name=key" json:"key,omitempty"` - StartInclusive *bool `protobuf:"varint,28,opt,name=start_inclusive,def=1" json:"start_inclusive,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CompiledCursor_Position) Reset() { *m = CompiledCursor_Position{} } -func (m *CompiledCursor_Position) String() string { return proto.CompactTextString(m) } -func (*CompiledCursor_Position) ProtoMessage() {} - -const Default_CompiledCursor_Position_StartInclusive bool = true - -func (m *CompiledCursor_Position) GetStartKey() string { - if m != nil && m.StartKey != nil { - return *m.StartKey - } - return "" -} - -func (m *CompiledCursor_Position) GetIndexvalue() []*CompiledCursor_Position_IndexValue { - if m != nil { - return m.Indexvalue - } - return nil -} - -func (m *CompiledCursor_Position) GetKey() *Reference { - if m != nil { - return m.Key - } - return nil -} - -func (m *CompiledCursor_Position) GetStartInclusive() bool { - if m != nil && m.StartInclusive != nil { - return *m.StartInclusive - } - return Default_CompiledCursor_Position_StartInclusive -} - -type CompiledCursor_Position_IndexValue struct { - Property *string `protobuf:"bytes,30,opt,name=property" json:"property,omitempty"` - Value *PropertyValue `protobuf:"bytes,31,req,name=value" json:"value,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CompiledCursor_Position_IndexValue) Reset() { *m = CompiledCursor_Position_IndexValue{} } -func (m *CompiledCursor_Position_IndexValue) String() string { return proto.CompactTextString(m) } -func (*CompiledCursor_Position_IndexValue) ProtoMessage() {} - -func (m *CompiledCursor_Position_IndexValue) GetProperty() string { - if m != nil && m.Property != nil { - return *m.Property - } - return "" -} - -func (m *CompiledCursor_Position_IndexValue) GetValue() *PropertyValue { - if m != nil { - return m.Value - } - return nil -} - -type Cursor struct { - Cursor *uint64 `protobuf:"fixed64,1,req,name=cursor" json:"cursor,omitempty"` - App *string `protobuf:"bytes,2,opt,name=app" json:"app,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Cursor) Reset() { *m = Cursor{} } -func (m *Cursor) String() string { return proto.CompactTextString(m) } -func (*Cursor) ProtoMessage() {} - -func (m *Cursor) GetCursor() uint64 { - if m != nil && m.Cursor != nil { - return *m.Cursor - } - return 0 -} - -func (m *Cursor) GetApp() string { - if m != nil && m.App != nil { - return *m.App - } - return "" -} - -type Error struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *Error) Reset() { *m = Error{} } -func (m *Error) String() string { return proto.CompactTextString(m) } -func (*Error) ProtoMessage() {} - -type Cost struct { - IndexWrites *int32 `protobuf:"varint,1,opt,name=index_writes" json:"index_writes,omitempty"` - IndexWriteBytes *int32 `protobuf:"varint,2,opt,name=index_write_bytes" json:"index_write_bytes,omitempty"` - EntityWrites *int32 `protobuf:"varint,3,opt,name=entity_writes" json:"entity_writes,omitempty"` - EntityWriteBytes *int32 `protobuf:"varint,4,opt,name=entity_write_bytes" json:"entity_write_bytes,omitempty"` - Commitcost *Cost_CommitCost `protobuf:"group,5,opt,name=CommitCost" json:"commitcost,omitempty"` - ApproximateStorageDelta *int32 `protobuf:"varint,8,opt,name=approximate_storage_delta" json:"approximate_storage_delta,omitempty"` - IdSequenceUpdates *int32 `protobuf:"varint,9,opt,name=id_sequence_updates" json:"id_sequence_updates,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Cost) Reset() { *m = Cost{} } -func (m *Cost) String() string { return proto.CompactTextString(m) } -func (*Cost) ProtoMessage() {} - -func (m *Cost) GetIndexWrites() int32 { - if m != nil && m.IndexWrites != nil { - return *m.IndexWrites - } - return 0 -} - -func (m *Cost) GetIndexWriteBytes() int32 { - if m != nil && m.IndexWriteBytes != nil { - return *m.IndexWriteBytes - } - return 0 -} - -func (m *Cost) GetEntityWrites() int32 { - if m != nil && m.EntityWrites != nil { - return *m.EntityWrites - } - return 0 -} - -func (m *Cost) GetEntityWriteBytes() int32 { - if m != nil && m.EntityWriteBytes != nil { - return *m.EntityWriteBytes - } - return 0 -} - -func (m *Cost) GetCommitcost() *Cost_CommitCost { - if m != nil { - return m.Commitcost - } - return nil -} - -func (m *Cost) GetApproximateStorageDelta() int32 { - if m != nil && m.ApproximateStorageDelta != nil { - return *m.ApproximateStorageDelta - } - return 0 -} - -func (m *Cost) GetIdSequenceUpdates() int32 { - if m != nil && m.IdSequenceUpdates != nil { - return *m.IdSequenceUpdates - } - return 0 -} - -type Cost_CommitCost struct { - RequestedEntityPuts *int32 `protobuf:"varint,6,opt,name=requested_entity_puts" json:"requested_entity_puts,omitempty"` - RequestedEntityDeletes *int32 `protobuf:"varint,7,opt,name=requested_entity_deletes" json:"requested_entity_deletes,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Cost_CommitCost) Reset() { *m = Cost_CommitCost{} } -func (m *Cost_CommitCost) String() string { return proto.CompactTextString(m) } -func (*Cost_CommitCost) ProtoMessage() {} - -func (m *Cost_CommitCost) GetRequestedEntityPuts() int32 { - if m != nil && m.RequestedEntityPuts != nil { - return *m.RequestedEntityPuts - } - return 0 -} - -func (m *Cost_CommitCost) GetRequestedEntityDeletes() int32 { - if m != nil && m.RequestedEntityDeletes != nil { - return *m.RequestedEntityDeletes - } - return 0 -} - -type GetRequest struct { - Header *InternalHeader `protobuf:"bytes,6,opt,name=header" json:"header,omitempty"` - Key []*Reference `protobuf:"bytes,1,rep,name=key" json:"key,omitempty"` - Transaction *Transaction `protobuf:"bytes,2,opt,name=transaction" json:"transaction,omitempty"` - FailoverMs *int64 `protobuf:"varint,3,opt,name=failover_ms" json:"failover_ms,omitempty"` - Strong *bool `protobuf:"varint,4,opt,name=strong" json:"strong,omitempty"` - AllowDeferred *bool `protobuf:"varint,5,opt,name=allow_deferred,def=0" json:"allow_deferred,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetRequest) Reset() { *m = GetRequest{} } -func (m *GetRequest) String() string { return proto.CompactTextString(m) } -func (*GetRequest) ProtoMessage() {} - -const Default_GetRequest_AllowDeferred bool = false - -func (m *GetRequest) GetHeader() *InternalHeader { - if m != nil { - return m.Header - } - return nil -} - -func (m *GetRequest) GetKey() []*Reference { - if m != nil { - return m.Key - } - return nil -} - -func (m *GetRequest) GetTransaction() *Transaction { - if m != nil { - return m.Transaction - } - return nil -} - -func (m *GetRequest) GetFailoverMs() int64 { - if m != nil && m.FailoverMs != nil { - return *m.FailoverMs - } - return 0 -} - -func (m *GetRequest) GetStrong() bool { - if m != nil && m.Strong != nil { - return *m.Strong - } - return false -} - -func (m *GetRequest) GetAllowDeferred() bool { - if m != nil && m.AllowDeferred != nil { - return *m.AllowDeferred - } - return Default_GetRequest_AllowDeferred -} - -type GetResponse struct { - Entity []*GetResponse_Entity `protobuf:"group,1,rep,name=Entity" json:"entity,omitempty"` - Deferred []*Reference `protobuf:"bytes,5,rep,name=deferred" json:"deferred,omitempty"` - InOrder *bool `protobuf:"varint,6,opt,name=in_order,def=1" json:"in_order,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetResponse) Reset() { *m = GetResponse{} } -func (m *GetResponse) String() string { return proto.CompactTextString(m) } -func (*GetResponse) ProtoMessage() {} - -const Default_GetResponse_InOrder bool = true - -func (m *GetResponse) GetEntity() []*GetResponse_Entity { - if m != nil { - return m.Entity - } - return nil -} - -func (m *GetResponse) GetDeferred() []*Reference { - if m != nil { - return m.Deferred - } - return nil -} - -func (m *GetResponse) GetInOrder() bool { - if m != nil && m.InOrder != nil { - return *m.InOrder - } - return Default_GetResponse_InOrder -} - -type GetResponse_Entity struct { - Entity *EntityProto `protobuf:"bytes,2,opt,name=entity" json:"entity,omitempty"` - Key *Reference `protobuf:"bytes,4,opt,name=key" json:"key,omitempty"` - Version *int64 `protobuf:"varint,3,opt,name=version" json:"version,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetResponse_Entity) Reset() { *m = GetResponse_Entity{} } -func (m *GetResponse_Entity) String() string { return proto.CompactTextString(m) } -func (*GetResponse_Entity) ProtoMessage() {} - -func (m *GetResponse_Entity) GetEntity() *EntityProto { - if m != nil { - return m.Entity - } - return nil -} - -func (m *GetResponse_Entity) GetKey() *Reference { - if m != nil { - return m.Key - } - return nil -} - -func (m *GetResponse_Entity) GetVersion() int64 { - if m != nil && m.Version != nil { - return *m.Version - } - return 0 -} - -type PutRequest struct { - Header *InternalHeader `protobuf:"bytes,11,opt,name=header" json:"header,omitempty"` - Entity []*EntityProto `protobuf:"bytes,1,rep,name=entity" json:"entity,omitempty"` - Transaction *Transaction `protobuf:"bytes,2,opt,name=transaction" json:"transaction,omitempty"` - CompositeIndex []*CompositeIndex `protobuf:"bytes,3,rep,name=composite_index" json:"composite_index,omitempty"` - Trusted *bool `protobuf:"varint,4,opt,name=trusted,def=0" json:"trusted,omitempty"` - Force *bool `protobuf:"varint,7,opt,name=force,def=0" json:"force,omitempty"` - MarkChanges *bool `protobuf:"varint,8,opt,name=mark_changes,def=0" json:"mark_changes,omitempty"` - Snapshot []*Snapshot `protobuf:"bytes,9,rep,name=snapshot" json:"snapshot,omitempty"` - AutoIdPolicy *PutRequest_AutoIdPolicy `protobuf:"varint,10,opt,name=auto_id_policy,enum=appengine.PutRequest_AutoIdPolicy,def=0" json:"auto_id_policy,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PutRequest) Reset() { *m = PutRequest{} } -func (m *PutRequest) String() string { return proto.CompactTextString(m) } -func (*PutRequest) ProtoMessage() {} - -const Default_PutRequest_Trusted bool = false -const Default_PutRequest_Force bool = false -const Default_PutRequest_MarkChanges bool = false -const Default_PutRequest_AutoIdPolicy PutRequest_AutoIdPolicy = PutRequest_CURRENT - -func (m *PutRequest) GetHeader() *InternalHeader { - if m != nil { - return m.Header - } - return nil -} - -func (m *PutRequest) GetEntity() []*EntityProto { - if m != nil { - return m.Entity - } - return nil -} - -func (m *PutRequest) GetTransaction() *Transaction { - if m != nil { - return m.Transaction - } - return nil -} - -func (m *PutRequest) GetCompositeIndex() []*CompositeIndex { - if m != nil { - return m.CompositeIndex - } - return nil -} - -func (m *PutRequest) GetTrusted() bool { - if m != nil && m.Trusted != nil { - return *m.Trusted - } - return Default_PutRequest_Trusted -} - -func (m *PutRequest) GetForce() bool { - if m != nil && m.Force != nil { - return *m.Force - } - return Default_PutRequest_Force -} - -func (m *PutRequest) GetMarkChanges() bool { - if m != nil && m.MarkChanges != nil { - return *m.MarkChanges - } - return Default_PutRequest_MarkChanges -} - -func (m *PutRequest) GetSnapshot() []*Snapshot { - if m != nil { - return m.Snapshot - } - return nil -} - -func (m *PutRequest) GetAutoIdPolicy() PutRequest_AutoIdPolicy { - if m != nil && m.AutoIdPolicy != nil { - return *m.AutoIdPolicy - } - return Default_PutRequest_AutoIdPolicy -} - -type PutResponse struct { - Key []*Reference `protobuf:"bytes,1,rep,name=key" json:"key,omitempty"` - Cost *Cost `protobuf:"bytes,2,opt,name=cost" json:"cost,omitempty"` - Version []int64 `protobuf:"varint,3,rep,name=version" json:"version,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *PutResponse) Reset() { *m = PutResponse{} } -func (m *PutResponse) String() string { return proto.CompactTextString(m) } -func (*PutResponse) ProtoMessage() {} - -func (m *PutResponse) GetKey() []*Reference { - if m != nil { - return m.Key - } - return nil -} - -func (m *PutResponse) GetCost() *Cost { - if m != nil { - return m.Cost - } - return nil -} - -func (m *PutResponse) GetVersion() []int64 { - if m != nil { - return m.Version - } - return nil -} - -type TouchRequest struct { - Header *InternalHeader `protobuf:"bytes,10,opt,name=header" json:"header,omitempty"` - Key []*Reference `protobuf:"bytes,1,rep,name=key" json:"key,omitempty"` - CompositeIndex []*CompositeIndex `protobuf:"bytes,2,rep,name=composite_index" json:"composite_index,omitempty"` - Force *bool `protobuf:"varint,3,opt,name=force,def=0" json:"force,omitempty"` - Snapshot []*Snapshot `protobuf:"bytes,9,rep,name=snapshot" json:"snapshot,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *TouchRequest) Reset() { *m = TouchRequest{} } -func (m *TouchRequest) String() string { return proto.CompactTextString(m) } -func (*TouchRequest) ProtoMessage() {} - -const Default_TouchRequest_Force bool = false - -func (m *TouchRequest) GetHeader() *InternalHeader { - if m != nil { - return m.Header - } - return nil -} - -func (m *TouchRequest) GetKey() []*Reference { - if m != nil { - return m.Key - } - return nil -} - -func (m *TouchRequest) GetCompositeIndex() []*CompositeIndex { - if m != nil { - return m.CompositeIndex - } - return nil -} - -func (m *TouchRequest) GetForce() bool { - if m != nil && m.Force != nil { - return *m.Force - } - return Default_TouchRequest_Force -} - -func (m *TouchRequest) GetSnapshot() []*Snapshot { - if m != nil { - return m.Snapshot - } - return nil -} - -type TouchResponse struct { - Cost *Cost `protobuf:"bytes,1,opt,name=cost" json:"cost,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *TouchResponse) Reset() { *m = TouchResponse{} } -func (m *TouchResponse) String() string { return proto.CompactTextString(m) } -func (*TouchResponse) ProtoMessage() {} - -func (m *TouchResponse) GetCost() *Cost { - if m != nil { - return m.Cost - } - return nil -} - -type DeleteRequest struct { - Header *InternalHeader `protobuf:"bytes,10,opt,name=header" json:"header,omitempty"` - Key []*Reference `protobuf:"bytes,6,rep,name=key" json:"key,omitempty"` - Transaction *Transaction `protobuf:"bytes,5,opt,name=transaction" json:"transaction,omitempty"` - Trusted *bool `protobuf:"varint,4,opt,name=trusted,def=0" json:"trusted,omitempty"` - Force *bool `protobuf:"varint,7,opt,name=force,def=0" json:"force,omitempty"` - MarkChanges *bool `protobuf:"varint,8,opt,name=mark_changes,def=0" json:"mark_changes,omitempty"` - Snapshot []*Snapshot `protobuf:"bytes,9,rep,name=snapshot" json:"snapshot,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *DeleteRequest) Reset() { *m = DeleteRequest{} } -func (m *DeleteRequest) String() string { return proto.CompactTextString(m) } -func (*DeleteRequest) ProtoMessage() {} - -const Default_DeleteRequest_Trusted bool = false -const Default_DeleteRequest_Force bool = false -const Default_DeleteRequest_MarkChanges bool = false - -func (m *DeleteRequest) GetHeader() *InternalHeader { - if m != nil { - return m.Header - } - return nil -} - -func (m *DeleteRequest) GetKey() []*Reference { - if m != nil { - return m.Key - } - return nil -} - -func (m *DeleteRequest) GetTransaction() *Transaction { - if m != nil { - return m.Transaction - } - return nil -} - -func (m *DeleteRequest) GetTrusted() bool { - if m != nil && m.Trusted != nil { - return *m.Trusted - } - return Default_DeleteRequest_Trusted -} - -func (m *DeleteRequest) GetForce() bool { - if m != nil && m.Force != nil { - return *m.Force - } - return Default_DeleteRequest_Force -} - -func (m *DeleteRequest) GetMarkChanges() bool { - if m != nil && m.MarkChanges != nil { - return *m.MarkChanges - } - return Default_DeleteRequest_MarkChanges -} - -func (m *DeleteRequest) GetSnapshot() []*Snapshot { - if m != nil { - return m.Snapshot - } - return nil -} - -type DeleteResponse struct { - Cost *Cost `protobuf:"bytes,1,opt,name=cost" json:"cost,omitempty"` - Version []int64 `protobuf:"varint,3,rep,name=version" json:"version,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *DeleteResponse) Reset() { *m = DeleteResponse{} } -func (m *DeleteResponse) String() string { return proto.CompactTextString(m) } -func (*DeleteResponse) ProtoMessage() {} - -func (m *DeleteResponse) GetCost() *Cost { - if m != nil { - return m.Cost - } - return nil -} - -func (m *DeleteResponse) GetVersion() []int64 { - if m != nil { - return m.Version - } - return nil -} - -type NextRequest struct { - Header *InternalHeader `protobuf:"bytes,5,opt,name=header" json:"header,omitempty"` - Cursor *Cursor `protobuf:"bytes,1,req,name=cursor" json:"cursor,omitempty"` - Count *int32 `protobuf:"varint,2,opt,name=count" json:"count,omitempty"` - Offset *int32 `protobuf:"varint,4,opt,name=offset,def=0" json:"offset,omitempty"` - Compile *bool `protobuf:"varint,3,opt,name=compile,def=0" json:"compile,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *NextRequest) Reset() { *m = NextRequest{} } -func (m *NextRequest) String() string { return proto.CompactTextString(m) } -func (*NextRequest) ProtoMessage() {} - -const Default_NextRequest_Offset int32 = 0 -const Default_NextRequest_Compile bool = false - -func (m *NextRequest) GetHeader() *InternalHeader { - if m != nil { - return m.Header - } - return nil -} - -func (m *NextRequest) GetCursor() *Cursor { - if m != nil { - return m.Cursor - } - return nil -} - -func (m *NextRequest) GetCount() int32 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -func (m *NextRequest) GetOffset() int32 { - if m != nil && m.Offset != nil { - return *m.Offset - } - return Default_NextRequest_Offset -} - -func (m *NextRequest) GetCompile() bool { - if m != nil && m.Compile != nil { - return *m.Compile - } - return Default_NextRequest_Compile -} - -type QueryResult struct { - Cursor *Cursor `protobuf:"bytes,1,opt,name=cursor" json:"cursor,omitempty"` - Result []*EntityProto `protobuf:"bytes,2,rep,name=result" json:"result,omitempty"` - SkippedResults *int32 `protobuf:"varint,7,opt,name=skipped_results" json:"skipped_results,omitempty"` - MoreResults *bool `protobuf:"varint,3,req,name=more_results" json:"more_results,omitempty"` - KeysOnly *bool `protobuf:"varint,4,opt,name=keys_only" json:"keys_only,omitempty"` - IndexOnly *bool `protobuf:"varint,9,opt,name=index_only" json:"index_only,omitempty"` - SmallOps *bool `protobuf:"varint,10,opt,name=small_ops" json:"small_ops,omitempty"` - CompiledQuery *CompiledQuery `protobuf:"bytes,5,opt,name=compiled_query" json:"compiled_query,omitempty"` - CompiledCursor *CompiledCursor `protobuf:"bytes,6,opt,name=compiled_cursor" json:"compiled_cursor,omitempty"` - Index []*CompositeIndex `protobuf:"bytes,8,rep,name=index" json:"index,omitempty"` - Version []int64 `protobuf:"varint,11,rep,name=version" json:"version,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *QueryResult) Reset() { *m = QueryResult{} } -func (m *QueryResult) String() string { return proto.CompactTextString(m) } -func (*QueryResult) ProtoMessage() {} - -func (m *QueryResult) GetCursor() *Cursor { - if m != nil { - return m.Cursor - } - return nil -} - -func (m *QueryResult) GetResult() []*EntityProto { - if m != nil { - return m.Result - } - return nil -} - -func (m *QueryResult) GetSkippedResults() int32 { - if m != nil && m.SkippedResults != nil { - return *m.SkippedResults - } - return 0 -} - -func (m *QueryResult) GetMoreResults() bool { - if m != nil && m.MoreResults != nil { - return *m.MoreResults - } - return false -} - -func (m *QueryResult) GetKeysOnly() bool { - if m != nil && m.KeysOnly != nil { - return *m.KeysOnly - } - return false -} - -func (m *QueryResult) GetIndexOnly() bool { - if m != nil && m.IndexOnly != nil { - return *m.IndexOnly - } - return false -} - -func (m *QueryResult) GetSmallOps() bool { - if m != nil && m.SmallOps != nil { - return *m.SmallOps - } - return false -} - -func (m *QueryResult) GetCompiledQuery() *CompiledQuery { - if m != nil { - return m.CompiledQuery - } - return nil -} - -func (m *QueryResult) GetCompiledCursor() *CompiledCursor { - if m != nil { - return m.CompiledCursor - } - return nil -} - -func (m *QueryResult) GetIndex() []*CompositeIndex { - if m != nil { - return m.Index - } - return nil -} - -func (m *QueryResult) GetVersion() []int64 { - if m != nil { - return m.Version - } - return nil -} - -type AllocateIdsRequest struct { - Header *InternalHeader `protobuf:"bytes,4,opt,name=header" json:"header,omitempty"` - ModelKey *Reference `protobuf:"bytes,1,opt,name=model_key" json:"model_key,omitempty"` - Size *int64 `protobuf:"varint,2,opt,name=size" json:"size,omitempty"` - Max *int64 `protobuf:"varint,3,opt,name=max" json:"max,omitempty"` - Reserve []*Reference `protobuf:"bytes,5,rep,name=reserve" json:"reserve,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *AllocateIdsRequest) Reset() { *m = AllocateIdsRequest{} } -func (m *AllocateIdsRequest) String() string { return proto.CompactTextString(m) } -func (*AllocateIdsRequest) ProtoMessage() {} - -func (m *AllocateIdsRequest) GetHeader() *InternalHeader { - if m != nil { - return m.Header - } - return nil -} - -func (m *AllocateIdsRequest) GetModelKey() *Reference { - if m != nil { - return m.ModelKey - } - return nil -} - -func (m *AllocateIdsRequest) GetSize() int64 { - if m != nil && m.Size != nil { - return *m.Size - } - return 0 -} - -func (m *AllocateIdsRequest) GetMax() int64 { - if m != nil && m.Max != nil { - return *m.Max - } - return 0 -} - -func (m *AllocateIdsRequest) GetReserve() []*Reference { - if m != nil { - return m.Reserve - } - return nil -} - -type AllocateIdsResponse struct { - Start *int64 `protobuf:"varint,1,req,name=start" json:"start,omitempty"` - End *int64 `protobuf:"varint,2,req,name=end" json:"end,omitempty"` - Cost *Cost `protobuf:"bytes,3,opt,name=cost" json:"cost,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *AllocateIdsResponse) Reset() { *m = AllocateIdsResponse{} } -func (m *AllocateIdsResponse) String() string { return proto.CompactTextString(m) } -func (*AllocateIdsResponse) ProtoMessage() {} - -func (m *AllocateIdsResponse) GetStart() int64 { - if m != nil && m.Start != nil { - return *m.Start - } - return 0 -} - -func (m *AllocateIdsResponse) GetEnd() int64 { - if m != nil && m.End != nil { - return *m.End - } - return 0 -} - -func (m *AllocateIdsResponse) GetCost() *Cost { - if m != nil { - return m.Cost - } - return nil -} - -type CompositeIndices struct { - Index []*CompositeIndex `protobuf:"bytes,1,rep,name=index" json:"index,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CompositeIndices) Reset() { *m = CompositeIndices{} } -func (m *CompositeIndices) String() string { return proto.CompactTextString(m) } -func (*CompositeIndices) ProtoMessage() {} - -func (m *CompositeIndices) GetIndex() []*CompositeIndex { - if m != nil { - return m.Index - } - return nil -} - -type AddActionsRequest struct { - Header *InternalHeader `protobuf:"bytes,3,opt,name=header" json:"header,omitempty"` - Transaction *Transaction `protobuf:"bytes,1,req,name=transaction" json:"transaction,omitempty"` - Action []*Action `protobuf:"bytes,2,rep,name=action" json:"action,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *AddActionsRequest) Reset() { *m = AddActionsRequest{} } -func (m *AddActionsRequest) String() string { return proto.CompactTextString(m) } -func (*AddActionsRequest) ProtoMessage() {} - -func (m *AddActionsRequest) GetHeader() *InternalHeader { - if m != nil { - return m.Header - } - return nil -} - -func (m *AddActionsRequest) GetTransaction() *Transaction { - if m != nil { - return m.Transaction - } - return nil -} - -func (m *AddActionsRequest) GetAction() []*Action { - if m != nil { - return m.Action - } - return nil -} - -type AddActionsResponse struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *AddActionsResponse) Reset() { *m = AddActionsResponse{} } -func (m *AddActionsResponse) String() string { return proto.CompactTextString(m) } -func (*AddActionsResponse) ProtoMessage() {} - -type BeginTransactionRequest struct { - Header *InternalHeader `protobuf:"bytes,3,opt,name=header" json:"header,omitempty"` - App *string `protobuf:"bytes,1,req,name=app" json:"app,omitempty"` - AllowMultipleEg *bool `protobuf:"varint,2,opt,name=allow_multiple_eg,def=0" json:"allow_multiple_eg,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *BeginTransactionRequest) Reset() { *m = BeginTransactionRequest{} } -func (m *BeginTransactionRequest) String() string { return proto.CompactTextString(m) } -func (*BeginTransactionRequest) ProtoMessage() {} - -const Default_BeginTransactionRequest_AllowMultipleEg bool = false - -func (m *BeginTransactionRequest) GetHeader() *InternalHeader { - if m != nil { - return m.Header - } - return nil -} - -func (m *BeginTransactionRequest) GetApp() string { - if m != nil && m.App != nil { - return *m.App - } - return "" -} - -func (m *BeginTransactionRequest) GetAllowMultipleEg() bool { - if m != nil && m.AllowMultipleEg != nil { - return *m.AllowMultipleEg - } - return Default_BeginTransactionRequest_AllowMultipleEg -} - -type CommitResponse struct { - Cost *Cost `protobuf:"bytes,1,opt,name=cost" json:"cost,omitempty"` - Version []*CommitResponse_Version `protobuf:"group,3,rep,name=Version" json:"version,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CommitResponse) Reset() { *m = CommitResponse{} } -func (m *CommitResponse) String() string { return proto.CompactTextString(m) } -func (*CommitResponse) ProtoMessage() {} - -func (m *CommitResponse) GetCost() *Cost { - if m != nil { - return m.Cost - } - return nil -} - -func (m *CommitResponse) GetVersion() []*CommitResponse_Version { - if m != nil { - return m.Version - } - return nil -} - -type CommitResponse_Version struct { - RootEntityKey *Reference `protobuf:"bytes,4,req,name=root_entity_key" json:"root_entity_key,omitempty"` - Version *int64 `protobuf:"varint,5,req,name=version" json:"version,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *CommitResponse_Version) Reset() { *m = CommitResponse_Version{} } -func (m *CommitResponse_Version) String() string { return proto.CompactTextString(m) } -func (*CommitResponse_Version) ProtoMessage() {} - -func (m *CommitResponse_Version) GetRootEntityKey() *Reference { - if m != nil { - return m.RootEntityKey - } - return nil -} - -func (m *CommitResponse_Version) GetVersion() int64 { - if m != nil && m.Version != nil { - return *m.Version - } - return 0 -} - -func init() { -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/datastore/datastore_v3.proto b/Godeps/_workspace/src/google.golang.org/appengine/internal/datastore/datastore_v3.proto deleted file mode 100644 index e76f126ff..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/datastore/datastore_v3.proto +++ /dev/null @@ -1,541 +0,0 @@ -syntax = "proto2"; -option go_package = "datastore"; - -package appengine; - -message Action{} - -message PropertyValue { - optional int64 int64Value = 1; - optional bool booleanValue = 2; - optional string stringValue = 3; - optional double doubleValue = 4; - - optional group PointValue = 5 { - required double x = 6; - required double y = 7; - } - - optional group UserValue = 8 { - required string email = 9; - required string auth_domain = 10; - optional string nickname = 11; - optional string federated_identity = 21; - optional string federated_provider = 22; - } - - optional group ReferenceValue = 12 { - required string app = 13; - optional string name_space = 20; - repeated group PathElement = 14 { - required string type = 15; - optional int64 id = 16; - optional string name = 17; - } - } -} - -message Property { - enum Meaning { - NO_MEANING = 0; - BLOB = 14; - TEXT = 15; - BYTESTRING = 16; - - ATOM_CATEGORY = 1; - ATOM_LINK = 2; - ATOM_TITLE = 3; - ATOM_CONTENT = 4; - ATOM_SUMMARY = 5; - ATOM_AUTHOR = 6; - - GD_WHEN = 7; - GD_EMAIL = 8; - GEORSS_POINT = 9; - GD_IM = 10; - - GD_PHONENUMBER = 11; - GD_POSTALADDRESS = 12; - - GD_RATING = 13; - - BLOBKEY = 17; - ENTITY_PROTO = 19; - - INDEX_VALUE = 18; - }; - - optional Meaning meaning = 1 [default = NO_MEANING]; - optional string meaning_uri = 2; - - required string name = 3; - - required PropertyValue value = 5; - - required bool multiple = 4; - - optional bool searchable = 6 [default=false]; - - enum FtsTokenizationOption { - HTML = 1; - ATOM = 2; - } - - optional FtsTokenizationOption fts_tokenization_option = 8; - - optional string locale = 9 [default = "en"]; -} - -message Path { - repeated group Element = 1 { - required string type = 2; - optional int64 id = 3; - optional string name = 4; - } -} - -message Reference { - required string app = 13; - optional string name_space = 20; - required Path path = 14; -} - -message User { - required string email = 1; - required string auth_domain = 2; - optional string nickname = 3; - optional string federated_identity = 6; - optional string federated_provider = 7; -} - -message EntityProto { - required Reference key = 13; - required Path entity_group = 16; - optional User owner = 17; - - enum Kind { - GD_CONTACT = 1; - GD_EVENT = 2; - GD_MESSAGE = 3; - } - optional Kind kind = 4; - optional string kind_uri = 5; - - repeated Property property = 14; - repeated Property raw_property = 15; - - optional int32 rank = 18; -} - -message CompositeProperty { - required int64 index_id = 1; - repeated string value = 2; -} - -message Index { - required string entity_type = 1; - required bool ancestor = 5; - repeated group Property = 2 { - required string name = 3; - enum Direction { - ASCENDING = 1; - DESCENDING = 2; - } - optional Direction direction = 4 [default = ASCENDING]; - } -} - -message CompositeIndex { - required string app_id = 1; - required int64 id = 2; - required Index definition = 3; - - enum State { - WRITE_ONLY = 1; - READ_WRITE = 2; - DELETED = 3; - ERROR = 4; - } - required State state = 4; - - optional bool only_use_if_required = 6 [default = false]; -} - -message IndexPostfix { - message IndexValue { - required string property_name = 1; - required PropertyValue value = 2; - } - - repeated IndexValue index_value = 1; - - optional Reference key = 2; - - optional bool before = 3 [default=true]; -} - -message IndexPosition { - optional string key = 1; - - optional bool before = 2 [default=true]; -} - -message Snapshot { - enum Status { - INACTIVE = 0; - ACTIVE = 1; - } - - required int64 ts = 1; -} - -message InternalHeader { - optional string qos = 1; -} - -message Transaction { - optional InternalHeader header = 4; - required fixed64 handle = 1; - required string app = 2; - optional bool mark_changes = 3 [default = false]; -} - -message Query { - optional InternalHeader header = 39; - - required string app = 1; - optional string name_space = 29; - - optional string kind = 3; - optional Reference ancestor = 17; - - repeated group Filter = 4 { - enum Operator { - LESS_THAN = 1; - LESS_THAN_OR_EQUAL = 2; - GREATER_THAN = 3; - GREATER_THAN_OR_EQUAL = 4; - EQUAL = 5; - IN = 6; - EXISTS = 7; - } - - required Operator op = 6; - repeated Property property = 14; - } - - optional string search_query = 8; - - repeated group Order = 9 { - enum Direction { - ASCENDING = 1; - DESCENDING = 2; - } - - required string property = 10; - optional Direction direction = 11 [default = ASCENDING]; - } - - enum Hint { - ORDER_FIRST = 1; - ANCESTOR_FIRST = 2; - FILTER_FIRST = 3; - } - optional Hint hint = 18; - - optional int32 count = 23; - - optional int32 offset = 12 [default = 0]; - - optional int32 limit = 16; - - optional CompiledCursor compiled_cursor = 30; - optional CompiledCursor end_compiled_cursor = 31; - - repeated CompositeIndex composite_index = 19; - - optional bool require_perfect_plan = 20 [default = false]; - - optional bool keys_only = 21 [default = false]; - - optional Transaction transaction = 22; - - optional bool compile = 25 [default = false]; - - optional int64 failover_ms = 26; - - optional bool strong = 32; - - repeated string property_name = 33; - - repeated string group_by_property_name = 34; - - optional bool distinct = 24; - - optional int64 min_safe_time_seconds = 35; - - repeated string safe_replica_name = 36; - - optional bool persist_offset = 37 [default=false]; -} - -message CompiledQuery { - required group PrimaryScan = 1 { - optional string index_name = 2; - - optional string start_key = 3; - optional bool start_inclusive = 4; - optional string end_key = 5; - optional bool end_inclusive = 6; - - repeated string start_postfix_value = 22; - repeated string end_postfix_value = 23; - - optional int64 end_unapplied_log_timestamp_us = 19; - } - - repeated group MergeJoinScan = 7 { - required string index_name = 8; - - repeated string prefix_value = 9; - - optional bool value_prefix = 20 [default=false]; - } - - optional Index index_def = 21; - - optional int32 offset = 10 [default = 0]; - - optional int32 limit = 11; - - required bool keys_only = 12; - - repeated string property_name = 24; - - optional int32 distinct_infix_size = 25; - - optional group EntityFilter = 13 { - optional bool distinct = 14 [default=false]; - - optional string kind = 17; - optional Reference ancestor = 18; - } -} - -message CompiledCursor { - optional group Position = 2 { - optional string start_key = 27; - - repeated group IndexValue = 29 { - optional string property = 30; - required PropertyValue value = 31; - } - - optional Reference key = 32; - - optional bool start_inclusive = 28 [default=true]; - } -} - -message Cursor { - required fixed64 cursor = 1; - - optional string app = 2; -} - -message Error { - enum ErrorCode { - BAD_REQUEST = 1; - CONCURRENT_TRANSACTION = 2; - INTERNAL_ERROR = 3; - NEED_INDEX = 4; - TIMEOUT = 5; - PERMISSION_DENIED = 6; - BIGTABLE_ERROR = 7; - COMMITTED_BUT_STILL_APPLYING = 8; - CAPABILITY_DISABLED = 9; - TRY_ALTERNATE_BACKEND = 10; - SAFE_TIME_TOO_OLD = 11; - } -} - -message Cost { - optional int32 index_writes = 1; - optional int32 index_write_bytes = 2; - optional int32 entity_writes = 3; - optional int32 entity_write_bytes = 4; - optional group CommitCost = 5 { - optional int32 requested_entity_puts = 6; - optional int32 requested_entity_deletes = 7; - }; - optional int32 approximate_storage_delta = 8; - optional int32 id_sequence_updates = 9; -} - -message GetRequest { - optional InternalHeader header = 6; - - repeated Reference key = 1; - optional Transaction transaction = 2; - - optional int64 failover_ms = 3; - - optional bool strong = 4; - - optional bool allow_deferred = 5 [default=false]; -} - -message GetResponse { - repeated group Entity = 1 { - optional EntityProto entity = 2; - optional Reference key = 4; - - optional int64 version = 3; - } - - repeated Reference deferred = 5; - - optional bool in_order = 6 [default=true]; -} - -message PutRequest { - optional InternalHeader header = 11; - - repeated EntityProto entity = 1; - optional Transaction transaction = 2; - repeated CompositeIndex composite_index = 3; - - optional bool trusted = 4 [default = false]; - - optional bool force = 7 [default = false]; - - optional bool mark_changes = 8 [default = false]; - repeated Snapshot snapshot = 9; - - enum AutoIdPolicy { - CURRENT = 0; - SEQUENTIAL = 1; - } - optional AutoIdPolicy auto_id_policy = 10 [default = CURRENT]; -} - -message PutResponse { - repeated Reference key = 1; - optional Cost cost = 2; - repeated int64 version = 3; -} - -message TouchRequest { - optional InternalHeader header = 10; - - repeated Reference key = 1; - repeated CompositeIndex composite_index = 2; - optional bool force = 3 [default = false]; - repeated Snapshot snapshot = 9; -} - -message TouchResponse { - optional Cost cost = 1; -} - -message DeleteRequest { - optional InternalHeader header = 10; - - repeated Reference key = 6; - optional Transaction transaction = 5; - - optional bool trusted = 4 [default = false]; - - optional bool force = 7 [default = false]; - - optional bool mark_changes = 8 [default = false]; - repeated Snapshot snapshot = 9; -} - -message DeleteResponse { - optional Cost cost = 1; - repeated int64 version = 3; -} - -message NextRequest { - optional InternalHeader header = 5; - - required Cursor cursor = 1; - optional int32 count = 2; - - optional int32 offset = 4 [default = 0]; - - optional bool compile = 3 [default = false]; -} - -message QueryResult { - optional Cursor cursor = 1; - - repeated EntityProto result = 2; - - optional int32 skipped_results = 7; - - required bool more_results = 3; - - optional bool keys_only = 4; - - optional bool index_only = 9; - - optional bool small_ops = 10; - - optional CompiledQuery compiled_query = 5; - - optional CompiledCursor compiled_cursor = 6; - - repeated CompositeIndex index = 8; - - repeated int64 version = 11; -} - -message AllocateIdsRequest { - optional InternalHeader header = 4; - - optional Reference model_key = 1; - - optional int64 size = 2; - - optional int64 max = 3; - - repeated Reference reserve = 5; -} - -message AllocateIdsResponse { - required int64 start = 1; - required int64 end = 2; - optional Cost cost = 3; -} - -message CompositeIndices { - repeated CompositeIndex index = 1; -} - -message AddActionsRequest { - optional InternalHeader header = 3; - - required Transaction transaction = 1; - repeated Action action = 2; -} - -message AddActionsResponse { -} - -message BeginTransactionRequest { - optional InternalHeader header = 3; - - required string app = 1; - optional bool allow_multiple_eg = 2 [default = false]; -} - -message CommitResponse { - optional Cost cost = 1; - - repeated group Version = 3 { - required Reference root_entity_key = 4; - required int64 version = 5; - } -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/identity.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/identity.go deleted file mode 100644 index d538701ab..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/identity.go +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package internal - -import netcontext "golang.org/x/net/context" - -// These functions are implementations of the wrapper functions -// in ../appengine/identity.go. See that file for commentary. - -func AppID(c netcontext.Context) string { - return appID(FullyQualifiedAppID(c)) -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/identity_classic.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/identity_classic.go deleted file mode 100644 index e6b9227c5..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/identity_classic.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2015 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build appengine - -package internal - -import ( - "appengine" - - netcontext "golang.org/x/net/context" -) - -func DefaultVersionHostname(ctx netcontext.Context) string { - return appengine.DefaultVersionHostname(fromContext(ctx)) -} - -func RequestID(ctx netcontext.Context) string { return appengine.RequestID(fromContext(ctx)) } -func Datacenter(_ netcontext.Context) string { return appengine.Datacenter() } -func ServerSoftware() string { return appengine.ServerSoftware() } -func ModuleName(ctx netcontext.Context) string { return appengine.ModuleName(fromContext(ctx)) } -func VersionID(ctx netcontext.Context) string { return appengine.VersionID(fromContext(ctx)) } -func InstanceID() string { return appengine.InstanceID() } -func IsDevAppServer() bool { return appengine.IsDevAppServer() } - -func fullyQualifiedAppID(ctx netcontext.Context) string { return fromContext(ctx).FullyQualifiedAppID() } diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/identity_vm.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/identity_vm.go deleted file mode 100644 index ebe68b785..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/identity_vm.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// +build !appengine - -package internal - -import ( - "net/http" - "os" - - netcontext "golang.org/x/net/context" -) - -// These functions are implementations of the wrapper functions -// in ../appengine/identity.go. See that file for commentary. - -const ( - hDefaultVersionHostname = "X-AppEngine-Default-Version-Hostname" - hRequestLogId = "X-AppEngine-Request-Log-Id" - hDatacenter = "X-AppEngine-Datacenter" -) - -func ctxHeaders(ctx netcontext.Context) http.Header { - return fromContext(ctx).Request().Header -} - -func DefaultVersionHostname(ctx netcontext.Context) string { - return ctxHeaders(ctx).Get(hDefaultVersionHostname) -} - -func RequestID(ctx netcontext.Context) string { - return ctxHeaders(ctx).Get(hRequestLogId) -} - -func Datacenter(ctx netcontext.Context) string { - return ctxHeaders(ctx).Get(hDatacenter) -} - -func ServerSoftware() string { - // TODO(dsymonds): Remove fallback when we've verified this. - if s := os.Getenv("SERVER_SOFTWARE"); s != "" { - return s - } - return "Google App Engine/1.x.x" -} - -// TODO(dsymonds): Remove the metadata fetches. - -func ModuleName(_ netcontext.Context) string { - if s := os.Getenv("GAE_MODULE_NAME"); s != "" { - return s - } - return string(mustGetMetadata("instance/attributes/gae_backend_name")) -} - -func VersionID(_ netcontext.Context) string { - if s1, s2 := os.Getenv("GAE_MODULE_VERSION"), os.Getenv("GAE_MINOR_VERSION"); s1 != "" && s2 != "" { - return s1 + "." + s2 - } - return string(mustGetMetadata("instance/attributes/gae_backend_version")) + "." + string(mustGetMetadata("instance/attributes/gae_backend_minor_version")) -} - -func InstanceID() string { - if s := os.Getenv("GAE_MODULE_INSTANCE"); s != "" { - return s - } - return string(mustGetMetadata("instance/attributes/gae_backend_instance")) -} - -func partitionlessAppID() string { - // gae_project has everything except the partition prefix. - appID := os.Getenv("GAE_LONG_APP_ID") - if appID == "" { - appID = string(mustGetMetadata("instance/attributes/gae_project")) - } - return appID -} - -func fullyQualifiedAppID(_ netcontext.Context) string { - appID := partitionlessAppID() - - part := os.Getenv("GAE_PARTITION") - if part == "" { - part = string(mustGetMetadata("instance/attributes/gae_partition")) - } - - if part != "" { - appID = part + "~" + appID - } - return appID -} - -func IsDevAppServer() bool { - return os.Getenv("RUN_WITH_DEVAPPSERVER") != "" -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/internal.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/internal.go deleted file mode 100644 index 66e8d7686..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/internal.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2011 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -// Package internal provides support for package appengine. -// -// Programs should not use this package directly. Its API is not stable. -// Use packages appengine and appengine/* instead. -package internal - -import ( - "fmt" - "io" - "log" - "net/http" - "net/url" - "os" - - "github.com/golang/protobuf/proto" - - remotepb "google.golang.org/appengine/internal/remote_api" -) - -// errorCodeMaps is a map of service name to the error code map for the service. -var errorCodeMaps = make(map[string]map[int32]string) - -// RegisterErrorCodeMap is called from API implementations to register their -// error code map. This should only be called from init functions. -func RegisterErrorCodeMap(service string, m map[int32]string) { - errorCodeMaps[service] = m -} - -type timeoutCodeKey struct { - service string - code int32 -} - -// timeoutCodes is the set of service+code pairs that represent timeouts. -var timeoutCodes = make(map[timeoutCodeKey]bool) - -func RegisterTimeoutErrorCode(service string, code int32) { - timeoutCodes[timeoutCodeKey{service, code}] = true -} - -// APIError is the type returned by appengine.Context's Call method -// when an API call fails in an API-specific way. This may be, for instance, -// a taskqueue API call failing with TaskQueueServiceError::UNKNOWN_QUEUE. -type APIError struct { - Service string - Detail string - Code int32 // API-specific error code -} - -func (e *APIError) Error() string { - if e.Code == 0 { - if e.Detail == "" { - return "APIError " - } - return e.Detail - } - s := fmt.Sprintf("API error %d", e.Code) - if m, ok := errorCodeMaps[e.Service]; ok { - s += " (" + e.Service + ": " + m[e.Code] + ")" - } else { - // Shouldn't happen, but provide a bit more detail if it does. - s = e.Service + " " + s - } - if e.Detail != "" { - s += ": " + e.Detail - } - return s -} - -func (e *APIError) IsTimeout() bool { - return timeoutCodes[timeoutCodeKey{e.Service, e.Code}] -} - -// CallError is the type returned by appengine.Context's Call method when an -// API call fails in a generic way, such as RpcError::CAPABILITY_DISABLED. -type CallError struct { - Detail string - Code int32 - // TODO: Remove this if we get a distinguishable error code. - Timeout bool -} - -func (e *CallError) Error() string { - var msg string - switch remotepb.RpcError_ErrorCode(e.Code) { - case remotepb.RpcError_UNKNOWN: - return e.Detail - case remotepb.RpcError_OVER_QUOTA: - msg = "Over quota" - case remotepb.RpcError_CAPABILITY_DISABLED: - msg = "Capability disabled" - case remotepb.RpcError_CANCELLED: - msg = "Canceled" - default: - msg = fmt.Sprintf("Call error %d", e.Code) - } - s := msg + ": " + e.Detail - if e.Timeout { - s += " (timeout)" - } - return s -} - -func (e *CallError) IsTimeout() bool { - return e.Timeout -} - -func Main() { - installHealthChecker(http.DefaultServeMux) - - port := "8080" - if s := os.Getenv("PORT"); s != "" { - port = s - } - - if err := http.ListenAndServe(":"+port, http.HandlerFunc(handleHTTP)); err != nil { - log.Fatalf("http.ListenAndServe: %v", err) - } -} - -func installHealthChecker(mux *http.ServeMux) { - // If no health check handler has been installed by this point, add a trivial one. - const healthPath = "/_ah/health" - hreq := &http.Request{ - Method: "GET", - URL: &url.URL{ - Path: healthPath, - }, - } - if _, pat := mux.Handler(hreq); pat != healthPath { - mux.HandleFunc(healthPath, func(w http.ResponseWriter, r *http.Request) { - io.WriteString(w, "ok") - }) - } -} - -// NamespaceMods is a map from API service to a function that will mutate an RPC request to attach a namespace. -// The function should be prepared to be called on the same message more than once; it should only modify the -// RPC request the first time. -var NamespaceMods = make(map[string]func(m proto.Message, namespace string)) diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/log/log_service.pb.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/log/log_service.pb.go deleted file mode 100644 index 20c595be3..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/log/log_service.pb.go +++ /dev/null @@ -1,899 +0,0 @@ -// Code generated by protoc-gen-go. -// source: google.golang.org/appengine/internal/log/log_service.proto -// DO NOT EDIT! - -/* -Package log is a generated protocol buffer package. - -It is generated from these files: - google.golang.org/appengine/internal/log/log_service.proto - -It has these top-level messages: - LogServiceError - UserAppLogLine - UserAppLogGroup - FlushRequest - SetStatusRequest - LogOffset - LogLine - RequestLog - LogModuleVersion - LogReadRequest - LogReadResponse - LogUsageRecord - LogUsageRequest - LogUsageResponse -*/ -package log - -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 - -type LogServiceError_ErrorCode int32 - -const ( - LogServiceError_OK LogServiceError_ErrorCode = 0 - LogServiceError_INVALID_REQUEST LogServiceError_ErrorCode = 1 - LogServiceError_STORAGE_ERROR LogServiceError_ErrorCode = 2 -) - -var LogServiceError_ErrorCode_name = map[int32]string{ - 0: "OK", - 1: "INVALID_REQUEST", - 2: "STORAGE_ERROR", -} -var LogServiceError_ErrorCode_value = map[string]int32{ - "OK": 0, - "INVALID_REQUEST": 1, - "STORAGE_ERROR": 2, -} - -func (x LogServiceError_ErrorCode) Enum() *LogServiceError_ErrorCode { - p := new(LogServiceError_ErrorCode) - *p = x - return p -} -func (x LogServiceError_ErrorCode) String() string { - return proto.EnumName(LogServiceError_ErrorCode_name, int32(x)) -} -func (x *LogServiceError_ErrorCode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(LogServiceError_ErrorCode_value, data, "LogServiceError_ErrorCode") - if err != nil { - return err - } - *x = LogServiceError_ErrorCode(value) - return nil -} - -type LogServiceError struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *LogServiceError) Reset() { *m = LogServiceError{} } -func (m *LogServiceError) String() string { return proto.CompactTextString(m) } -func (*LogServiceError) ProtoMessage() {} - -type UserAppLogLine struct { - TimestampUsec *int64 `protobuf:"varint,1,req,name=timestamp_usec" json:"timestamp_usec,omitempty"` - Level *int64 `protobuf:"varint,2,req,name=level" json:"level,omitempty"` - Message *string `protobuf:"bytes,3,req,name=message" json:"message,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *UserAppLogLine) Reset() { *m = UserAppLogLine{} } -func (m *UserAppLogLine) String() string { return proto.CompactTextString(m) } -func (*UserAppLogLine) ProtoMessage() {} - -func (m *UserAppLogLine) GetTimestampUsec() int64 { - if m != nil && m.TimestampUsec != nil { - return *m.TimestampUsec - } - return 0 -} - -func (m *UserAppLogLine) GetLevel() int64 { - if m != nil && m.Level != nil { - return *m.Level - } - return 0 -} - -func (m *UserAppLogLine) GetMessage() string { - if m != nil && m.Message != nil { - return *m.Message - } - return "" -} - -type UserAppLogGroup struct { - LogLine []*UserAppLogLine `protobuf:"bytes,2,rep,name=log_line" json:"log_line,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *UserAppLogGroup) Reset() { *m = UserAppLogGroup{} } -func (m *UserAppLogGroup) String() string { return proto.CompactTextString(m) } -func (*UserAppLogGroup) ProtoMessage() {} - -func (m *UserAppLogGroup) GetLogLine() []*UserAppLogLine { - if m != nil { - return m.LogLine - } - return nil -} - -type FlushRequest struct { - Logs []byte `protobuf:"bytes,1,opt,name=logs" json:"logs,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *FlushRequest) Reset() { *m = FlushRequest{} } -func (m *FlushRequest) String() string { return proto.CompactTextString(m) } -func (*FlushRequest) ProtoMessage() {} - -func (m *FlushRequest) GetLogs() []byte { - if m != nil { - return m.Logs - } - return nil -} - -type SetStatusRequest struct { - Status *string `protobuf:"bytes,1,req,name=status" json:"status,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SetStatusRequest) Reset() { *m = SetStatusRequest{} } -func (m *SetStatusRequest) String() string { return proto.CompactTextString(m) } -func (*SetStatusRequest) ProtoMessage() {} - -func (m *SetStatusRequest) GetStatus() string { - if m != nil && m.Status != nil { - return *m.Status - } - return "" -} - -type LogOffset struct { - RequestId []byte `protobuf:"bytes,1,opt,name=request_id" json:"request_id,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *LogOffset) Reset() { *m = LogOffset{} } -func (m *LogOffset) String() string { return proto.CompactTextString(m) } -func (*LogOffset) ProtoMessage() {} - -func (m *LogOffset) GetRequestId() []byte { - if m != nil { - return m.RequestId - } - return nil -} - -type LogLine struct { - Time *int64 `protobuf:"varint,1,req,name=time" json:"time,omitempty"` - Level *int32 `protobuf:"varint,2,req,name=level" json:"level,omitempty"` - LogMessage *string `protobuf:"bytes,3,req,name=log_message" json:"log_message,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *LogLine) Reset() { *m = LogLine{} } -func (m *LogLine) String() string { return proto.CompactTextString(m) } -func (*LogLine) ProtoMessage() {} - -func (m *LogLine) GetTime() int64 { - if m != nil && m.Time != nil { - return *m.Time - } - return 0 -} - -func (m *LogLine) GetLevel() int32 { - if m != nil && m.Level != nil { - return *m.Level - } - return 0 -} - -func (m *LogLine) GetLogMessage() string { - if m != nil && m.LogMessage != nil { - return *m.LogMessage - } - return "" -} - -type RequestLog struct { - AppId *string `protobuf:"bytes,1,req,name=app_id" json:"app_id,omitempty"` - ModuleId *string `protobuf:"bytes,37,opt,name=module_id,def=default" json:"module_id,omitempty"` - VersionId *string `protobuf:"bytes,2,req,name=version_id" json:"version_id,omitempty"` - RequestId []byte `protobuf:"bytes,3,req,name=request_id" json:"request_id,omitempty"` - Offset *LogOffset `protobuf:"bytes,35,opt,name=offset" json:"offset,omitempty"` - Ip *string `protobuf:"bytes,4,req,name=ip" json:"ip,omitempty"` - Nickname *string `protobuf:"bytes,5,opt,name=nickname" json:"nickname,omitempty"` - StartTime *int64 `protobuf:"varint,6,req,name=start_time" json:"start_time,omitempty"` - EndTime *int64 `protobuf:"varint,7,req,name=end_time" json:"end_time,omitempty"` - Latency *int64 `protobuf:"varint,8,req,name=latency" json:"latency,omitempty"` - Mcycles *int64 `protobuf:"varint,9,req,name=mcycles" json:"mcycles,omitempty"` - Method *string `protobuf:"bytes,10,req,name=method" json:"method,omitempty"` - Resource *string `protobuf:"bytes,11,req,name=resource" json:"resource,omitempty"` - HttpVersion *string `protobuf:"bytes,12,req,name=http_version" json:"http_version,omitempty"` - Status *int32 `protobuf:"varint,13,req,name=status" json:"status,omitempty"` - ResponseSize *int64 `protobuf:"varint,14,req,name=response_size" json:"response_size,omitempty"` - Referrer *string `protobuf:"bytes,15,opt,name=referrer" json:"referrer,omitempty"` - UserAgent *string `protobuf:"bytes,16,opt,name=user_agent" json:"user_agent,omitempty"` - UrlMapEntry *string `protobuf:"bytes,17,req,name=url_map_entry" json:"url_map_entry,omitempty"` - Combined *string `protobuf:"bytes,18,req,name=combined" json:"combined,omitempty"` - ApiMcycles *int64 `protobuf:"varint,19,opt,name=api_mcycles" json:"api_mcycles,omitempty"` - Host *string `protobuf:"bytes,20,opt,name=host" json:"host,omitempty"` - Cost *float64 `protobuf:"fixed64,21,opt,name=cost" json:"cost,omitempty"` - TaskQueueName *string `protobuf:"bytes,22,opt,name=task_queue_name" json:"task_queue_name,omitempty"` - TaskName *string `protobuf:"bytes,23,opt,name=task_name" json:"task_name,omitempty"` - WasLoadingRequest *bool `protobuf:"varint,24,opt,name=was_loading_request" json:"was_loading_request,omitempty"` - PendingTime *int64 `protobuf:"varint,25,opt,name=pending_time" json:"pending_time,omitempty"` - ReplicaIndex *int32 `protobuf:"varint,26,opt,name=replica_index,def=-1" json:"replica_index,omitempty"` - Finished *bool `protobuf:"varint,27,opt,name=finished,def=1" json:"finished,omitempty"` - CloneKey []byte `protobuf:"bytes,28,opt,name=clone_key" json:"clone_key,omitempty"` - Line []*LogLine `protobuf:"bytes,29,rep,name=line" json:"line,omitempty"` - LinesIncomplete *bool `protobuf:"varint,36,opt,name=lines_incomplete" json:"lines_incomplete,omitempty"` - AppEngineRelease []byte `protobuf:"bytes,38,opt,name=app_engine_release" json:"app_engine_release,omitempty"` - ExitReason *int32 `protobuf:"varint,30,opt,name=exit_reason" json:"exit_reason,omitempty"` - WasThrottledForTime *bool `protobuf:"varint,31,opt,name=was_throttled_for_time" json:"was_throttled_for_time,omitempty"` - WasThrottledForRequests *bool `protobuf:"varint,32,opt,name=was_throttled_for_requests" json:"was_throttled_for_requests,omitempty"` - ThrottledTime *int64 `protobuf:"varint,33,opt,name=throttled_time" json:"throttled_time,omitempty"` - ServerName []byte `protobuf:"bytes,34,opt,name=server_name" json:"server_name,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *RequestLog) Reset() { *m = RequestLog{} } -func (m *RequestLog) String() string { return proto.CompactTextString(m) } -func (*RequestLog) ProtoMessage() {} - -const Default_RequestLog_ModuleId string = "default" -const Default_RequestLog_ReplicaIndex int32 = -1 -const Default_RequestLog_Finished bool = true - -func (m *RequestLog) GetAppId() string { - if m != nil && m.AppId != nil { - return *m.AppId - } - return "" -} - -func (m *RequestLog) GetModuleId() string { - if m != nil && m.ModuleId != nil { - return *m.ModuleId - } - return Default_RequestLog_ModuleId -} - -func (m *RequestLog) GetVersionId() string { - if m != nil && m.VersionId != nil { - return *m.VersionId - } - return "" -} - -func (m *RequestLog) GetRequestId() []byte { - if m != nil { - return m.RequestId - } - return nil -} - -func (m *RequestLog) GetOffset() *LogOffset { - if m != nil { - return m.Offset - } - return nil -} - -func (m *RequestLog) GetIp() string { - if m != nil && m.Ip != nil { - return *m.Ip - } - return "" -} - -func (m *RequestLog) GetNickname() string { - if m != nil && m.Nickname != nil { - return *m.Nickname - } - return "" -} - -func (m *RequestLog) GetStartTime() int64 { - if m != nil && m.StartTime != nil { - return *m.StartTime - } - return 0 -} - -func (m *RequestLog) GetEndTime() int64 { - if m != nil && m.EndTime != nil { - return *m.EndTime - } - return 0 -} - -func (m *RequestLog) GetLatency() int64 { - if m != nil && m.Latency != nil { - return *m.Latency - } - return 0 -} - -func (m *RequestLog) GetMcycles() int64 { - if m != nil && m.Mcycles != nil { - return *m.Mcycles - } - return 0 -} - -func (m *RequestLog) GetMethod() string { - if m != nil && m.Method != nil { - return *m.Method - } - return "" -} - -func (m *RequestLog) GetResource() string { - if m != nil && m.Resource != nil { - return *m.Resource - } - return "" -} - -func (m *RequestLog) GetHttpVersion() string { - if m != nil && m.HttpVersion != nil { - return *m.HttpVersion - } - return "" -} - -func (m *RequestLog) GetStatus() int32 { - if m != nil && m.Status != nil { - return *m.Status - } - return 0 -} - -func (m *RequestLog) GetResponseSize() int64 { - if m != nil && m.ResponseSize != nil { - return *m.ResponseSize - } - return 0 -} - -func (m *RequestLog) GetReferrer() string { - if m != nil && m.Referrer != nil { - return *m.Referrer - } - return "" -} - -func (m *RequestLog) GetUserAgent() string { - if m != nil && m.UserAgent != nil { - return *m.UserAgent - } - return "" -} - -func (m *RequestLog) GetUrlMapEntry() string { - if m != nil && m.UrlMapEntry != nil { - return *m.UrlMapEntry - } - return "" -} - -func (m *RequestLog) GetCombined() string { - if m != nil && m.Combined != nil { - return *m.Combined - } - return "" -} - -func (m *RequestLog) GetApiMcycles() int64 { - if m != nil && m.ApiMcycles != nil { - return *m.ApiMcycles - } - return 0 -} - -func (m *RequestLog) GetHost() string { - if m != nil && m.Host != nil { - return *m.Host - } - return "" -} - -func (m *RequestLog) GetCost() float64 { - if m != nil && m.Cost != nil { - return *m.Cost - } - return 0 -} - -func (m *RequestLog) GetTaskQueueName() string { - if m != nil && m.TaskQueueName != nil { - return *m.TaskQueueName - } - return "" -} - -func (m *RequestLog) GetTaskName() string { - if m != nil && m.TaskName != nil { - return *m.TaskName - } - return "" -} - -func (m *RequestLog) GetWasLoadingRequest() bool { - if m != nil && m.WasLoadingRequest != nil { - return *m.WasLoadingRequest - } - return false -} - -func (m *RequestLog) GetPendingTime() int64 { - if m != nil && m.PendingTime != nil { - return *m.PendingTime - } - return 0 -} - -func (m *RequestLog) GetReplicaIndex() int32 { - if m != nil && m.ReplicaIndex != nil { - return *m.ReplicaIndex - } - return Default_RequestLog_ReplicaIndex -} - -func (m *RequestLog) GetFinished() bool { - if m != nil && m.Finished != nil { - return *m.Finished - } - return Default_RequestLog_Finished -} - -func (m *RequestLog) GetCloneKey() []byte { - if m != nil { - return m.CloneKey - } - return nil -} - -func (m *RequestLog) GetLine() []*LogLine { - if m != nil { - return m.Line - } - return nil -} - -func (m *RequestLog) GetLinesIncomplete() bool { - if m != nil && m.LinesIncomplete != nil { - return *m.LinesIncomplete - } - return false -} - -func (m *RequestLog) GetAppEngineRelease() []byte { - if m != nil { - return m.AppEngineRelease - } - return nil -} - -func (m *RequestLog) GetExitReason() int32 { - if m != nil && m.ExitReason != nil { - return *m.ExitReason - } - return 0 -} - -func (m *RequestLog) GetWasThrottledForTime() bool { - if m != nil && m.WasThrottledForTime != nil { - return *m.WasThrottledForTime - } - return false -} - -func (m *RequestLog) GetWasThrottledForRequests() bool { - if m != nil && m.WasThrottledForRequests != nil { - return *m.WasThrottledForRequests - } - return false -} - -func (m *RequestLog) GetThrottledTime() int64 { - if m != nil && m.ThrottledTime != nil { - return *m.ThrottledTime - } - return 0 -} - -func (m *RequestLog) GetServerName() []byte { - if m != nil { - return m.ServerName - } - return nil -} - -type LogModuleVersion struct { - ModuleId *string `protobuf:"bytes,1,opt,name=module_id,def=default" json:"module_id,omitempty"` - VersionId *string `protobuf:"bytes,2,opt,name=version_id" json:"version_id,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *LogModuleVersion) Reset() { *m = LogModuleVersion{} } -func (m *LogModuleVersion) String() string { return proto.CompactTextString(m) } -func (*LogModuleVersion) ProtoMessage() {} - -const Default_LogModuleVersion_ModuleId string = "default" - -func (m *LogModuleVersion) GetModuleId() string { - if m != nil && m.ModuleId != nil { - return *m.ModuleId - } - return Default_LogModuleVersion_ModuleId -} - -func (m *LogModuleVersion) GetVersionId() string { - if m != nil && m.VersionId != nil { - return *m.VersionId - } - return "" -} - -type LogReadRequest struct { - AppId *string `protobuf:"bytes,1,req,name=app_id" json:"app_id,omitempty"` - VersionId []string `protobuf:"bytes,2,rep,name=version_id" json:"version_id,omitempty"` - ModuleVersion []*LogModuleVersion `protobuf:"bytes,19,rep,name=module_version" json:"module_version,omitempty"` - StartTime *int64 `protobuf:"varint,3,opt,name=start_time" json:"start_time,omitempty"` - EndTime *int64 `protobuf:"varint,4,opt,name=end_time" json:"end_time,omitempty"` - Offset *LogOffset `protobuf:"bytes,5,opt,name=offset" json:"offset,omitempty"` - RequestId [][]byte `protobuf:"bytes,6,rep,name=request_id" json:"request_id,omitempty"` - MinimumLogLevel *int32 `protobuf:"varint,7,opt,name=minimum_log_level" json:"minimum_log_level,omitempty"` - IncludeIncomplete *bool `protobuf:"varint,8,opt,name=include_incomplete" json:"include_incomplete,omitempty"` - Count *int64 `protobuf:"varint,9,opt,name=count" json:"count,omitempty"` - CombinedLogRegex *string `protobuf:"bytes,14,opt,name=combined_log_regex" json:"combined_log_regex,omitempty"` - HostRegex *string `protobuf:"bytes,15,opt,name=host_regex" json:"host_regex,omitempty"` - ReplicaIndex *int32 `protobuf:"varint,16,opt,name=replica_index" json:"replica_index,omitempty"` - IncludeAppLogs *bool `protobuf:"varint,10,opt,name=include_app_logs" json:"include_app_logs,omitempty"` - AppLogsPerRequest *int32 `protobuf:"varint,17,opt,name=app_logs_per_request" json:"app_logs_per_request,omitempty"` - IncludeHost *bool `protobuf:"varint,11,opt,name=include_host" json:"include_host,omitempty"` - IncludeAll *bool `protobuf:"varint,12,opt,name=include_all" json:"include_all,omitempty"` - CacheIterator *bool `protobuf:"varint,13,opt,name=cache_iterator" json:"cache_iterator,omitempty"` - NumShards *int32 `protobuf:"varint,18,opt,name=num_shards" json:"num_shards,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *LogReadRequest) Reset() { *m = LogReadRequest{} } -func (m *LogReadRequest) String() string { return proto.CompactTextString(m) } -func (*LogReadRequest) ProtoMessage() {} - -func (m *LogReadRequest) GetAppId() string { - if m != nil && m.AppId != nil { - return *m.AppId - } - return "" -} - -func (m *LogReadRequest) GetVersionId() []string { - if m != nil { - return m.VersionId - } - return nil -} - -func (m *LogReadRequest) GetModuleVersion() []*LogModuleVersion { - if m != nil { - return m.ModuleVersion - } - return nil -} - -func (m *LogReadRequest) GetStartTime() int64 { - if m != nil && m.StartTime != nil { - return *m.StartTime - } - return 0 -} - -func (m *LogReadRequest) GetEndTime() int64 { - if m != nil && m.EndTime != nil { - return *m.EndTime - } - return 0 -} - -func (m *LogReadRequest) GetOffset() *LogOffset { - if m != nil { - return m.Offset - } - return nil -} - -func (m *LogReadRequest) GetRequestId() [][]byte { - if m != nil { - return m.RequestId - } - return nil -} - -func (m *LogReadRequest) GetMinimumLogLevel() int32 { - if m != nil && m.MinimumLogLevel != nil { - return *m.MinimumLogLevel - } - return 0 -} - -func (m *LogReadRequest) GetIncludeIncomplete() bool { - if m != nil && m.IncludeIncomplete != nil { - return *m.IncludeIncomplete - } - return false -} - -func (m *LogReadRequest) GetCount() int64 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -func (m *LogReadRequest) GetCombinedLogRegex() string { - if m != nil && m.CombinedLogRegex != nil { - return *m.CombinedLogRegex - } - return "" -} - -func (m *LogReadRequest) GetHostRegex() string { - if m != nil && m.HostRegex != nil { - return *m.HostRegex - } - return "" -} - -func (m *LogReadRequest) GetReplicaIndex() int32 { - if m != nil && m.ReplicaIndex != nil { - return *m.ReplicaIndex - } - return 0 -} - -func (m *LogReadRequest) GetIncludeAppLogs() bool { - if m != nil && m.IncludeAppLogs != nil { - return *m.IncludeAppLogs - } - return false -} - -func (m *LogReadRequest) GetAppLogsPerRequest() int32 { - if m != nil && m.AppLogsPerRequest != nil { - return *m.AppLogsPerRequest - } - return 0 -} - -func (m *LogReadRequest) GetIncludeHost() bool { - if m != nil && m.IncludeHost != nil { - return *m.IncludeHost - } - return false -} - -func (m *LogReadRequest) GetIncludeAll() bool { - if m != nil && m.IncludeAll != nil { - return *m.IncludeAll - } - return false -} - -func (m *LogReadRequest) GetCacheIterator() bool { - if m != nil && m.CacheIterator != nil { - return *m.CacheIterator - } - return false -} - -func (m *LogReadRequest) GetNumShards() int32 { - if m != nil && m.NumShards != nil { - return *m.NumShards - } - return 0 -} - -type LogReadResponse struct { - Log []*RequestLog `protobuf:"bytes,1,rep,name=log" json:"log,omitempty"` - Offset *LogOffset `protobuf:"bytes,2,opt,name=offset" json:"offset,omitempty"` - LastEndTime *int64 `protobuf:"varint,3,opt,name=last_end_time" json:"last_end_time,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *LogReadResponse) Reset() { *m = LogReadResponse{} } -func (m *LogReadResponse) String() string { return proto.CompactTextString(m) } -func (*LogReadResponse) ProtoMessage() {} - -func (m *LogReadResponse) GetLog() []*RequestLog { - if m != nil { - return m.Log - } - return nil -} - -func (m *LogReadResponse) GetOffset() *LogOffset { - if m != nil { - return m.Offset - } - return nil -} - -func (m *LogReadResponse) GetLastEndTime() int64 { - if m != nil && m.LastEndTime != nil { - return *m.LastEndTime - } - return 0 -} - -type LogUsageRecord struct { - VersionId *string `protobuf:"bytes,1,opt,name=version_id" json:"version_id,omitempty"` - StartTime *int32 `protobuf:"varint,2,opt,name=start_time" json:"start_time,omitempty"` - EndTime *int32 `protobuf:"varint,3,opt,name=end_time" json:"end_time,omitempty"` - Count *int64 `protobuf:"varint,4,opt,name=count" json:"count,omitempty"` - TotalSize *int64 `protobuf:"varint,5,opt,name=total_size" json:"total_size,omitempty"` - Records *int32 `protobuf:"varint,6,opt,name=records" json:"records,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *LogUsageRecord) Reset() { *m = LogUsageRecord{} } -func (m *LogUsageRecord) String() string { return proto.CompactTextString(m) } -func (*LogUsageRecord) ProtoMessage() {} - -func (m *LogUsageRecord) GetVersionId() string { - if m != nil && m.VersionId != nil { - return *m.VersionId - } - return "" -} - -func (m *LogUsageRecord) GetStartTime() int32 { - if m != nil && m.StartTime != nil { - return *m.StartTime - } - return 0 -} - -func (m *LogUsageRecord) GetEndTime() int32 { - if m != nil && m.EndTime != nil { - return *m.EndTime - } - return 0 -} - -func (m *LogUsageRecord) GetCount() int64 { - if m != nil && m.Count != nil { - return *m.Count - } - return 0 -} - -func (m *LogUsageRecord) GetTotalSize() int64 { - if m != nil && m.TotalSize != nil { - return *m.TotalSize - } - return 0 -} - -func (m *LogUsageRecord) GetRecords() int32 { - if m != nil && m.Records != nil { - return *m.Records - } - return 0 -} - -type LogUsageRequest struct { - AppId *string `protobuf:"bytes,1,req,name=app_id" json:"app_id,omitempty"` - VersionId []string `protobuf:"bytes,2,rep,name=version_id" json:"version_id,omitempty"` - StartTime *int32 `protobuf:"varint,3,opt,name=start_time" json:"start_time,omitempty"` - EndTime *int32 `protobuf:"varint,4,opt,name=end_time" json:"end_time,omitempty"` - ResolutionHours *uint32 `protobuf:"varint,5,opt,name=resolution_hours,def=1" json:"resolution_hours,omitempty"` - CombineVersions *bool `protobuf:"varint,6,opt,name=combine_versions" json:"combine_versions,omitempty"` - UsageVersion *int32 `protobuf:"varint,7,opt,name=usage_version" json:"usage_version,omitempty"` - VersionsOnly *bool `protobuf:"varint,8,opt,name=versions_only" json:"versions_only,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *LogUsageRequest) Reset() { *m = LogUsageRequest{} } -func (m *LogUsageRequest) String() string { return proto.CompactTextString(m) } -func (*LogUsageRequest) ProtoMessage() {} - -const Default_LogUsageRequest_ResolutionHours uint32 = 1 - -func (m *LogUsageRequest) GetAppId() string { - if m != nil && m.AppId != nil { - return *m.AppId - } - return "" -} - -func (m *LogUsageRequest) GetVersionId() []string { - if m != nil { - return m.VersionId - } - return nil -} - -func (m *LogUsageRequest) GetStartTime() int32 { - if m != nil && m.StartTime != nil { - return *m.StartTime - } - return 0 -} - -func (m *LogUsageRequest) GetEndTime() int32 { - if m != nil && m.EndTime != nil { - return *m.EndTime - } - return 0 -} - -func (m *LogUsageRequest) GetResolutionHours() uint32 { - if m != nil && m.ResolutionHours != nil { - return *m.ResolutionHours - } - return Default_LogUsageRequest_ResolutionHours -} - -func (m *LogUsageRequest) GetCombineVersions() bool { - if m != nil && m.CombineVersions != nil { - return *m.CombineVersions - } - return false -} - -func (m *LogUsageRequest) GetUsageVersion() int32 { - if m != nil && m.UsageVersion != nil { - return *m.UsageVersion - } - return 0 -} - -func (m *LogUsageRequest) GetVersionsOnly() bool { - if m != nil && m.VersionsOnly != nil { - return *m.VersionsOnly - } - return false -} - -type LogUsageResponse struct { - Usage []*LogUsageRecord `protobuf:"bytes,1,rep,name=usage" json:"usage,omitempty"` - Summary *LogUsageRecord `protobuf:"bytes,2,opt,name=summary" json:"summary,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *LogUsageResponse) Reset() { *m = LogUsageResponse{} } -func (m *LogUsageResponse) String() string { return proto.CompactTextString(m) } -func (*LogUsageResponse) ProtoMessage() {} - -func (m *LogUsageResponse) GetUsage() []*LogUsageRecord { - if m != nil { - return m.Usage - } - return nil -} - -func (m *LogUsageResponse) GetSummary() *LogUsageRecord { - if m != nil { - return m.Summary - } - return nil -} - -func init() { -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/log/log_service.proto b/Godeps/_workspace/src/google.golang.org/appengine/internal/log/log_service.proto deleted file mode 100644 index 8981dc475..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/log/log_service.proto +++ /dev/null @@ -1,150 +0,0 @@ -syntax = "proto2"; -option go_package = "log"; - -package appengine; - -message LogServiceError { - enum ErrorCode { - OK = 0; - INVALID_REQUEST = 1; - STORAGE_ERROR = 2; - } -} - -message UserAppLogLine { - required int64 timestamp_usec = 1; - required int64 level = 2; - required string message = 3; -} - -message UserAppLogGroup { - repeated UserAppLogLine log_line = 2; -} - -message FlushRequest { - optional bytes logs = 1; -} - -message SetStatusRequest { - required string status = 1; -} - - -message LogOffset { - optional bytes request_id = 1; -} - -message LogLine { - required int64 time = 1; - required int32 level = 2; - required string log_message = 3; -} - -message RequestLog { - required string app_id = 1; - optional string module_id = 37 [default="default"]; - required string version_id = 2; - required bytes request_id = 3; - optional LogOffset offset = 35; - required string ip = 4; - optional string nickname = 5; - required int64 start_time = 6; - required int64 end_time = 7; - required int64 latency = 8; - required int64 mcycles = 9; - required string method = 10; - required string resource = 11; - required string http_version = 12; - required int32 status = 13; - required int64 response_size = 14; - optional string referrer = 15; - optional string user_agent = 16; - required string url_map_entry = 17; - required string combined = 18; - optional int64 api_mcycles = 19; - optional string host = 20; - optional double cost = 21; - - optional string task_queue_name = 22; - optional string task_name = 23; - - optional bool was_loading_request = 24; - optional int64 pending_time = 25; - optional int32 replica_index = 26 [default = -1]; - optional bool finished = 27 [default = true]; - optional bytes clone_key = 28; - - repeated LogLine line = 29; - - optional bool lines_incomplete = 36; - optional bytes app_engine_release = 38; - - optional int32 exit_reason = 30; - optional bool was_throttled_for_time = 31; - optional bool was_throttled_for_requests = 32; - optional int64 throttled_time = 33; - - optional bytes server_name = 34; -} - -message LogModuleVersion { - optional string module_id = 1 [default="default"]; - optional string version_id = 2; -} - -message LogReadRequest { - required string app_id = 1; - repeated string version_id = 2; - repeated LogModuleVersion module_version = 19; - - optional int64 start_time = 3; - optional int64 end_time = 4; - optional LogOffset offset = 5; - repeated bytes request_id = 6; - - optional int32 minimum_log_level = 7; - optional bool include_incomplete = 8; - optional int64 count = 9; - - optional string combined_log_regex = 14; - optional string host_regex = 15; - optional int32 replica_index = 16; - - optional bool include_app_logs = 10; - optional int32 app_logs_per_request = 17; - optional bool include_host = 11; - optional bool include_all = 12; - optional bool cache_iterator = 13; - optional int32 num_shards = 18; -} - -message LogReadResponse { - repeated RequestLog log = 1; - optional LogOffset offset = 2; - optional int64 last_end_time = 3; -} - -message LogUsageRecord { - optional string version_id = 1; - optional int32 start_time = 2; - optional int32 end_time = 3; - optional int64 count = 4; - optional int64 total_size = 5; - optional int32 records = 6; -} - -message LogUsageRequest { - required string app_id = 1; - repeated string version_id = 2; - optional int32 start_time = 3; - optional int32 end_time = 4; - optional uint32 resolution_hours = 5 [default = 1]; - optional bool combine_versions = 6; - optional int32 usage_version = 7; - optional bool versions_only = 8; -} - -message LogUsageResponse { - repeated LogUsageRecord usage = 1; - optional LogUsageRecord summary = 2; -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/metadata.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/metadata.go deleted file mode 100644 index 9cc1f71d1..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/metadata.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package internal - -// This file has code for accessing metadata. -// -// References: -// https://cloud.google.com/compute/docs/metadata - -import ( - "fmt" - "io/ioutil" - "log" - "net/http" - "net/url" -) - -const ( - metadataHost = "metadata" - metadataPath = "/computeMetadata/v1/" -) - -var ( - metadataRequestHeaders = http.Header{ - "Metadata-Flavor": []string{"Google"}, - } -) - -// TODO(dsymonds): Do we need to support default values, like Python? -func mustGetMetadata(key string) []byte { - b, err := getMetadata(key) - if err != nil { - log.Fatalf("Metadata fetch failed: %v", err) - } - return b -} - -func getMetadata(key string) ([]byte, error) { - // TODO(dsymonds): May need to use url.Parse to support keys with query args. - req := &http.Request{ - Method: "GET", - URL: &url.URL{ - Scheme: "http", - Host: metadataHost, - Path: metadataPath + key, - }, - Header: metadataRequestHeaders, - Host: metadataHost, - } - resp, err := http.DefaultClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - if resp.StatusCode != 200 { - return nil, fmt.Errorf("metadata server returned HTTP %d", resp.StatusCode) - } - return ioutil.ReadAll(resp.Body) -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/modules/modules_service.pb.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/modules/modules_service.pb.go deleted file mode 100644 index a0145ed31..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/modules/modules_service.pb.go +++ /dev/null @@ -1,375 +0,0 @@ -// Code generated by protoc-gen-go. -// source: google.golang.org/appengine/internal/modules/modules_service.proto -// DO NOT EDIT! - -/* -Package modules is a generated protocol buffer package. - -It is generated from these files: - google.golang.org/appengine/internal/modules/modules_service.proto - -It has these top-level messages: - ModulesServiceError - GetModulesRequest - GetModulesResponse - GetVersionsRequest - GetVersionsResponse - GetDefaultVersionRequest - GetDefaultVersionResponse - GetNumInstancesRequest - GetNumInstancesResponse - SetNumInstancesRequest - SetNumInstancesResponse - StartModuleRequest - StartModuleResponse - StopModuleRequest - StopModuleResponse - GetHostnameRequest - GetHostnameResponse -*/ -package modules - -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 - -type ModulesServiceError_ErrorCode int32 - -const ( - ModulesServiceError_OK ModulesServiceError_ErrorCode = 0 - ModulesServiceError_INVALID_MODULE ModulesServiceError_ErrorCode = 1 - ModulesServiceError_INVALID_VERSION ModulesServiceError_ErrorCode = 2 - ModulesServiceError_INVALID_INSTANCES ModulesServiceError_ErrorCode = 3 - ModulesServiceError_TRANSIENT_ERROR ModulesServiceError_ErrorCode = 4 - ModulesServiceError_UNEXPECTED_STATE ModulesServiceError_ErrorCode = 5 -) - -var ModulesServiceError_ErrorCode_name = map[int32]string{ - 0: "OK", - 1: "INVALID_MODULE", - 2: "INVALID_VERSION", - 3: "INVALID_INSTANCES", - 4: "TRANSIENT_ERROR", - 5: "UNEXPECTED_STATE", -} -var ModulesServiceError_ErrorCode_value = map[string]int32{ - "OK": 0, - "INVALID_MODULE": 1, - "INVALID_VERSION": 2, - "INVALID_INSTANCES": 3, - "TRANSIENT_ERROR": 4, - "UNEXPECTED_STATE": 5, -} - -func (x ModulesServiceError_ErrorCode) Enum() *ModulesServiceError_ErrorCode { - p := new(ModulesServiceError_ErrorCode) - *p = x - return p -} -func (x ModulesServiceError_ErrorCode) String() string { - return proto.EnumName(ModulesServiceError_ErrorCode_name, int32(x)) -} -func (x *ModulesServiceError_ErrorCode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(ModulesServiceError_ErrorCode_value, data, "ModulesServiceError_ErrorCode") - if err != nil { - return err - } - *x = ModulesServiceError_ErrorCode(value) - return nil -} - -type ModulesServiceError struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *ModulesServiceError) Reset() { *m = ModulesServiceError{} } -func (m *ModulesServiceError) String() string { return proto.CompactTextString(m) } -func (*ModulesServiceError) ProtoMessage() {} - -type GetModulesRequest struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetModulesRequest) Reset() { *m = GetModulesRequest{} } -func (m *GetModulesRequest) String() string { return proto.CompactTextString(m) } -func (*GetModulesRequest) ProtoMessage() {} - -type GetModulesResponse struct { - Module []string `protobuf:"bytes,1,rep,name=module" json:"module,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetModulesResponse) Reset() { *m = GetModulesResponse{} } -func (m *GetModulesResponse) String() string { return proto.CompactTextString(m) } -func (*GetModulesResponse) ProtoMessage() {} - -func (m *GetModulesResponse) GetModule() []string { - if m != nil { - return m.Module - } - return nil -} - -type GetVersionsRequest struct { - Module *string `protobuf:"bytes,1,opt,name=module" json:"module,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetVersionsRequest) Reset() { *m = GetVersionsRequest{} } -func (m *GetVersionsRequest) String() string { return proto.CompactTextString(m) } -func (*GetVersionsRequest) ProtoMessage() {} - -func (m *GetVersionsRequest) GetModule() string { - if m != nil && m.Module != nil { - return *m.Module - } - return "" -} - -type GetVersionsResponse struct { - Version []string `protobuf:"bytes,1,rep,name=version" json:"version,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetVersionsResponse) Reset() { *m = GetVersionsResponse{} } -func (m *GetVersionsResponse) String() string { return proto.CompactTextString(m) } -func (*GetVersionsResponse) ProtoMessage() {} - -func (m *GetVersionsResponse) GetVersion() []string { - if m != nil { - return m.Version - } - return nil -} - -type GetDefaultVersionRequest struct { - Module *string `protobuf:"bytes,1,opt,name=module" json:"module,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetDefaultVersionRequest) Reset() { *m = GetDefaultVersionRequest{} } -func (m *GetDefaultVersionRequest) String() string { return proto.CompactTextString(m) } -func (*GetDefaultVersionRequest) ProtoMessage() {} - -func (m *GetDefaultVersionRequest) GetModule() string { - if m != nil && m.Module != nil { - return *m.Module - } - return "" -} - -type GetDefaultVersionResponse struct { - Version *string `protobuf:"bytes,1,req,name=version" json:"version,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetDefaultVersionResponse) Reset() { *m = GetDefaultVersionResponse{} } -func (m *GetDefaultVersionResponse) String() string { return proto.CompactTextString(m) } -func (*GetDefaultVersionResponse) ProtoMessage() {} - -func (m *GetDefaultVersionResponse) GetVersion() string { - if m != nil && m.Version != nil { - return *m.Version - } - return "" -} - -type GetNumInstancesRequest struct { - Module *string `protobuf:"bytes,1,opt,name=module" json:"module,omitempty"` - Version *string `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetNumInstancesRequest) Reset() { *m = GetNumInstancesRequest{} } -func (m *GetNumInstancesRequest) String() string { return proto.CompactTextString(m) } -func (*GetNumInstancesRequest) ProtoMessage() {} - -func (m *GetNumInstancesRequest) GetModule() string { - if m != nil && m.Module != nil { - return *m.Module - } - return "" -} - -func (m *GetNumInstancesRequest) GetVersion() string { - if m != nil && m.Version != nil { - return *m.Version - } - return "" -} - -type GetNumInstancesResponse struct { - Instances *int64 `protobuf:"varint,1,req,name=instances" json:"instances,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetNumInstancesResponse) Reset() { *m = GetNumInstancesResponse{} } -func (m *GetNumInstancesResponse) String() string { return proto.CompactTextString(m) } -func (*GetNumInstancesResponse) ProtoMessage() {} - -func (m *GetNumInstancesResponse) GetInstances() int64 { - if m != nil && m.Instances != nil { - return *m.Instances - } - return 0 -} - -type SetNumInstancesRequest struct { - Module *string `protobuf:"bytes,1,opt,name=module" json:"module,omitempty"` - Version *string `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"` - Instances *int64 `protobuf:"varint,3,req,name=instances" json:"instances,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *SetNumInstancesRequest) Reset() { *m = SetNumInstancesRequest{} } -func (m *SetNumInstancesRequest) String() string { return proto.CompactTextString(m) } -func (*SetNumInstancesRequest) ProtoMessage() {} - -func (m *SetNumInstancesRequest) GetModule() string { - if m != nil && m.Module != nil { - return *m.Module - } - return "" -} - -func (m *SetNumInstancesRequest) GetVersion() string { - if m != nil && m.Version != nil { - return *m.Version - } - return "" -} - -func (m *SetNumInstancesRequest) GetInstances() int64 { - if m != nil && m.Instances != nil { - return *m.Instances - } - return 0 -} - -type SetNumInstancesResponse struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *SetNumInstancesResponse) Reset() { *m = SetNumInstancesResponse{} } -func (m *SetNumInstancesResponse) String() string { return proto.CompactTextString(m) } -func (*SetNumInstancesResponse) ProtoMessage() {} - -type StartModuleRequest struct { - Module *string `protobuf:"bytes,1,req,name=module" json:"module,omitempty"` - Version *string `protobuf:"bytes,2,req,name=version" json:"version,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *StartModuleRequest) Reset() { *m = StartModuleRequest{} } -func (m *StartModuleRequest) String() string { return proto.CompactTextString(m) } -func (*StartModuleRequest) ProtoMessage() {} - -func (m *StartModuleRequest) GetModule() string { - if m != nil && m.Module != nil { - return *m.Module - } - return "" -} - -func (m *StartModuleRequest) GetVersion() string { - if m != nil && m.Version != nil { - return *m.Version - } - return "" -} - -type StartModuleResponse struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *StartModuleResponse) Reset() { *m = StartModuleResponse{} } -func (m *StartModuleResponse) String() string { return proto.CompactTextString(m) } -func (*StartModuleResponse) ProtoMessage() {} - -type StopModuleRequest struct { - Module *string `protobuf:"bytes,1,opt,name=module" json:"module,omitempty"` - Version *string `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *StopModuleRequest) Reset() { *m = StopModuleRequest{} } -func (m *StopModuleRequest) String() string { return proto.CompactTextString(m) } -func (*StopModuleRequest) ProtoMessage() {} - -func (m *StopModuleRequest) GetModule() string { - if m != nil && m.Module != nil { - return *m.Module - } - return "" -} - -func (m *StopModuleRequest) GetVersion() string { - if m != nil && m.Version != nil { - return *m.Version - } - return "" -} - -type StopModuleResponse struct { - XXX_unrecognized []byte `json:"-"` -} - -func (m *StopModuleResponse) Reset() { *m = StopModuleResponse{} } -func (m *StopModuleResponse) String() string { return proto.CompactTextString(m) } -func (*StopModuleResponse) ProtoMessage() {} - -type GetHostnameRequest struct { - Module *string `protobuf:"bytes,1,opt,name=module" json:"module,omitempty"` - Version *string `protobuf:"bytes,2,opt,name=version" json:"version,omitempty"` - Instance *string `protobuf:"bytes,3,opt,name=instance" json:"instance,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetHostnameRequest) Reset() { *m = GetHostnameRequest{} } -func (m *GetHostnameRequest) String() string { return proto.CompactTextString(m) } -func (*GetHostnameRequest) ProtoMessage() {} - -func (m *GetHostnameRequest) GetModule() string { - if m != nil && m.Module != nil { - return *m.Module - } - return "" -} - -func (m *GetHostnameRequest) GetVersion() string { - if m != nil && m.Version != nil { - return *m.Version - } - return "" -} - -func (m *GetHostnameRequest) GetInstance() string { - if m != nil && m.Instance != nil { - return *m.Instance - } - return "" -} - -type GetHostnameResponse struct { - Hostname *string `protobuf:"bytes,1,req,name=hostname" json:"hostname,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *GetHostnameResponse) Reset() { *m = GetHostnameResponse{} } -func (m *GetHostnameResponse) String() string { return proto.CompactTextString(m) } -func (*GetHostnameResponse) ProtoMessage() {} - -func (m *GetHostnameResponse) GetHostname() string { - if m != nil && m.Hostname != nil { - return *m.Hostname - } - return "" -} - -func init() { -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/modules/modules_service.proto b/Godeps/_workspace/src/google.golang.org/appengine/internal/modules/modules_service.proto deleted file mode 100644 index d29f0065a..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/modules/modules_service.proto +++ /dev/null @@ -1,80 +0,0 @@ -syntax = "proto2"; -option go_package = "modules"; - -package appengine; - -message ModulesServiceError { - enum ErrorCode { - OK = 0; - INVALID_MODULE = 1; - INVALID_VERSION = 2; - INVALID_INSTANCES = 3; - TRANSIENT_ERROR = 4; - UNEXPECTED_STATE = 5; - } -} - -message GetModulesRequest { -} - -message GetModulesResponse { - repeated string module = 1; -} - -message GetVersionsRequest { - optional string module = 1; -} - -message GetVersionsResponse { - repeated string version = 1; -} - -message GetDefaultVersionRequest { - optional string module = 1; -} - -message GetDefaultVersionResponse { - required string version = 1; -} - -message GetNumInstancesRequest { - optional string module = 1; - optional string version = 2; -} - -message GetNumInstancesResponse { - required int64 instances = 1; -} - -message SetNumInstancesRequest { - optional string module = 1; - optional string version = 2; - required int64 instances = 3; -} - -message SetNumInstancesResponse {} - -message StartModuleRequest { - required string module = 1; - required string version = 2; -} - -message StartModuleResponse {} - -message StopModuleRequest { - optional string module = 1; - optional string version = 2; -} - -message StopModuleResponse {} - -message GetHostnameRequest { - optional string module = 1; - optional string version = 2; - optional string instance = 3; -} - -message GetHostnameResponse { - required string hostname = 1; -} - diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/net.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/net.go deleted file mode 100644 index 3b94cf0c6..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/net.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package internal - -// This file implements a network dialer that limits the number of concurrent connections. -// It is only used for API calls. - -import ( - "log" - "net" - "runtime" - "sync" - "time" -) - -var limitSem = make(chan int, 100) // TODO(dsymonds): Use environment variable. - -func limitRelease() { - // non-blocking - select { - case <-limitSem: - default: - // This should not normally happen. - log.Print("appengine: unbalanced limitSem release!") - } -} - -func limitDial(network, addr string) (net.Conn, error) { - limitSem <- 1 - - // Dial with a timeout in case the API host is MIA. - // The connection should normally be very fast. - conn, err := net.DialTimeout(network, addr, 500*time.Millisecond) - if err != nil { - limitRelease() - return nil, err - } - lc := &limitConn{Conn: conn} - runtime.SetFinalizer(lc, (*limitConn).Close) // shouldn't usually be required - return lc, nil -} - -type limitConn struct { - close sync.Once - net.Conn -} - -func (lc *limitConn) Close() error { - defer lc.close.Do(func() { - limitRelease() - runtime.SetFinalizer(lc, nil) - }) - return lc.Conn.Close() -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/regen.sh b/Godeps/_workspace/src/google.golang.org/appengine/internal/regen.sh deleted file mode 100644 index 2fdb546a6..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/regen.sh +++ /dev/null @@ -1,40 +0,0 @@ -#!/bin/bash -e -# -# This script rebuilds the generated code for the protocol buffers. -# To run this you will need protoc and goprotobuf installed; -# see https://github.com/golang/protobuf for instructions. - -PKG=google.golang.org/appengine - -function die() { - echo 1>&2 $* - exit 1 -} - -# Sanity check that the right tools are accessible. -for tool in go protoc protoc-gen-go; do - q=$(which $tool) || die "didn't find $tool" - echo 1>&2 "$tool: $q" -done - -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 - -# Run protoc once per package. -for dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do - echo 1>&2 "* $dir" - protoc --go_out=. $dir/*.proto -done - -for f in $(find $PKG/internal -name '*.pb.go'); do - # Remove proto.RegisterEnum calls. - # These cause duplicate registration panics when these packages - # are used on classic App Engine. proto.RegisterEnum only affects - # parsing the text format; we don't care about that. - # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17 - sed -i '/proto.RegisterEnum/d' $f -done diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/remote_api/remote_api.pb.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/remote_api/remote_api.pb.go deleted file mode 100644 index 526bd39e6..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/remote_api/remote_api.pb.go +++ /dev/null @@ -1,231 +0,0 @@ -// Code generated by protoc-gen-go. -// source: google.golang.org/appengine/internal/remote_api/remote_api.proto -// DO NOT EDIT! - -/* -Package remote_api is a generated protocol buffer package. - -It is generated from these files: - google.golang.org/appengine/internal/remote_api/remote_api.proto - -It has these top-level messages: - Request - ApplicationError - RpcError - Response -*/ -package remote_api - -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 - -type RpcError_ErrorCode int32 - -const ( - RpcError_UNKNOWN RpcError_ErrorCode = 0 - RpcError_CALL_NOT_FOUND RpcError_ErrorCode = 1 - RpcError_PARSE_ERROR RpcError_ErrorCode = 2 - RpcError_SECURITY_VIOLATION RpcError_ErrorCode = 3 - RpcError_OVER_QUOTA RpcError_ErrorCode = 4 - RpcError_REQUEST_TOO_LARGE RpcError_ErrorCode = 5 - RpcError_CAPABILITY_DISABLED RpcError_ErrorCode = 6 - RpcError_FEATURE_DISABLED RpcError_ErrorCode = 7 - RpcError_BAD_REQUEST RpcError_ErrorCode = 8 - RpcError_RESPONSE_TOO_LARGE RpcError_ErrorCode = 9 - RpcError_CANCELLED RpcError_ErrorCode = 10 - RpcError_REPLAY_ERROR RpcError_ErrorCode = 11 - RpcError_DEADLINE_EXCEEDED RpcError_ErrorCode = 12 -) - -var RpcError_ErrorCode_name = map[int32]string{ - 0: "UNKNOWN", - 1: "CALL_NOT_FOUND", - 2: "PARSE_ERROR", - 3: "SECURITY_VIOLATION", - 4: "OVER_QUOTA", - 5: "REQUEST_TOO_LARGE", - 6: "CAPABILITY_DISABLED", - 7: "FEATURE_DISABLED", - 8: "BAD_REQUEST", - 9: "RESPONSE_TOO_LARGE", - 10: "CANCELLED", - 11: "REPLAY_ERROR", - 12: "DEADLINE_EXCEEDED", -} -var RpcError_ErrorCode_value = map[string]int32{ - "UNKNOWN": 0, - "CALL_NOT_FOUND": 1, - "PARSE_ERROR": 2, - "SECURITY_VIOLATION": 3, - "OVER_QUOTA": 4, - "REQUEST_TOO_LARGE": 5, - "CAPABILITY_DISABLED": 6, - "FEATURE_DISABLED": 7, - "BAD_REQUEST": 8, - "RESPONSE_TOO_LARGE": 9, - "CANCELLED": 10, - "REPLAY_ERROR": 11, - "DEADLINE_EXCEEDED": 12, -} - -func (x RpcError_ErrorCode) Enum() *RpcError_ErrorCode { - p := new(RpcError_ErrorCode) - *p = x - return p -} -func (x RpcError_ErrorCode) String() string { - return proto.EnumName(RpcError_ErrorCode_name, int32(x)) -} -func (x *RpcError_ErrorCode) UnmarshalJSON(data []byte) error { - value, err := proto.UnmarshalJSONEnum(RpcError_ErrorCode_value, data, "RpcError_ErrorCode") - if err != nil { - return err - } - *x = RpcError_ErrorCode(value) - return nil -} - -type Request struct { - ServiceName *string `protobuf:"bytes,2,req,name=service_name" json:"service_name,omitempty"` - Method *string `protobuf:"bytes,3,req,name=method" json:"method,omitempty"` - Request []byte `protobuf:"bytes,4,req,name=request" json:"request,omitempty"` - RequestId *string `protobuf:"bytes,5,opt,name=request_id" json:"request_id,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Request) Reset() { *m = Request{} } -func (m *Request) String() string { return proto.CompactTextString(m) } -func (*Request) ProtoMessage() {} - -func (m *Request) GetServiceName() string { - if m != nil && m.ServiceName != nil { - return *m.ServiceName - } - return "" -} - -func (m *Request) GetMethod() string { - if m != nil && m.Method != nil { - return *m.Method - } - return "" -} - -func (m *Request) GetRequest() []byte { - if m != nil { - return m.Request - } - return nil -} - -func (m *Request) GetRequestId() string { - if m != nil && m.RequestId != nil { - return *m.RequestId - } - return "" -} - -type ApplicationError struct { - Code *int32 `protobuf:"varint,1,req,name=code" json:"code,omitempty"` - Detail *string `protobuf:"bytes,2,req,name=detail" json:"detail,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *ApplicationError) Reset() { *m = ApplicationError{} } -func (m *ApplicationError) String() string { return proto.CompactTextString(m) } -func (*ApplicationError) ProtoMessage() {} - -func (m *ApplicationError) GetCode() int32 { - if m != nil && m.Code != nil { - return *m.Code - } - return 0 -} - -func (m *ApplicationError) GetDetail() string { - if m != nil && m.Detail != nil { - return *m.Detail - } - return "" -} - -type RpcError struct { - Code *int32 `protobuf:"varint,1,req,name=code" json:"code,omitempty"` - Detail *string `protobuf:"bytes,2,opt,name=detail" json:"detail,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *RpcError) Reset() { *m = RpcError{} } -func (m *RpcError) String() string { return proto.CompactTextString(m) } -func (*RpcError) ProtoMessage() {} - -func (m *RpcError) GetCode() int32 { - if m != nil && m.Code != nil { - return *m.Code - } - return 0 -} - -func (m *RpcError) GetDetail() string { - if m != nil && m.Detail != nil { - return *m.Detail - } - return "" -} - -type Response struct { - Response []byte `protobuf:"bytes,1,opt,name=response" json:"response,omitempty"` - Exception []byte `protobuf:"bytes,2,opt,name=exception" json:"exception,omitempty"` - ApplicationError *ApplicationError `protobuf:"bytes,3,opt,name=application_error" json:"application_error,omitempty"` - JavaException []byte `protobuf:"bytes,4,opt,name=java_exception" json:"java_exception,omitempty"` - RpcError *RpcError `protobuf:"bytes,5,opt,name=rpc_error" json:"rpc_error,omitempty"` - XXX_unrecognized []byte `json:"-"` -} - -func (m *Response) Reset() { *m = Response{} } -func (m *Response) String() string { return proto.CompactTextString(m) } -func (*Response) ProtoMessage() {} - -func (m *Response) GetResponse() []byte { - if m != nil { - return m.Response - } - return nil -} - -func (m *Response) GetException() []byte { - if m != nil { - return m.Exception - } - return nil -} - -func (m *Response) GetApplicationError() *ApplicationError { - if m != nil { - return m.ApplicationError - } - return nil -} - -func (m *Response) GetJavaException() []byte { - if m != nil { - return m.JavaException - } - return nil -} - -func (m *Response) GetRpcError() *RpcError { - if m != nil { - return m.RpcError - } - return nil -} - -func init() { -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/remote_api/remote_api.proto b/Godeps/_workspace/src/google.golang.org/appengine/internal/remote_api/remote_api.proto deleted file mode 100644 index f21763a4e..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/remote_api/remote_api.proto +++ /dev/null @@ -1,44 +0,0 @@ -syntax = "proto2"; -option go_package = "remote_api"; - -package remote_api; - -message Request { - required string service_name = 2; - required string method = 3; - required bytes request = 4; - optional string request_id = 5; -} - -message ApplicationError { - required int32 code = 1; - required string detail = 2; -} - -message RpcError { - enum ErrorCode { - UNKNOWN = 0; - CALL_NOT_FOUND = 1; - PARSE_ERROR = 2; - SECURITY_VIOLATION = 3; - OVER_QUOTA = 4; - REQUEST_TOO_LARGE = 5; - CAPABILITY_DISABLED = 6; - FEATURE_DISABLED = 7; - BAD_REQUEST = 8; - RESPONSE_TOO_LARGE = 9; - CANCELLED = 10; - REPLAY_ERROR = 11; - DEADLINE_EXCEEDED = 12; - } - required int32 code = 1; - optional string detail = 2; -} - -message Response { - optional bytes response = 1; - optional bytes exception = 2; - optional ApplicationError application_error = 3; - optional bytes java_exception = 4; - optional RpcError rpc_error = 5; -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/internal/transaction.go b/Godeps/_workspace/src/google.golang.org/appengine/internal/transaction.go deleted file mode 100644 index 28a6d1812..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/internal/transaction.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2014 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package internal - -// This file implements hooks for applying datastore transactions. - -import ( - "errors" - "reflect" - - "github.com/golang/protobuf/proto" - netcontext "golang.org/x/net/context" - - basepb "google.golang.org/appengine/internal/base" - pb "google.golang.org/appengine/internal/datastore" -) - -var transactionSetters = make(map[reflect.Type]reflect.Value) - -// RegisterTransactionSetter registers a function that sets transaction information -// in a protocol buffer message. f should be a function with two arguments, -// the first being a protocol buffer type, and the second being *datastore.Transaction. -func RegisterTransactionSetter(f interface{}) { - v := reflect.ValueOf(f) - transactionSetters[v.Type().In(0)] = v -} - -// applyTransaction applies the transaction t to message pb -// by using the relevant setter passed to RegisterTransactionSetter. -func applyTransaction(pb proto.Message, t *pb.Transaction) { - v := reflect.ValueOf(pb) - if f, ok := transactionSetters[v.Type()]; ok { - f.Call([]reflect.Value{v, reflect.ValueOf(t)}) - } -} - -var transactionKey = "used for *Transaction" - -func transactionFromContext(ctx netcontext.Context) *transaction { - t, _ := ctx.Value(&transactionKey).(*transaction) - return t -} - -func withTransaction(ctx netcontext.Context, t *transaction) netcontext.Context { - return netcontext.WithValue(ctx, &transactionKey, t) -} - -type transaction struct { - transaction pb.Transaction - finished bool -} - -var ErrConcurrentTransaction = errors.New("internal: concurrent transaction") - -func RunTransactionOnce(c netcontext.Context, f func(netcontext.Context) error, xg bool) error { - if transactionFromContext(c) != nil { - return errors.New("nested transactions are not supported") - } - - // Begin the transaction. - t := &transaction{} - req := &pb.BeginTransactionRequest{ - App: proto.String(FullyQualifiedAppID(c)), - } - if xg { - req.AllowMultipleEg = proto.Bool(true) - } - if err := Call(c, "datastore_v3", "BeginTransaction", req, &t.transaction); err != nil { - return err - } - - // Call f, rolling back the transaction if f returns a non-nil error, or panics. - // The panic is not recovered. - defer func() { - if t.finished { - return - } - t.finished = true - // Ignore the error return value, since we are already returning a non-nil - // error (or we're panicking). - Call(c, "datastore_v3", "Rollback", &t.transaction, &basepb.VoidProto{}) - }() - if err := f(withTransaction(c, t)); err != nil { - return err - } - t.finished = true - - // Commit the transaction. - res := &pb.CommitResponse{} - err := Call(c, "datastore_v3", "Commit", &t.transaction, res) - if ae, ok := err.(*APIError); ok { - /* TODO: restore this conditional - if appengine.IsDevAppServer() { - */ - // The Python Dev AppServer raises an ApplicationError with error code 2 (which is - // Error.CONCURRENT_TRANSACTION) and message "Concurrency exception.". - if ae.Code == int32(pb.Error_BAD_REQUEST) && ae.Detail == "ApplicationError: 2 Concurrency exception." { - return ErrConcurrentTransaction - } - if ae.Code == int32(pb.Error_CONCURRENT_TRANSACTION) { - return ErrConcurrentTransaction - } - } - return err -} diff --git a/Godeps/_workspace/src/google.golang.org/appengine/namespace.go b/Godeps/_workspace/src/google.golang.org/appengine/namespace.go deleted file mode 100644 index 21860ca08..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/namespace.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2012 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package appengine - -import ( - "fmt" - "regexp" - - "golang.org/x/net/context" - - "google.golang.org/appengine/internal" -) - -// Namespace returns a replacement context that operates within the given namespace. -func Namespace(c context.Context, namespace string) (context.Context, error) { - if !validNamespace.MatchString(namespace) { - return nil, fmt.Errorf("appengine: namespace %q does not match /%s/", namespace, validNamespace) - } - return internal.NamespacedContext(c, namespace), nil -} - -// validNamespace matches valid namespace names. -var validNamespace = regexp.MustCompile(`^[0-9A-Za-z._-]{0,100}$`) diff --git a/Godeps/_workspace/src/google.golang.org/appengine/timeout.go b/Godeps/_workspace/src/google.golang.org/appengine/timeout.go deleted file mode 100644 index 05642a992..000000000 --- a/Godeps/_workspace/src/google.golang.org/appengine/timeout.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2013 Google Inc. All rights reserved. -// Use of this source code is governed by the Apache 2.0 -// license that can be found in the LICENSE file. - -package appengine - -import "golang.org/x/net/context" - -// IsTimeoutError reports whether err is a timeout error. -func IsTimeoutError(err error) bool { - if err == context.DeadlineExceeded { - return true - } - if t, ok := err.(interface { - IsTimeout() bool - }); ok { - return t.IsTimeout() - } - return false -} diff --git a/Godeps/_workspace/src/google.golang.org/cloud/LICENSE b/Godeps/_workspace/src/google.golang.org/cloud/LICENSE deleted file mode 100644 index a4c5efd82..000000000 --- a/Godeps/_workspace/src/google.golang.org/cloud/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (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 2014 Google Inc. - - 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/Godeps/_workspace/src/google.golang.org/cloud/compute/metadata/metadata.go b/Godeps/_workspace/src/google.golang.org/cloud/compute/metadata/metadata.go deleted file mode 100644 index a3daf943a..000000000 --- a/Godeps/_workspace/src/google.golang.org/cloud/compute/metadata/metadata.go +++ /dev/null @@ -1,332 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package metadata provides access to Google Compute Engine (GCE) -// metadata and API service accounts. -// -// This package is a wrapper around the GCE metadata service, -// as documented at https://developers.google.com/compute/docs/metadata. -package metadata - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/url" - "os" - "strings" - "sync" - "time" - - "google.golang.org/cloud/internal" -) - -type cachedValue struct { - k string - trim bool - mu sync.Mutex - v string -} - -var ( - projID = &cachedValue{k: "project/project-id", trim: true} - projNum = &cachedValue{k: "project/numeric-project-id", trim: true} - instID = &cachedValue{k: "instance/id", trim: true} -) - -var metaClient = &http.Client{ - Transport: &internal.Transport{ - Base: &http.Transport{ - Dial: (&net.Dialer{ - Timeout: 750 * time.Millisecond, - KeepAlive: 30 * time.Second, - }).Dial, - ResponseHeaderTimeout: 750 * time.Millisecond, - }, - }, -} - -// NotDefinedError is returned when requested metadata is not defined. -// -// The underlying string is the suffix after "/computeMetadata/v1/". -// -// This error is not returned if the value is defined to be the empty -// string. -type NotDefinedError string - -func (suffix NotDefinedError) Error() string { - return fmt.Sprintf("metadata: GCE metadata %q not defined", string(suffix)) -} - -// Get returns a value from the metadata service. -// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/". -// -// If the GCE_METADATA_HOST environment variable is not defined, a default of -// 169.254.169.254 will be used instead. -// -// If the requested metadata is not defined, the returned error will -// be of type NotDefinedError. -func Get(suffix string) (string, error) { - val, _, err := getETag(suffix) - return val, err -} - -// getETag returns a value from the metadata service as well as the associated -// ETag. This func is otherwise equivalent to Get. -func getETag(suffix string) (value, etag string, err error) { - // Using a fixed IP makes it very difficult to spoof the metadata service in - // a container, which is an important use-case for local testing of cloud - // deployments. To enable spoofing of the metadata service, the environment - // variable GCE_METADATA_HOST is first inspected to decide where metadata - // requests shall go. - host := os.Getenv("GCE_METADATA_HOST") - if host == "" { - // Using 169.254.169.254 instead of "metadata" here because Go - // binaries built with the "netgo" tag and without cgo won't - // know the search suffix for "metadata" is - // ".google.internal", and this IP address is documented as - // being stable anyway. - host = "169.254.169.254" - } - url := "http://" + host + "/computeMetadata/v1/" + suffix - req, _ := http.NewRequest("GET", url, nil) - req.Header.Set("Metadata-Flavor", "Google") - res, err := metaClient.Do(req) - if err != nil { - return "", "", err - } - defer res.Body.Close() - if res.StatusCode == http.StatusNotFound { - return "", "", NotDefinedError(suffix) - } - if res.StatusCode != 200 { - return "", "", fmt.Errorf("status code %d trying to fetch %s", res.StatusCode, url) - } - all, err := ioutil.ReadAll(res.Body) - if err != nil { - return "", "", err - } - return string(all), res.Header.Get("Etag"), nil -} - -func getTrimmed(suffix string) (s string, err error) { - s, err = Get(suffix) - s = strings.TrimSpace(s) - return -} - -func (c *cachedValue) get() (v string, err error) { - defer c.mu.Unlock() - c.mu.Lock() - if c.v != "" { - return c.v, nil - } - if c.trim { - v, err = getTrimmed(c.k) - } else { - v, err = Get(c.k) - } - if err == nil { - c.v = v - } - return -} - -var onGCE struct { - sync.Mutex - set bool - v bool -} - -// OnGCE reports whether this process is running on Google Compute Engine. -func OnGCE() bool { - defer onGCE.Unlock() - onGCE.Lock() - if onGCE.set { - return onGCE.v - } - onGCE.set = true - - // We use the DNS name of the metadata service here instead of the IP address - // because we expect that to fail faster in the not-on-GCE case. - res, err := metaClient.Get("http://metadata.google.internal") - if err != nil { - return false - } - onGCE.v = res.Header.Get("Metadata-Flavor") == "Google" - return onGCE.v -} - -// Subscribe subscribes to a value from the metadata service. -// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/". -// The suffix may contain query parameters. -// -// Subscribe calls fn with the latest metadata value indicated by the provided -// suffix. If the metadata value is deleted, fn is called with the empty string -// and ok false. Subscribe blocks until fn returns a non-nil error or the value -// is deleted. Subscribe returns the error value returned from the last call to -// fn, which may be nil when ok == false. -func Subscribe(suffix string, fn func(v string, ok bool) error) error { - const failedSubscribeSleep = time.Second * 5 - - // First check to see if the metadata value exists at all. - val, lastETag, err := getETag(suffix) - if err != nil { - return err - } - - if err := fn(val, true); err != nil { - return err - } - - ok := true - if strings.ContainsRune(suffix, '?') { - suffix += "&wait_for_change=true&last_etag=" - } else { - suffix += "?wait_for_change=true&last_etag=" - } - for { - val, etag, err := getETag(suffix + url.QueryEscape(lastETag)) - if err != nil { - if _, deleted := err.(NotDefinedError); !deleted { - time.Sleep(failedSubscribeSleep) - continue // Retry on other errors. - } - ok = false - } - lastETag = etag - - if err := fn(val, ok); err != nil || !ok { - return err - } - } -} - -// ProjectID returns the current instance's project ID string. -func ProjectID() (string, error) { return projID.get() } - -// NumericProjectID returns the current instance's numeric project ID. -func NumericProjectID() (string, error) { return projNum.get() } - -// InternalIP returns the instance's primary internal IP address. -func InternalIP() (string, error) { - return getTrimmed("instance/network-interfaces/0/ip") -} - -// ExternalIP returns the instance's primary external (public) IP address. -func ExternalIP() (string, error) { - return getTrimmed("instance/network-interfaces/0/access-configs/0/external-ip") -} - -// Hostname returns the instance's hostname. This will be of the form -// ".c..internal". -func Hostname() (string, error) { - return getTrimmed("instance/hostname") -} - -// InstanceTags returns the list of user-defined instance tags, -// assigned when initially creating a GCE instance. -func InstanceTags() ([]string, error) { - var s []string - j, err := Get("instance/tags") - if err != nil { - return nil, err - } - if err := json.NewDecoder(strings.NewReader(j)).Decode(&s); err != nil { - return nil, err - } - return s, nil -} - -// InstanceID returns the current VM's numeric instance ID. -func InstanceID() (string, error) { - return instID.get() -} - -// InstanceName returns the current VM's instance ID string. -func InstanceName() (string, error) { - host, err := Hostname() - if err != nil { - return "", err - } - return strings.Split(host, ".")[0], nil -} - -// Zone returns the current VM's zone, such as "us-central1-b". -func Zone() (string, error) { - zone, err := getTrimmed("instance/zone") - // zone is of the form "projects//zones/". - if err != nil { - return "", err - } - return zone[strings.LastIndex(zone, "/")+1:], nil -} - -// InstanceAttributes returns the list of user-defined attributes, -// assigned when initially creating a GCE VM instance. The value of an -// attribute can be obtained with InstanceAttributeValue. -func InstanceAttributes() ([]string, error) { return lines("instance/attributes/") } - -// ProjectAttributes returns the list of user-defined attributes -// applying to the project as a whole, not just this VM. The value of -// an attribute can be obtained with ProjectAttributeValue. -func ProjectAttributes() ([]string, error) { return lines("project/attributes/") } - -func lines(suffix string) ([]string, error) { - j, err := Get(suffix) - if err != nil { - return nil, err - } - s := strings.Split(strings.TrimSpace(j), "\n") - for i := range s { - s[i] = strings.TrimSpace(s[i]) - } - return s, nil -} - -// InstanceAttributeValue returns the value of the provided VM -// instance attribute. -// -// If the requested attribute is not defined, the returned error will -// be of type NotDefinedError. -// -// InstanceAttributeValue may return ("", nil) if the attribute was -// defined to be the empty string. -func InstanceAttributeValue(attr string) (string, error) { - return Get("instance/attributes/" + attr) -} - -// ProjectAttributeValue returns the value of the provided -// project attribute. -// -// If the requested attribute is not defined, the returned error will -// be of type NotDefinedError. -// -// ProjectAttributeValue may return ("", nil) if the attribute was -// defined to be the empty string. -func ProjectAttributeValue(attr string) (string, error) { - return Get("project/attributes/" + attr) -} - -// Scopes returns the service account scopes for the given account. -// The account may be empty or the string "default" to use the instance's -// main account. -func Scopes(serviceAccount string) ([]string, error) { - if serviceAccount == "" { - serviceAccount = "default" - } - return lines("instance/service-accounts/" + serviceAccount + "/scopes") -} diff --git a/Godeps/_workspace/src/google.golang.org/cloud/internal/cloud.go b/Godeps/_workspace/src/google.golang.org/cloud/internal/cloud.go deleted file mode 100644 index 59428803d..000000000 --- a/Godeps/_workspace/src/google.golang.org/cloud/internal/cloud.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package internal provides support for the cloud packages. -// -// Users should not import this package directly. -package internal - -import ( - "fmt" - "net/http" - "sync" - - "golang.org/x/net/context" -) - -type contextKey struct{} - -func WithContext(parent context.Context, projID string, c *http.Client) context.Context { - if c == nil { - panic("nil *http.Client passed to WithContext") - } - if projID == "" { - panic("empty project ID passed to WithContext") - } - return context.WithValue(parent, contextKey{}, &cloudContext{ - ProjectID: projID, - HTTPClient: c, - }) -} - -const userAgent = "gcloud-golang/0.1" - -type cloudContext struct { - ProjectID string - HTTPClient *http.Client - - mu sync.Mutex // guards svc - svc map[string]interface{} // e.g. "storage" => *rawStorage.Service -} - -// Service returns the result of the fill function if it's never been -// called before for the given name (which is assumed to be an API -// service name, like "datastore"). If it has already been cached, the fill -// func is not run. -// It's safe for concurrent use by multiple goroutines. -func Service(ctx context.Context, name string, fill func(*http.Client) interface{}) interface{} { - return cc(ctx).service(name, fill) -} - -func (c *cloudContext) service(name string, fill func(*http.Client) interface{}) interface{} { - c.mu.Lock() - defer c.mu.Unlock() - - if c.svc == nil { - c.svc = make(map[string]interface{}) - } else if v, ok := c.svc[name]; ok { - return v - } - v := fill(c.HTTPClient) - c.svc[name] = v - return v -} - -// Transport is an http.RoundTripper that appends -// Google Cloud client's user-agent to the original -// request's user-agent header. -type Transport struct { - // Base is the actual http.RoundTripper - // requests will use. It must not be nil. - Base http.RoundTripper -} - -// RoundTrip appends a user-agent to the existing user-agent -// header and delegates the request to the base http.RoundTripper. -func (t *Transport) RoundTrip(req *http.Request) (*http.Response, error) { - req = cloneRequest(req) - ua := req.Header.Get("User-Agent") - if ua == "" { - ua = userAgent - } else { - ua = fmt.Sprintf("%s %s", ua, userAgent) - } - req.Header.Set("User-Agent", ua) - return t.Base.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 -} - -func ProjID(ctx context.Context) string { - return cc(ctx).ProjectID -} - -func HTTPClient(ctx context.Context) *http.Client { - return cc(ctx).HTTPClient -} - -// cc returns the internal *cloudContext (cc) state for a context.Context. -// It panics if the user did it wrong. -func cc(ctx context.Context) *cloudContext { - if c, ok := ctx.Value(contextKey{}).(*cloudContext); ok { - return c - } - panic("invalid context.Context type; it should be created with cloud.NewContext") -} diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/.gitignore b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/.gitignore deleted file mode 100644 index 4cd0cbaf4..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -# Setup a Global .gitignore for OS and editor generated files: -# https://help.github.com/articles/ignoring-files -# git config --global core.excludesfile ~/.gitignore_global - -.vagrant -*.sublime-project diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/.travis.yml b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/.travis.yml deleted file mode 100644 index 70988769c..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/.travis.yml +++ /dev/null @@ -1,23 +0,0 @@ -sudo: false -language: go - -go: - - 1.5.2 - -before_script: - - go get -u github.com/golang/lint/golint - -script: - - go test -v --race ./... - -after_script: - - test -z "$(gofmt -s -l -w . | tee /dev/stderr)" - - test -z "$(golint ./... | tee /dev/stderr)" - - go vet ./... - -os: - - linux - - osx - -notifications: - email: false diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/AUTHORS b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/AUTHORS deleted file mode 100644 index 2b9d1fdd6..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/AUTHORS +++ /dev/null @@ -1,40 +0,0 @@ -# Names should be added to this file as -# Name or Organization -# The email address is not required for organizations. - -# You can update this list using the following command: -# -# $ git shortlog -se | awk '{print $2 " " $3 " " $4}' - -# Please keep the list sorted. - -Adrien Bustany -Caleb Spare -Case Nelson -Chris Howey -Christoffer Buchholz -Daniel Wagner-Hall -Dave Cheney -Evan Phoenix -Francisco Souza -Hari haran -John C Barstow -Kelvin Fo -Ken-ichirou MATSUZAWA -Matt Layher -Nathan Youngman -Paul Hammond -Pawel Knap -Pieter Droogendijk -Pursuit92 -Riku Voipio -Rob Figueiredo -Soge Zhang -Tilak Sharma -Travis Cline -Tudor Golubenco -Yukang -bronze1man -debrando -henrikedwards -铁哥 diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/CHANGELOG.md b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/CHANGELOG.md deleted file mode 100644 index d37247e0b..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/CHANGELOG.md +++ /dev/null @@ -1,283 +0,0 @@ -# Changelog - -## v1.2.9 / 2016-01-13 - -kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/go-fsnotify/fsnotify/pull/111) (thanks @bep) - -## v1.2.8 / 2015-12-17 - -* kqueue: fix race condition in Close [#105](https://github.com/go-fsnotify/fsnotify/pull/105) (thanks @djui for reporting the issue and @ppknap for writing a failing test) -* inotify: fix race in test -* enable race detection for continuous integration (Linux, Mac, Windows) - -## v1.2.5 / 2015-10-17 - -* inotify: use epoll_create1 for arm64 support (requires Linux 2.6.27 or later) [#100](https://github.com/go-fsnotify/fsnotify/pull/100) (thanks @suihkulokki) -* inotify: fix path leaks [#73](https://github.com/go-fsnotify/fsnotify/pull/73) (thanks @chamaken) -* kqueue: watch for rename events on subdirectories [#83](https://github.com/go-fsnotify/fsnotify/pull/83) (thanks @guotie) -* kqueue: avoid infinite loops from symlinks cycles [#101](https://github.com/go-fsnotify/fsnotify/pull/101) (thanks @illicitonion) - -## v1.2.1 / 2015-10-14 - -* kqueue: don't watch named pipes [#98](https://github.com/go-fsnotify/fsnotify/pull/98) (thanks @evanphx) - -## v1.2.0 / 2015-02-08 - -* inotify: use epoll to wake up readEvents [#66](https://github.com/go-fsnotify/fsnotify/pull/66) (thanks @PieterD) -* inotify: closing watcher should now always shut down goroutine [#63](https://github.com/go-fsnotify/fsnotify/pull/63) (thanks @PieterD) -* kqueue: close kqueue after removing watches, fixes [#59](https://github.com/go-fsnotify/fsnotify/issues/59) - -## v1.1.1 / 2015-02-05 - -* inotify: Retry read on EINTR [#61](https://github.com/go-fsnotify/fsnotify/issues/61) (thanks @PieterD) - -## v1.1.0 / 2014-12-12 - -* kqueue: rework internals [#43](https://github.com/go-fsnotify/fsnotify/pull/43) - * add low-level functions - * only need to store flags on directories - * less mutexes [#13](https://github.com/go-fsnotify/fsnotify/issues/13) - * done can be an unbuffered channel - * remove calls to os.NewSyscallError -* More efficient string concatenation for Event.String() [#52](https://github.com/go-fsnotify/fsnotify/pull/52) (thanks @mdlayher) -* kqueue: fix regression in rework causing subdirectories to be watched [#48](https://github.com/go-fsnotify/fsnotify/issues/48) -* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/go-fsnotify/fsnotify/issues/51) - -## v1.0.4 / 2014-09-07 - -* kqueue: add dragonfly to the build tags. -* Rename source code files, rearrange code so exported APIs are at the top. -* Add done channel to example code. [#37](https://github.com/go-fsnotify/fsnotify/pull/37) (thanks @chenyukang) - -## v1.0.3 / 2014-08-19 - -* [Fix] Windows MOVED_TO now translates to Create like on BSD and Linux. [#36](https://github.com/go-fsnotify/fsnotify/issues/36) - -## v1.0.2 / 2014-08-17 - -* [Fix] Missing create events on OS X. [#14](https://github.com/go-fsnotify/fsnotify/issues/14) (thanks @zhsso) -* [Fix] Make ./path and path equivalent. (thanks @zhsso) - -## v1.0.0 / 2014-08-15 - -* [API] Remove AddWatch on Windows, use Add. -* Improve documentation for exported identifiers. [#30](https://github.com/go-fsnotify/fsnotify/issues/30) -* Minor updates based on feedback from golint. - -## dev / 2014-07-09 - -* Moved to [github.com/go-fsnotify/fsnotify](https://github.com/go-fsnotify/fsnotify). -* Use os.NewSyscallError instead of returning errno (thanks @hariharan-uno) - -## dev / 2014-07-04 - -* kqueue: fix incorrect mutex used in Close() -* Update example to demonstrate usage of Op. - -## dev / 2014-06-28 - -* [API] Don't set the Write Op for attribute notifications [#4](https://github.com/go-fsnotify/fsnotify/issues/4) -* Fix for String() method on Event (thanks Alex Brainman) -* Don't build on Plan 9 or Solaris (thanks @4ad) - -## dev / 2014-06-21 - -* Events channel of type Event rather than *Event. -* [internal] use syscall constants directly for inotify and kqueue. -* [internal] kqueue: rename events to kevents and fileEvent to event. - -## dev / 2014-06-19 - -* Go 1.3+ required on Windows (uses syscall.ERROR_MORE_DATA internally). -* [internal] remove cookie from Event struct (unused). -* [internal] Event struct has the same definition across every OS. -* [internal] remove internal watch and removeWatch methods. - -## dev / 2014-06-12 - -* [API] Renamed Watch() to Add() and RemoveWatch() to Remove(). -* [API] Pluralized channel names: Events and Errors. -* [API] Renamed FileEvent struct to Event. -* [API] Op constants replace methods like IsCreate(). - -## dev / 2014-06-12 - -* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98) - -## dev / 2014-05-23 - -* [API] Remove current implementation of WatchFlags. - * current implementation doesn't take advantage of OS for efficiency - * provides little benefit over filtering events as they are received, but has extra bookkeeping and mutexes - * no tests for the current implementation - * not fully implemented on Windows [#93](https://github.com/howeyc/fsnotify/issues/93#issuecomment-39285195) - -## v0.9.3 / 2014-12-31 - -* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/go-fsnotify/fsnotify/issues/51) - -## v0.9.2 / 2014-08-17 - -* [Backport] Fix missing create events on OS X. [#14](https://github.com/go-fsnotify/fsnotify/issues/14) (thanks @zhsso) - -## v0.9.1 / 2014-06-12 - -* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98) - -## v0.9.0 / 2014-01-17 - -* IsAttrib() for events that only concern a file's metadata [#79][] (thanks @abustany) -* [Fix] kqueue: fix deadlock [#77][] (thanks @cespare) -* [NOTICE] Development has moved to `code.google.com/p/go.exp/fsnotify` in preparation for inclusion in the Go standard library. - -## v0.8.12 / 2013-11-13 - -* [API] Remove FD_SET and friends from Linux adapter - -## v0.8.11 / 2013-11-02 - -* [Doc] Add Changelog [#72][] (thanks @nathany) -* [Doc] Spotlight and double modify events on OS X [#62][] (reported by @paulhammond) - -## v0.8.10 / 2013-10-19 - -* [Fix] kqueue: remove file watches when parent directory is removed [#71][] (reported by @mdwhatcott) -* [Fix] kqueue: race between Close and readEvents [#70][] (reported by @bernerdschaefer) -* [Doc] specify OS-specific limits in README (thanks @debrando) - -## v0.8.9 / 2013-09-08 - -* [Doc] Contributing (thanks @nathany) -* [Doc] update package path in example code [#63][] (thanks @paulhammond) -* [Doc] GoCI badge in README (Linux only) [#60][] -* [Doc] Cross-platform testing with Vagrant [#59][] (thanks @nathany) - -## v0.8.8 / 2013-06-17 - -* [Fix] Windows: handle `ERROR_MORE_DATA` on Windows [#49][] (thanks @jbowtie) - -## v0.8.7 / 2013-06-03 - -* [API] Make syscall flags internal -* [Fix] inotify: ignore event changes -* [Fix] race in symlink test [#45][] (reported by @srid) -* [Fix] tests on Windows -* lower case error messages - -## v0.8.6 / 2013-05-23 - -* kqueue: Use EVT_ONLY flag on Darwin -* [Doc] Update README with full example - -## v0.8.5 / 2013-05-09 - -* [Fix] inotify: allow monitoring of "broken" symlinks (thanks @tsg) - -## v0.8.4 / 2013-04-07 - -* [Fix] kqueue: watch all file events [#40][] (thanks @ChrisBuchholz) - -## v0.8.3 / 2013-03-13 - -* [Fix] inoitfy/kqueue memory leak [#36][] (reported by @nbkolchin) -* [Fix] kqueue: use fsnFlags for watching a directory [#33][] (reported by @nbkolchin) - -## v0.8.2 / 2013-02-07 - -* [Doc] add Authors -* [Fix] fix data races for map access [#29][] (thanks @fsouza) - -## v0.8.1 / 2013-01-09 - -* [Fix] Windows path separators -* [Doc] BSD License - -## v0.8.0 / 2012-11-09 - -* kqueue: directory watching improvements (thanks @vmirage) -* inotify: add `IN_MOVED_TO` [#25][] (requested by @cpisto) -* [Fix] kqueue: deleting watched directory [#24][] (reported by @jakerr) - -## v0.7.4 / 2012-10-09 - -* [Fix] inotify: fixes from https://codereview.appspot.com/5418045/ (ugorji) -* [Fix] kqueue: preserve watch flags when watching for delete [#21][] (reported by @robfig) -* [Fix] kqueue: watch the directory even if it isn't a new watch (thanks @robfig) -* [Fix] kqueue: modify after recreation of file - -## v0.7.3 / 2012-09-27 - -* [Fix] kqueue: watch with an existing folder inside the watched folder (thanks @vmirage) -* [Fix] kqueue: no longer get duplicate CREATE events - -## v0.7.2 / 2012-09-01 - -* kqueue: events for created directories - -## v0.7.1 / 2012-07-14 - -* [Fix] for renaming files - -## v0.7.0 / 2012-07-02 - -* [Feature] FSNotify flags -* [Fix] inotify: Added file name back to event path - -## v0.6.0 / 2012-06-06 - -* kqueue: watch files after directory created (thanks @tmc) - -## v0.5.1 / 2012-05-22 - -* [Fix] inotify: remove all watches before Close() - -## v0.5.0 / 2012-05-03 - -* [API] kqueue: return errors during watch instead of sending over channel -* kqueue: match symlink behavior on Linux -* inotify: add `DELETE_SELF` (requested by @taralx) -* [Fix] kqueue: handle EINTR (reported by @robfig) -* [Doc] Godoc example [#1][] (thanks @davecheney) - -## v0.4.0 / 2012-03-30 - -* Go 1 released: build with go tool -* [Feature] Windows support using winfsnotify -* Windows does not have attribute change notifications -* Roll attribute notifications into IsModify - -## v0.3.0 / 2012-02-19 - -* kqueue: add files when watch directory - -## v0.2.0 / 2011-12-30 - -* update to latest Go weekly code - -## v0.1.0 / 2011-10-19 - -* kqueue: add watch on file creation to match inotify -* kqueue: create file event -* inotify: ignore `IN_IGNORED` events -* event String() -* linux: common FileEvent functions -* initial commit - -[#79]: https://github.com/howeyc/fsnotify/pull/79 -[#77]: https://github.com/howeyc/fsnotify/pull/77 -[#72]: https://github.com/howeyc/fsnotify/issues/72 -[#71]: https://github.com/howeyc/fsnotify/issues/71 -[#70]: https://github.com/howeyc/fsnotify/issues/70 -[#63]: https://github.com/howeyc/fsnotify/issues/63 -[#62]: https://github.com/howeyc/fsnotify/issues/62 -[#60]: https://github.com/howeyc/fsnotify/issues/60 -[#59]: https://github.com/howeyc/fsnotify/issues/59 -[#49]: https://github.com/howeyc/fsnotify/issues/49 -[#45]: https://github.com/howeyc/fsnotify/issues/45 -[#40]: https://github.com/howeyc/fsnotify/issues/40 -[#36]: https://github.com/howeyc/fsnotify/issues/36 -[#33]: https://github.com/howeyc/fsnotify/issues/33 -[#29]: https://github.com/howeyc/fsnotify/issues/29 -[#25]: https://github.com/howeyc/fsnotify/issues/25 -[#24]: https://github.com/howeyc/fsnotify/issues/24 -[#21]: https://github.com/howeyc/fsnotify/issues/21 diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/CONTRIBUTING.md b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/CONTRIBUTING.md deleted file mode 100644 index 0f377f341..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/CONTRIBUTING.md +++ /dev/null @@ -1,77 +0,0 @@ -# Contributing - -## Issues - -* Request features and report bugs using the [GitHub Issue Tracker](https://github.com/go-fsnotify/fsnotify/issues). -* Please indicate the platform you are using fsnotify on. -* A code example to reproduce the problem is appreciated. - -## Pull Requests - -### Contributor License Agreement - -fsnotify is derived from code in the [golang.org/x/exp](https://godoc.org/golang.org/x/exp) package and it may be included [in the standard library](https://github.com/go-fsnotify/fsnotify/issues/1) in the future. Therefore fsnotify carries the same [LICENSE](https://github.com/go-fsnotify/fsnotify/blob/master/LICENSE) as Go. Contributors retain their copyright, so you need to fill out a short form before we can accept your contribution: [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual). - -Please indicate that you have signed the CLA in your pull request. - -### How fsnotify is Developed - -* Development is done on feature branches. -* Tests are run on BSD, Linux, OS X and Windows. -* Pull requests are reviewed and [applied to master][am] using [hub][]. - * Maintainers may modify or squash commits rather than asking contributors to. -* To issue a new release, the maintainers will: - * Update the CHANGELOG - * Tag a version, which will become available through gopkg.in. - -### How to Fork - -For smooth sailing, always use the original import path. Installing with `go get` makes this easy. - -1. Install from GitHub (`go get -u github.com/go-fsnotify/fsnotify`) -2. Create your feature branch (`git checkout -b my-new-feature`) -3. Ensure everything works and the tests pass (see below) -4. Commit your changes (`git commit -am 'Add some feature'`) - -Contribute upstream: - -1. Fork fsnotify on GitHub -2. Add your remote (`git remote add fork git@github.com:mycompany/repo.git`) -3. Push to the branch (`git push fork my-new-feature`) -4. Create a new Pull Request on GitHub - -This workflow is [thoroughly explained by Katrina Owen](https://blog.splice.com/contributing-open-source-git-repositories-go/). - -### Testing - -fsnotify uses build tags to compile different code on Linux, BSD, OS X, and Windows. - -Before doing a pull request, please do your best to test your changes on multiple platforms, and list which platforms you were able/unable to test on. - -To aid in cross-platform testing there is a Vagrantfile for Linux and BSD. - -* Install [Vagrant](http://www.vagrantup.com/) and [VirtualBox](https://www.virtualbox.org/) -* Setup [Vagrant Gopher](https://github.com/nathany/vagrant-gopher) in your `src` folder. -* Run `vagrant up` from the project folder. You can also setup just one box with `vagrant up linux` or `vagrant up bsd` (note: the BSD box doesn't support Windows hosts at this time, and NFS may prompt for your host OS password) -* Once setup, you can run the test suite on a given OS with a single command `vagrant ssh linux -c 'cd go-fsnotify/fsnotify; go test'`. -* When you're done, you will want to halt or destroy the Vagrant boxes. - -Notice: fsnotify file system events won't trigger in shared folders. The tests get around this limitation by using the /tmp directory. - -Right now there is no equivalent solution for Windows and OS X, but there are Windows VMs [freely available from Microsoft](http://www.modern.ie/en-us/virtualization-tools#downloads). - -### Maintainers - -Help maintaining fsnotify is welcome. To be a maintainer: - -* Submit a pull request and sign the CLA as above. -* You must be able to run the test suite on Mac, Windows, Linux and BSD. - -To keep master clean, the fsnotify project uses the "apply mail" workflow outlined in Nathaniel Talbott's post ["Merge pull request" Considered Harmful][am]. This requires installing [hub][]. - -All code changes should be internal pull requests. - -Releases are tagged using [Semantic Versioning](http://semver.org/). - -[hub]: https://github.com/github/hub -[am]: http://blog.spreedly.com/2014/06/24/merge-pull-request-considered-harmful/#.VGa5yZPF_Zs diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/LICENSE b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/LICENSE deleted file mode 100644 index f21e54080..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2012 The Go Authors. All rights reserved. -Copyright (c) 2012 fsnotify Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/README.md b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/README.md deleted file mode 100644 index f2b432e96..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/README.md +++ /dev/null @@ -1,64 +0,0 @@ -# File system notifications for Go - -[![GoDoc](https://godoc.org/gopkg.in/fsnotify.v1?status.svg)](https://godoc.org/gopkg.in/fsnotify.v1) [![Coverage](http://gocover.io/_badge/github.com/go-fsnotify/fsnotify)](http://gocover.io/github.com/go-fsnotify/fsnotify) - -Go 1.3+ required. - -Cross platform: Windows, Linux, BSD and OS X. - -|Adapter |OS |Status | -|----------|----------|----------| -|inotify |Linux 2.6.27 or later, Android\*|Supported [![Build Status](https://travis-ci.org/go-fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/go-fsnotify/fsnotify)| -|kqueue |BSD, OS X, iOS\*|Supported [![Build Status](https://travis-ci.org/go-fsnotify/fsnotify.svg?branch=master)](https://travis-ci.org/go-fsnotify/fsnotify)| -|ReadDirectoryChangesW|Windows|Supported [![Build status](https://ci.appveyor.com/api/projects/status/ivwjubaih4r0udeh/branch/master?svg=true)](https://ci.appveyor.com/project/NathanYoungman/fsnotify/branch/master)| -|FSEvents |OS X |[Planned](https://github.com/go-fsnotify/fsnotify/issues/11)| -|FEN |Solaris 11 |[Planned](https://github.com/go-fsnotify/fsnotify/issues/12)| -|fanotify |Linux 2.6.37+ | | -|USN Journals |Windows |[Maybe](https://github.com/go-fsnotify/fsnotify/issues/53)| -|Polling |*All* |[Maybe](https://github.com/go-fsnotify/fsnotify/issues/9)| - -\* Android and iOS are untested. - -Please see [the documentation](https://godoc.org/gopkg.in/fsnotify.v1) for usage. Consult the [Wiki](https://github.com/go-fsnotify/fsnotify/wiki) for the FAQ and further information. - -## API stability - -Two major versions of fsnotify exist. - -**[fsnotify.v0](https://gopkg.in/fsnotify.v0)** is API-compatible with [howeyc/fsnotify](https://godoc.org/github.com/howeyc/fsnotify). Bugfixes *may* be backported, but I recommend upgrading to v1. - -```go -import "gopkg.in/fsnotify.v0" -``` - -\* Refer to the package as fsnotify (without the .v0 suffix). - -**[fsnotify.v1](https://gopkg.in/fsnotify.v1)** provides [a new API](https://godoc.org/gopkg.in/fsnotify.v1) based on [this design document](http://goo.gl/MrYxyA). You can import v1 with: - -```go -import "gopkg.in/fsnotify.v1" -``` - -Further API changes are [planned](https://github.com/go-fsnotify/fsnotify/milestones), but a new major revision will be tagged, so you can depend on the v1 API. - -**Master** may have unreleased changes. Use it to test the very latest code or when [contributing][], but don't expect it to remain API-compatible: - -```go -import "github.com/go-fsnotify/fsnotify" -``` - -## Contributing - -Please refer to [CONTRIBUTING][] before opening an issue or pull request. - -## Example - -See [example_test.go](https://github.com/go-fsnotify/fsnotify/blob/master/example_test.go). - -[contributing]: https://github.com/go-fsnotify/fsnotify/blob/master/CONTRIBUTING.md - -## Related Projects - -* [notify](https://github.com/rjeczalik/notify) -* [fsevents](https://github.com/go-fsnotify/fsevents) - diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/fsnotify.go b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/fsnotify.go deleted file mode 100644 index c899ee008..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/fsnotify.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !plan9,!solaris - -// Package fsnotify provides a platform-independent interface for file system notifications. -package fsnotify - -import ( - "bytes" - "fmt" -) - -// Event represents a single file system notification. -type Event struct { - Name string // Relative path to the file or directory. - Op Op // File operation that triggered the event. -} - -// Op describes a set of file operations. -type Op uint32 - -// These are the generalized file operations that can trigger a notification. -const ( - Create Op = 1 << iota - Write - Remove - Rename - Chmod -) - -// String returns a string representation of the event in the form -// "file: REMOVE|WRITE|..." -func (e Event) String() string { - // Use a buffer for efficient string concatenation - var buffer bytes.Buffer - - if e.Op&Create == Create { - buffer.WriteString("|CREATE") - } - if e.Op&Remove == Remove { - buffer.WriteString("|REMOVE") - } - if e.Op&Write == Write { - buffer.WriteString("|WRITE") - } - if e.Op&Rename == Rename { - buffer.WriteString("|RENAME") - } - if e.Op&Chmod == Chmod { - buffer.WriteString("|CHMOD") - } - - // If buffer remains empty, return no event names - if buffer.Len() == 0 { - return fmt.Sprintf("%q: ", e.Name) - } - - // Return a list of event names, with leading pipe character stripped - return fmt.Sprintf("%q: %s", e.Name, buffer.String()[1:]) -} diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/inotify.go b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/inotify.go deleted file mode 100644 index 06f4bba88..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/inotify.go +++ /dev/null @@ -1,324 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux - -package fsnotify - -import ( - "errors" - "fmt" - "io" - "os" - "path/filepath" - "strings" - "sync" - "syscall" - "unsafe" -) - -// Watcher watches a set of files, delivering events to a channel. -type Watcher struct { - Events chan Event - Errors chan error - mu sync.Mutex // Map access - cv *sync.Cond // sync removing on rm_watch with IN_IGNORE - fd int - poller *fdPoller - watches map[string]*watch // Map of inotify watches (key: path) - paths map[int]string // Map of watched paths (key: watch descriptor) - done chan struct{} // Channel for sending a "quit message" to the reader goroutine - doneResp chan struct{} // Channel to respond to Close -} - -// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events. -func NewWatcher() (*Watcher, error) { - // Create inotify fd - fd, errno := syscall.InotifyInit() - if fd == -1 { - return nil, errno - } - // Create epoll - poller, err := newFdPoller(fd) - if err != nil { - syscall.Close(fd) - return nil, err - } - w := &Watcher{ - fd: fd, - poller: poller, - watches: make(map[string]*watch), - paths: make(map[int]string), - Events: make(chan Event), - Errors: make(chan error), - done: make(chan struct{}), - doneResp: make(chan struct{}), - } - w.cv = sync.NewCond(&w.mu) - - go w.readEvents() - return w, nil -} - -func (w *Watcher) isClosed() bool { - select { - case <-w.done: - return true - default: - return false - } -} - -// Close removes all watches and closes the events channel. -func (w *Watcher) Close() error { - if w.isClosed() { - return nil - } - - // Send 'close' signal to goroutine, and set the Watcher to closed. - close(w.done) - - // Wake up goroutine - w.poller.wake() - - // Wait for goroutine to close - <-w.doneResp - - return nil -} - -// Add starts watching the named file or directory (non-recursively). -func (w *Watcher) Add(name string) error { - name = filepath.Clean(name) - if w.isClosed() { - return errors.New("inotify instance already closed") - } - - const agnosticEvents = syscall.IN_MOVED_TO | syscall.IN_MOVED_FROM | - syscall.IN_CREATE | syscall.IN_ATTRIB | syscall.IN_MODIFY | - syscall.IN_MOVE_SELF | syscall.IN_DELETE | syscall.IN_DELETE_SELF - - var flags uint32 = agnosticEvents - - w.mu.Lock() - watchEntry, found := w.watches[name] - w.mu.Unlock() - if found { - watchEntry.flags |= flags - flags |= syscall.IN_MASK_ADD - } - wd, errno := syscall.InotifyAddWatch(w.fd, name, flags) - if wd == -1 { - return errno - } - - w.mu.Lock() - w.watches[name] = &watch{wd: uint32(wd), flags: flags} - w.paths[wd] = name - w.mu.Unlock() - - return nil -} - -// Remove stops watching the named file or directory (non-recursively). -func (w *Watcher) Remove(name string) error { - name = filepath.Clean(name) - - // Fetch the watch. - w.mu.Lock() - defer w.mu.Unlock() - watch, ok := w.watches[name] - - // Remove it from inotify. - if !ok { - return fmt.Errorf("can't remove non-existent inotify watch for: %s", name) - } - // inotify_rm_watch will return EINVAL if the file has been deleted; - // the inotify will already have been removed. - // watches and pathes are deleted in ignoreLinux() implicitly and asynchronously - // by calling inotify_rm_watch() below. e.g. readEvents() goroutine receives IN_IGNORE - // so that EINVAL means that the wd is being rm_watch()ed or its file removed - // by another thread and we have not received IN_IGNORE event. - success, errno := syscall.InotifyRmWatch(w.fd, watch.wd) - if success == -1 { - // TODO: Perhaps it's not helpful to return an error here in every case. - // the only two possible errors are: - // EBADF, which happens when w.fd is not a valid file descriptor of any kind. - // EINVAL, which is when fd is not an inotify descriptor or wd is not a valid watch descriptor. - // Watch descriptors are invalidated when they are removed explicitly or implicitly; - // explicitly by inotify_rm_watch, implicitly when the file they are watching is deleted. - return errno - } - - // wait until ignoreLinux() deleting maps - exists := true - for exists { - w.cv.Wait() - _, exists = w.watches[name] - } - - return nil -} - -type watch struct { - wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall) - flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags) -} - -// readEvents reads from the inotify file descriptor, converts the -// received events into Event objects and sends them via the Events channel -func (w *Watcher) readEvents() { - var ( - buf [syscall.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events - n int // Number of bytes read with read() - errno error // Syscall errno - ok bool // For poller.wait - ) - - defer close(w.doneResp) - defer close(w.Errors) - defer close(w.Events) - defer syscall.Close(w.fd) - defer w.poller.close() - - for { - // See if we have been closed. - if w.isClosed() { - return - } - - ok, errno = w.poller.wait() - if errno != nil { - select { - case w.Errors <- errno: - case <-w.done: - return - } - continue - } - - if !ok { - continue - } - - n, errno = syscall.Read(w.fd, buf[:]) - // If a signal interrupted execution, see if we've been asked to close, and try again. - // http://man7.org/linux/man-pages/man7/signal.7.html : - // "Before Linux 3.8, reads from an inotify(7) file descriptor were not restartable" - if errno == syscall.EINTR { - continue - } - - // syscall.Read might have been woken up by Close. If so, we're done. - if w.isClosed() { - return - } - - if n < syscall.SizeofInotifyEvent { - var err error - if n == 0 { - // If EOF is received. This should really never happen. - err = io.EOF - } else if n < 0 { - // If an error occured while reading. - err = errno - } else { - // Read was too short. - err = errors.New("notify: short read in readEvents()") - } - select { - case w.Errors <- err: - case <-w.done: - return - } - continue - } - - var offset uint32 - // We don't know how many events we just read into the buffer - // While the offset points to at least one whole event... - for offset <= uint32(n-syscall.SizeofInotifyEvent) { - // Point "raw" to the event in the buffer - raw := (*syscall.InotifyEvent)(unsafe.Pointer(&buf[offset])) - - mask := uint32(raw.Mask) - nameLen := uint32(raw.Len) - // If the event happened to the watched directory or the watched file, the kernel - // doesn't append the filename to the event, but we would like to always fill the - // the "Name" field with a valid filename. We retrieve the path of the watch from - // the "paths" map. - w.mu.Lock() - name := w.paths[int(raw.Wd)] - w.mu.Unlock() - if nameLen > 0 { - // Point "bytes" at the first byte of the filename - bytes := (*[syscall.PathMax]byte)(unsafe.Pointer(&buf[offset+syscall.SizeofInotifyEvent])) - // The filename is padded with NULL bytes. TrimRight() gets rid of those. - name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\000") - } - - event := newEvent(name, mask) - - // Send the events that are not ignored on the events channel - if !event.ignoreLinux(w, raw.Wd, mask) { - select { - case w.Events <- event: - case <-w.done: - return - } - } - - // Move to the next event in the buffer - offset += syscall.SizeofInotifyEvent + nameLen - } - } -} - -// Certain types of events can be "ignored" and not sent over the Events -// channel. Such as events marked ignore by the kernel, or MODIFY events -// against files that do not exist. -func (e *Event) ignoreLinux(w *Watcher, wd int32, mask uint32) bool { - // Ignore anything the inotify API says to ignore - if mask&syscall.IN_IGNORED == syscall.IN_IGNORED { - w.mu.Lock() - defer w.mu.Unlock() - name := w.paths[int(wd)] - delete(w.paths, int(wd)) - delete(w.watches, name) - w.cv.Broadcast() - return true - } - - // If the event is not a DELETE or RENAME, the file must exist. - // Otherwise the event is ignored. - // *Note*: this was put in place because it was seen that a MODIFY - // event was sent after the DELETE. This ignores that MODIFY and - // assumes a DELETE will come or has come if the file doesn't exist. - if !(e.Op&Remove == Remove || e.Op&Rename == Rename) { - _, statErr := os.Lstat(e.Name) - return os.IsNotExist(statErr) - } - return false -} - -// newEvent returns an platform-independent Event based on an inotify mask. -func newEvent(name string, mask uint32) Event { - e := Event{Name: name} - if mask&syscall.IN_CREATE == syscall.IN_CREATE || mask&syscall.IN_MOVED_TO == syscall.IN_MOVED_TO { - e.Op |= Create - } - if mask&syscall.IN_DELETE_SELF == syscall.IN_DELETE_SELF || mask&syscall.IN_DELETE == syscall.IN_DELETE { - e.Op |= Remove - } - if mask&syscall.IN_MODIFY == syscall.IN_MODIFY { - e.Op |= Write - } - if mask&syscall.IN_MOVE_SELF == syscall.IN_MOVE_SELF || mask&syscall.IN_MOVED_FROM == syscall.IN_MOVED_FROM { - e.Op |= Rename - } - if mask&syscall.IN_ATTRIB == syscall.IN_ATTRIB { - e.Op |= Chmod - } - return e -} diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/inotify_poller.go b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/inotify_poller.go deleted file mode 100644 index 23a5ca146..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/inotify_poller.go +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux - -package fsnotify - -import ( - "errors" - "syscall" -) - -type fdPoller struct { - fd int // File descriptor (as returned by the inotify_init() syscall) - epfd int // Epoll file descriptor - pipe [2]int // Pipe for waking up -} - -func emptyPoller(fd int) *fdPoller { - poller := new(fdPoller) - poller.fd = fd - poller.epfd = -1 - poller.pipe[0] = -1 - poller.pipe[1] = -1 - return poller -} - -// Create a new inotify poller. -// This creates an inotify handler, and an epoll handler. -func newFdPoller(fd int) (*fdPoller, error) { - var errno error - poller := emptyPoller(fd) - defer func() { - if errno != nil { - poller.close() - } - }() - poller.fd = fd - - // Create epoll fd - poller.epfd, errno = syscall.EpollCreate1(0) - if poller.epfd == -1 { - return nil, errno - } - // Create pipe; pipe[0] is the read end, pipe[1] the write end. - errno = syscall.Pipe2(poller.pipe[:], syscall.O_NONBLOCK) - if errno != nil { - return nil, errno - } - - // Register inotify fd with epoll - event := syscall.EpollEvent{ - Fd: int32(poller.fd), - Events: syscall.EPOLLIN, - } - errno = syscall.EpollCtl(poller.epfd, syscall.EPOLL_CTL_ADD, poller.fd, &event) - if errno != nil { - return nil, errno - } - - // Register pipe fd with epoll - event = syscall.EpollEvent{ - Fd: int32(poller.pipe[0]), - Events: syscall.EPOLLIN, - } - errno = syscall.EpollCtl(poller.epfd, syscall.EPOLL_CTL_ADD, poller.pipe[0], &event) - if errno != nil { - return nil, errno - } - - return poller, nil -} - -// Wait using epoll. -// Returns true if something is ready to be read, -// false if there is not. -func (poller *fdPoller) wait() (bool, error) { - // 3 possible events per fd, and 2 fds, makes a maximum of 6 events. - // I don't know whether epoll_wait returns the number of events returned, - // or the total number of events ready. - // I decided to catch both by making the buffer one larger than the maximum. - events := make([]syscall.EpollEvent, 7) - for { - n, errno := syscall.EpollWait(poller.epfd, events, -1) - if n == -1 { - if errno == syscall.EINTR { - continue - } - return false, errno - } - if n == 0 { - // If there are no events, try again. - continue - } - if n > 6 { - // This should never happen. More events were returned than should be possible. - return false, errors.New("epoll_wait returned more events than I know what to do with") - } - ready := events[:n] - epollhup := false - epollerr := false - epollin := false - for _, event := range ready { - if event.Fd == int32(poller.fd) { - if event.Events&syscall.EPOLLHUP != 0 { - // This should not happen, but if it does, treat it as a wakeup. - epollhup = true - } - if event.Events&syscall.EPOLLERR != 0 { - // If an error is waiting on the file descriptor, we should pretend - // something is ready to read, and let syscall.Read pick up the error. - epollerr = true - } - if event.Events&syscall.EPOLLIN != 0 { - // There is data to read. - epollin = true - } - } - if event.Fd == int32(poller.pipe[0]) { - if event.Events&syscall.EPOLLHUP != 0 { - // Write pipe descriptor was closed, by us. This means we're closing down the - // watcher, and we should wake up. - } - if event.Events&syscall.EPOLLERR != 0 { - // If an error is waiting on the pipe file descriptor. - // This is an absolute mystery, and should never ever happen. - return false, errors.New("Error on the pipe descriptor.") - } - if event.Events&syscall.EPOLLIN != 0 { - // This is a regular wakeup, so we have to clear the buffer. - err := poller.clearWake() - if err != nil { - return false, err - } - } - } - } - - if epollhup || epollerr || epollin { - return true, nil - } - return false, nil - } -} - -// Close the write end of the poller. -func (poller *fdPoller) wake() error { - buf := make([]byte, 1) - n, errno := syscall.Write(poller.pipe[1], buf) - if n == -1 { - if errno == syscall.EAGAIN { - // Buffer is full, poller will wake. - return nil - } - return errno - } - return nil -} - -func (poller *fdPoller) clearWake() error { - // You have to be woken up a LOT in order to get to 100! - buf := make([]byte, 100) - n, errno := syscall.Read(poller.pipe[0], buf) - if n == -1 { - if errno == syscall.EAGAIN { - // Buffer is empty, someone else cleared our wake. - return nil - } - return errno - } - return nil -} - -// Close all poller file descriptors, but not the one passed to it. -func (poller *fdPoller) close() { - if poller.pipe[1] != -1 { - syscall.Close(poller.pipe[1]) - } - if poller.pipe[0] != -1 { - syscall.Close(poller.pipe[0]) - } - if poller.epfd != -1 { - syscall.Close(poller.epfd) - } -} diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/kqueue.go b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/kqueue.go deleted file mode 100644 index b8ea30846..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/kqueue.go +++ /dev/null @@ -1,502 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build freebsd openbsd netbsd dragonfly darwin - -package fsnotify - -import ( - "errors" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "sync" - "syscall" - "time" -) - -// Watcher watches a set of files, delivering events to a channel. -type Watcher struct { - Events chan Event - Errors chan error - done chan bool // Channel for sending a "quit message" to the reader goroutine - - kq int // File descriptor (as returned by the kqueue() syscall). - - mu sync.Mutex // Protects access to watcher data - watches map[string]int // Map of watched file descriptors (key: path). - externalWatches map[string]bool // Map of watches added by user of the library. - dirFlags map[string]uint32 // Map of watched directories to fflags used in kqueue. - paths map[int]pathInfo // Map file descriptors to path names for processing kqueue events. - fileExists map[string]bool // Keep track of if we know this file exists (to stop duplicate create events). - isClosed bool // Set to true when Close() is first called -} - -type pathInfo struct { - name string - isDir bool -} - -// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events. -func NewWatcher() (*Watcher, error) { - kq, err := kqueue() - if err != nil { - return nil, err - } - - w := &Watcher{ - kq: kq, - watches: make(map[string]int), - dirFlags: make(map[string]uint32), - paths: make(map[int]pathInfo), - fileExists: make(map[string]bool), - externalWatches: make(map[string]bool), - Events: make(chan Event), - Errors: make(chan error), - done: make(chan bool), - } - - go w.readEvents() - return w, nil -} - -// Close removes all watches and closes the events channel. -func (w *Watcher) Close() error { - w.mu.Lock() - if w.isClosed { - w.mu.Unlock() - return nil - } - w.isClosed = true - w.mu.Unlock() - - // copy paths to remove while locked - w.mu.Lock() - var pathsToRemove = make([]string, 0, len(w.watches)) - for name := range w.watches { - pathsToRemove = append(pathsToRemove, name) - } - w.mu.Unlock() - // unlock before calling Remove, which also locks - - var err error - for _, name := range pathsToRemove { - if e := w.Remove(name); e != nil && err == nil { - err = e - } - } - - // Send "quit" message to the reader goroutine: - w.done <- true - - return nil -} - -// Add starts watching the named file or directory (non-recursively). -func (w *Watcher) Add(name string) error { - w.mu.Lock() - w.externalWatches[name] = true - w.mu.Unlock() - _, err := w.addWatch(name, noteAllEvents) - return err -} - -// Remove stops watching the the named file or directory (non-recursively). -func (w *Watcher) Remove(name string) error { - name = filepath.Clean(name) - w.mu.Lock() - watchfd, ok := w.watches[name] - w.mu.Unlock() - if !ok { - return fmt.Errorf("can't remove non-existent kevent watch for: %s", name) - } - - const registerRemove = syscall.EV_DELETE - if err := register(w.kq, []int{watchfd}, registerRemove, 0); err != nil { - return err - } - - syscall.Close(watchfd) - - w.mu.Lock() - isDir := w.paths[watchfd].isDir - delete(w.watches, name) - delete(w.paths, watchfd) - delete(w.dirFlags, name) - w.mu.Unlock() - - // Find all watched paths that are in this directory that are not external. - if isDir { - var pathsToRemove []string - w.mu.Lock() - for _, path := range w.paths { - wdir, _ := filepath.Split(path.name) - if filepath.Clean(wdir) == name { - if !w.externalWatches[path.name] { - pathsToRemove = append(pathsToRemove, path.name) - } - } - } - w.mu.Unlock() - for _, name := range pathsToRemove { - // Since these are internal, not much sense in propagating error - // to the user, as that will just confuse them with an error about - // a path they did not explicitly watch themselves. - w.Remove(name) - } - } - - return nil -} - -// Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE) -const noteAllEvents = syscall.NOTE_DELETE | syscall.NOTE_WRITE | syscall.NOTE_ATTRIB | syscall.NOTE_RENAME - -// keventWaitTime to block on each read from kevent -var keventWaitTime = durationToTimespec(100 * time.Millisecond) - -// addWatch adds name to the watched file set. -// The flags are interpreted as described in kevent(2). -// Returns the real path to the file which was added, if any, which may be different from the one passed in the case of symlinks. -func (w *Watcher) addWatch(name string, flags uint32) (string, error) { - var isDir bool - // Make ./name and name equivalent - name = filepath.Clean(name) - - w.mu.Lock() - if w.isClosed { - w.mu.Unlock() - return "", errors.New("kevent instance already closed") - } - watchfd, alreadyWatching := w.watches[name] - // We already have a watch, but we can still override flags. - if alreadyWatching { - isDir = w.paths[watchfd].isDir - } - w.mu.Unlock() - - if !alreadyWatching { - fi, err := os.Lstat(name) - if err != nil { - return "", err - } - - // Don't watch sockets. - if fi.Mode()&os.ModeSocket == os.ModeSocket { - return "", nil - } - - // Don't watch named pipes. - if fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe { - return "", nil - } - - // Follow Symlinks - // Unfortunately, Linux can add bogus symlinks to watch list without - // issue, and Windows can't do symlinks period (AFAIK). To maintain - // consistency, we will act like everything is fine. There will simply - // be no file events for broken symlinks. - // Hence the returns of nil on errors. - if fi.Mode()&os.ModeSymlink == os.ModeSymlink { - name, err = filepath.EvalSymlinks(name) - if err != nil { - return "", nil - } - - w.mu.Lock() - _, alreadyWatching = w.watches[name] - w.mu.Unlock() - - if alreadyWatching { - return name, nil - } - - fi, err = os.Lstat(name) - if err != nil { - return "", nil - } - } - - watchfd, err = syscall.Open(name, openMode, 0700) - if watchfd == -1 { - return "", err - } - - isDir = fi.IsDir() - } - - const registerAdd = syscall.EV_ADD | syscall.EV_CLEAR | syscall.EV_ENABLE - if err := register(w.kq, []int{watchfd}, registerAdd, flags); err != nil { - syscall.Close(watchfd) - return "", err - } - - if !alreadyWatching { - w.mu.Lock() - w.watches[name] = watchfd - w.paths[watchfd] = pathInfo{name: name, isDir: isDir} - w.mu.Unlock() - } - - if isDir { - // Watch the directory if it has not been watched before, - // or if it was watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles) - w.mu.Lock() - - watchDir := (flags&syscall.NOTE_WRITE) == syscall.NOTE_WRITE && - (!alreadyWatching || (w.dirFlags[name]&syscall.NOTE_WRITE) != syscall.NOTE_WRITE) - // Store flags so this watch can be updated later - w.dirFlags[name] = flags - w.mu.Unlock() - - if watchDir { - if err := w.watchDirectoryFiles(name); err != nil { - return "", err - } - } - } - return name, nil -} - -// readEvents reads from kqueue and converts the received kevents into -// Event values that it sends down the Events channel. -func (w *Watcher) readEvents() { - eventBuffer := make([]syscall.Kevent_t, 10) - - for { - // See if there is a message on the "done" channel - select { - case <-w.done: - err := syscall.Close(w.kq) - if err != nil { - w.Errors <- err - } - close(w.Events) - close(w.Errors) - return - default: - } - - // Get new events - kevents, err := read(w.kq, eventBuffer, &keventWaitTime) - // EINTR is okay, the syscall was interrupted before timeout expired. - if err != nil && err != syscall.EINTR { - w.Errors <- err - continue - } - - // Flush the events we received to the Events channel - for len(kevents) > 0 { - kevent := &kevents[0] - watchfd := int(kevent.Ident) - mask := uint32(kevent.Fflags) - w.mu.Lock() - path := w.paths[watchfd] - w.mu.Unlock() - event := newEvent(path.name, mask) - - if path.isDir && !(event.Op&Remove == Remove) { - // Double check to make sure the directory exists. This can happen when - // we do a rm -fr on a recursively watched folders and we receive a - // modification event first but the folder has been deleted and later - // receive the delete event - if _, err := os.Lstat(event.Name); os.IsNotExist(err) { - // mark is as delete event - event.Op |= Remove - } - } - - if event.Op&Rename == Rename || event.Op&Remove == Remove { - w.Remove(event.Name) - w.mu.Lock() - delete(w.fileExists, event.Name) - w.mu.Unlock() - } - - if path.isDir && event.Op&Write == Write && !(event.Op&Remove == Remove) { - w.sendDirectoryChangeEvents(event.Name) - } else { - // Send the event on the Events channel - w.Events <- event - } - - if event.Op&Remove == Remove { - // Look for a file that may have overwritten this. - // For example, mv f1 f2 will delete f2, then create f2. - if path.isDir { - fileDir := filepath.Clean(event.Name) - w.mu.Lock() - _, found := w.watches[fileDir] - w.mu.Unlock() - if found { - // make sure the directory exists before we watch for changes. When we - // do a recursive watch and perform rm -fr, the parent directory might - // have gone missing, ignore the missing directory and let the - // upcoming delete event remove the watch from the parent directory. - if _, err := os.Lstat(fileDir); err == nil { - w.sendDirectoryChangeEvents(fileDir) - } - } - } else { - filePath := filepath.Clean(event.Name) - if fileInfo, err := os.Lstat(filePath); err == nil { - w.sendFileCreatedEventIfNew(filePath, fileInfo) - } - } - } - - // Move to next event - kevents = kevents[1:] - } - } -} - -// newEvent returns an platform-independent Event based on kqueue Fflags. -func newEvent(name string, mask uint32) Event { - e := Event{Name: name} - if mask&syscall.NOTE_DELETE == syscall.NOTE_DELETE { - e.Op |= Remove - } - if mask&syscall.NOTE_WRITE == syscall.NOTE_WRITE { - e.Op |= Write - } - if mask&syscall.NOTE_RENAME == syscall.NOTE_RENAME { - e.Op |= Rename - } - if mask&syscall.NOTE_ATTRIB == syscall.NOTE_ATTRIB { - e.Op |= Chmod - } - return e -} - -func newCreateEvent(name string) Event { - return Event{Name: name, Op: Create} -} - -// watchDirectoryFiles to mimic inotify when adding a watch on a directory -func (w *Watcher) watchDirectoryFiles(dirPath string) error { - // Get all files - files, err := ioutil.ReadDir(dirPath) - if err != nil { - return err - } - - for _, fileInfo := range files { - filePath := filepath.Join(dirPath, fileInfo.Name()) - filePath, err = w.internalWatch(filePath, fileInfo) - if err != nil { - return err - } - - w.mu.Lock() - w.fileExists[filePath] = true - w.mu.Unlock() - } - - return nil -} - -// sendDirectoryEvents searches the directory for newly created files -// and sends them over the event channel. This functionality is to have -// the BSD version of fsnotify match Linux inotify which provides a -// create event for files created in a watched directory. -func (w *Watcher) sendDirectoryChangeEvents(dirPath string) { - // Get all files - files, err := ioutil.ReadDir(dirPath) - if err != nil { - w.Errors <- err - } - - // Search for new files - for _, fileInfo := range files { - filePath := filepath.Join(dirPath, fileInfo.Name()) - err := w.sendFileCreatedEventIfNew(filePath, fileInfo) - - if err != nil { - return - } - } -} - -// sendFileCreatedEvent sends a create event if the file isn't already being tracked. -func (w *Watcher) sendFileCreatedEventIfNew(filePath string, fileInfo os.FileInfo) (err error) { - w.mu.Lock() - _, doesExist := w.fileExists[filePath] - w.mu.Unlock() - if !doesExist { - // Send create event - w.Events <- newCreateEvent(filePath) - } - - // like watchDirectoryFiles (but without doing another ReadDir) - filePath, err = w.internalWatch(filePath, fileInfo) - if err != nil { - return err - } - - w.mu.Lock() - w.fileExists[filePath] = true - w.mu.Unlock() - - return nil -} - -func (w *Watcher) internalWatch(name string, fileInfo os.FileInfo) (string, error) { - if fileInfo.IsDir() { - // mimic Linux providing delete events for subdirectories - // but preserve the flags used if currently watching subdirectory - w.mu.Lock() - flags := w.dirFlags[name] - w.mu.Unlock() - - flags |= syscall.NOTE_DELETE | syscall.NOTE_RENAME - return w.addWatch(name, flags) - } - - // watch file to mimic Linux inotify - return w.addWatch(name, noteAllEvents) -} - -// kqueue creates a new kernel event queue and returns a descriptor. -func kqueue() (kq int, err error) { - kq, err = syscall.Kqueue() - if kq == -1 { - return kq, err - } - return kq, nil -} - -// register events with the queue -func register(kq int, fds []int, flags int, fflags uint32) error { - changes := make([]syscall.Kevent_t, len(fds)) - - for i, fd := range fds { - // SetKevent converts int to the platform-specific types: - syscall.SetKevent(&changes[i], fd, syscall.EVFILT_VNODE, flags) - changes[i].Fflags = fflags - } - - // register the events - success, err := syscall.Kevent(kq, changes, nil, nil) - if success == -1 { - return err - } - return nil -} - -// read retrieves pending events, or waits until an event occurs. -// A timeout of nil blocks indefinitely, while 0 polls the queue. -func read(kq int, events []syscall.Kevent_t, timeout *syscall.Timespec) ([]syscall.Kevent_t, error) { - n, err := syscall.Kevent(kq, nil, events, timeout) - if err != nil { - return nil, err - } - return events[0:n], nil -} - -// durationToTimespec prepares a timeout value -func durationToTimespec(d time.Duration) syscall.Timespec { - return syscall.NsecToTimespec(d.Nanoseconds()) -} diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/open_mode_bsd.go b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/open_mode_bsd.go deleted file mode 100644 index c57ccb427..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/open_mode_bsd.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build freebsd openbsd netbsd dragonfly - -package fsnotify - -import "syscall" - -const openMode = syscall.O_NONBLOCK | syscall.O_RDONLY diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/open_mode_darwin.go b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/open_mode_darwin.go deleted file mode 100644 index 174b2c331..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/open_mode_darwin.go +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin - -package fsnotify - -import "syscall" - -// note: this constant is not defined on BSD -const openMode = syscall.O_EVTONLY diff --git a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/windows.go b/Godeps/_workspace/src/gopkg.in/fsnotify.v1/windows.go deleted file mode 100644 index 811585227..000000000 --- a/Godeps/_workspace/src/gopkg.in/fsnotify.v1/windows.go +++ /dev/null @@ -1,561 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build windows - -package fsnotify - -import ( - "errors" - "fmt" - "os" - "path/filepath" - "runtime" - "sync" - "syscall" - "unsafe" -) - -// Watcher watches a set of files, delivering events to a channel. -type Watcher struct { - Events chan Event - Errors chan error - isClosed bool // Set to true when Close() is first called - mu sync.Mutex // Map access - port syscall.Handle // Handle to completion port - watches watchMap // Map of watches (key: i-number) - input chan *input // Inputs to the reader are sent on this channel - quit chan chan<- error -} - -// NewWatcher establishes a new watcher with the underlying OS and begins waiting for events. -func NewWatcher() (*Watcher, error) { - port, e := syscall.CreateIoCompletionPort(syscall.InvalidHandle, 0, 0, 0) - if e != nil { - return nil, os.NewSyscallError("CreateIoCompletionPort", e) - } - w := &Watcher{ - port: port, - watches: make(watchMap), - input: make(chan *input, 1), - Events: make(chan Event, 50), - Errors: make(chan error), - quit: make(chan chan<- error, 1), - } - go w.readEvents() - return w, nil -} - -// Close removes all watches and closes the events channel. -func (w *Watcher) Close() error { - if w.isClosed { - return nil - } - w.isClosed = true - - // Send "quit" message to the reader goroutine - ch := make(chan error) - w.quit <- ch - if err := w.wakeupReader(); err != nil { - return err - } - return <-ch -} - -// Add starts watching the named file or directory (non-recursively). -func (w *Watcher) Add(name string) error { - if w.isClosed { - return errors.New("watcher already closed") - } - in := &input{ - op: opAddWatch, - path: filepath.Clean(name), - flags: sys_FS_ALL_EVENTS, - reply: make(chan error), - } - w.input <- in - if err := w.wakeupReader(); err != nil { - return err - } - return <-in.reply -} - -// Remove stops watching the the named file or directory (non-recursively). -func (w *Watcher) Remove(name string) error { - in := &input{ - op: opRemoveWatch, - path: filepath.Clean(name), - reply: make(chan error), - } - w.input <- in - if err := w.wakeupReader(); err != nil { - return err - } - return <-in.reply -} - -const ( - // Options for AddWatch - sys_FS_ONESHOT = 0x80000000 - sys_FS_ONLYDIR = 0x1000000 - - // Events - sys_FS_ACCESS = 0x1 - sys_FS_ALL_EVENTS = 0xfff - sys_FS_ATTRIB = 0x4 - sys_FS_CLOSE = 0x18 - sys_FS_CREATE = 0x100 - sys_FS_DELETE = 0x200 - sys_FS_DELETE_SELF = 0x400 - sys_FS_MODIFY = 0x2 - sys_FS_MOVE = 0xc0 - sys_FS_MOVED_FROM = 0x40 - sys_FS_MOVED_TO = 0x80 - sys_FS_MOVE_SELF = 0x800 - - // Special events - sys_FS_IGNORED = 0x8000 - sys_FS_Q_OVERFLOW = 0x4000 -) - -func newEvent(name string, mask uint32) Event { - e := Event{Name: name} - if mask&sys_FS_CREATE == sys_FS_CREATE || mask&sys_FS_MOVED_TO == sys_FS_MOVED_TO { - e.Op |= Create - } - if mask&sys_FS_DELETE == sys_FS_DELETE || mask&sys_FS_DELETE_SELF == sys_FS_DELETE_SELF { - e.Op |= Remove - } - if mask&sys_FS_MODIFY == sys_FS_MODIFY { - e.Op |= Write - } - if mask&sys_FS_MOVE == sys_FS_MOVE || mask&sys_FS_MOVE_SELF == sys_FS_MOVE_SELF || mask&sys_FS_MOVED_FROM == sys_FS_MOVED_FROM { - e.Op |= Rename - } - if mask&sys_FS_ATTRIB == sys_FS_ATTRIB { - e.Op |= Chmod - } - return e -} - -const ( - opAddWatch = iota - opRemoveWatch -) - -const ( - provisional uint64 = 1 << (32 + iota) -) - -type input struct { - op int - path string - flags uint32 - reply chan error -} - -type inode struct { - handle syscall.Handle - volume uint32 - index uint64 -} - -type watch struct { - ov syscall.Overlapped - ino *inode // i-number - path string // Directory path - mask uint64 // Directory itself is being watched with these notify flags - names map[string]uint64 // Map of names being watched and their notify flags - rename string // Remembers the old name while renaming a file - buf [4096]byte -} - -type indexMap map[uint64]*watch -type watchMap map[uint32]indexMap - -func (w *Watcher) wakeupReader() error { - e := syscall.PostQueuedCompletionStatus(w.port, 0, 0, nil) - if e != nil { - return os.NewSyscallError("PostQueuedCompletionStatus", e) - } - return nil -} - -func getDir(pathname string) (dir string, err error) { - attr, e := syscall.GetFileAttributes(syscall.StringToUTF16Ptr(pathname)) - if e != nil { - return "", os.NewSyscallError("GetFileAttributes", e) - } - if attr&syscall.FILE_ATTRIBUTE_DIRECTORY != 0 { - dir = pathname - } else { - dir, _ = filepath.Split(pathname) - dir = filepath.Clean(dir) - } - return -} - -func getIno(path string) (ino *inode, err error) { - h, e := syscall.CreateFile(syscall.StringToUTF16Ptr(path), - syscall.FILE_LIST_DIRECTORY, - syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, - nil, syscall.OPEN_EXISTING, - syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OVERLAPPED, 0) - if e != nil { - return nil, os.NewSyscallError("CreateFile", e) - } - var fi syscall.ByHandleFileInformation - if e = syscall.GetFileInformationByHandle(h, &fi); e != nil { - syscall.CloseHandle(h) - return nil, os.NewSyscallError("GetFileInformationByHandle", e) - } - ino = &inode{ - handle: h, - volume: fi.VolumeSerialNumber, - index: uint64(fi.FileIndexHigh)<<32 | uint64(fi.FileIndexLow), - } - return ino, nil -} - -// Must run within the I/O thread. -func (m watchMap) get(ino *inode) *watch { - if i := m[ino.volume]; i != nil { - return i[ino.index] - } - return nil -} - -// Must run within the I/O thread. -func (m watchMap) set(ino *inode, watch *watch) { - i := m[ino.volume] - if i == nil { - i = make(indexMap) - m[ino.volume] = i - } - i[ino.index] = watch -} - -// Must run within the I/O thread. -func (w *Watcher) addWatch(pathname string, flags uint64) error { - dir, err := getDir(pathname) - if err != nil { - return err - } - if flags&sys_FS_ONLYDIR != 0 && pathname != dir { - return nil - } - ino, err := getIno(dir) - if err != nil { - return err - } - w.mu.Lock() - watchEntry := w.watches.get(ino) - w.mu.Unlock() - if watchEntry == nil { - if _, e := syscall.CreateIoCompletionPort(ino.handle, w.port, 0, 0); e != nil { - syscall.CloseHandle(ino.handle) - return os.NewSyscallError("CreateIoCompletionPort", e) - } - watchEntry = &watch{ - ino: ino, - path: dir, - names: make(map[string]uint64), - } - w.mu.Lock() - w.watches.set(ino, watchEntry) - w.mu.Unlock() - flags |= provisional - } else { - syscall.CloseHandle(ino.handle) - } - if pathname == dir { - watchEntry.mask |= flags - } else { - watchEntry.names[filepath.Base(pathname)] |= flags - } - if err = w.startRead(watchEntry); err != nil { - return err - } - if pathname == dir { - watchEntry.mask &= ^provisional - } else { - watchEntry.names[filepath.Base(pathname)] &= ^provisional - } - return nil -} - -// Must run within the I/O thread. -func (w *Watcher) remWatch(pathname string) error { - dir, err := getDir(pathname) - if err != nil { - return err - } - ino, err := getIno(dir) - if err != nil { - return err - } - w.mu.Lock() - watch := w.watches.get(ino) - w.mu.Unlock() - if watch == nil { - return fmt.Errorf("can't remove non-existent watch for: %s", pathname) - } - if pathname == dir { - w.sendEvent(watch.path, watch.mask&sys_FS_IGNORED) - watch.mask = 0 - } else { - name := filepath.Base(pathname) - w.sendEvent(watch.path+"\\"+name, watch.names[name]&sys_FS_IGNORED) - delete(watch.names, name) - } - return w.startRead(watch) -} - -// Must run within the I/O thread. -func (w *Watcher) deleteWatch(watch *watch) { - for name, mask := range watch.names { - if mask&provisional == 0 { - w.sendEvent(watch.path+"\\"+name, mask&sys_FS_IGNORED) - } - delete(watch.names, name) - } - if watch.mask != 0 { - if watch.mask&provisional == 0 { - w.sendEvent(watch.path, watch.mask&sys_FS_IGNORED) - } - watch.mask = 0 - } -} - -// Must run within the I/O thread. -func (w *Watcher) startRead(watch *watch) error { - if e := syscall.CancelIo(watch.ino.handle); e != nil { - w.Errors <- os.NewSyscallError("CancelIo", e) - w.deleteWatch(watch) - } - mask := toWindowsFlags(watch.mask) - for _, m := range watch.names { - mask |= toWindowsFlags(m) - } - if mask == 0 { - if e := syscall.CloseHandle(watch.ino.handle); e != nil { - w.Errors <- os.NewSyscallError("CloseHandle", e) - } - w.mu.Lock() - delete(w.watches[watch.ino.volume], watch.ino.index) - w.mu.Unlock() - return nil - } - e := syscall.ReadDirectoryChanges(watch.ino.handle, &watch.buf[0], - uint32(unsafe.Sizeof(watch.buf)), false, mask, nil, &watch.ov, 0) - if e != nil { - err := os.NewSyscallError("ReadDirectoryChanges", e) - if e == syscall.ERROR_ACCESS_DENIED && watch.mask&provisional == 0 { - // Watched directory was probably removed - if w.sendEvent(watch.path, watch.mask&sys_FS_DELETE_SELF) { - if watch.mask&sys_FS_ONESHOT != 0 { - watch.mask = 0 - } - } - err = nil - } - w.deleteWatch(watch) - w.startRead(watch) - return err - } - return nil -} - -// readEvents reads from the I/O completion port, converts the -// received events into Event objects and sends them via the Events channel. -// Entry point to the I/O thread. -func (w *Watcher) readEvents() { - var ( - n, key uint32 - ov *syscall.Overlapped - ) - runtime.LockOSThread() - - for { - e := syscall.GetQueuedCompletionStatus(w.port, &n, &key, &ov, syscall.INFINITE) - watch := (*watch)(unsafe.Pointer(ov)) - - if watch == nil { - select { - case ch := <-w.quit: - w.mu.Lock() - var indexes []indexMap - for _, index := range w.watches { - indexes = append(indexes, index) - } - w.mu.Unlock() - for _, index := range indexes { - for _, watch := range index { - w.deleteWatch(watch) - w.startRead(watch) - } - } - var err error - if e := syscall.CloseHandle(w.port); e != nil { - err = os.NewSyscallError("CloseHandle", e) - } - close(w.Events) - close(w.Errors) - ch <- err - return - case in := <-w.input: - switch in.op { - case opAddWatch: - in.reply <- w.addWatch(in.path, uint64(in.flags)) - case opRemoveWatch: - in.reply <- w.remWatch(in.path) - } - default: - } - continue - } - - switch e { - case syscall.ERROR_MORE_DATA: - if watch == nil { - w.Errors <- errors.New("ERROR_MORE_DATA has unexpectedly null lpOverlapped buffer") - } else { - // The i/o succeeded but the buffer is full. - // In theory we should be building up a full packet. - // In practice we can get away with just carrying on. - n = uint32(unsafe.Sizeof(watch.buf)) - } - case syscall.ERROR_ACCESS_DENIED: - // Watched directory was probably removed - w.sendEvent(watch.path, watch.mask&sys_FS_DELETE_SELF) - w.deleteWatch(watch) - w.startRead(watch) - continue - case syscall.ERROR_OPERATION_ABORTED: - // CancelIo was called on this handle - continue - default: - w.Errors <- os.NewSyscallError("GetQueuedCompletionPort", e) - continue - case nil: - } - - var offset uint32 - for { - if n == 0 { - w.Events <- newEvent("", sys_FS_Q_OVERFLOW) - w.Errors <- errors.New("short read in readEvents()") - break - } - - // Point "raw" to the event in the buffer - raw := (*syscall.FileNotifyInformation)(unsafe.Pointer(&watch.buf[offset])) - buf := (*[syscall.MAX_PATH]uint16)(unsafe.Pointer(&raw.FileName)) - name := syscall.UTF16ToString(buf[:raw.FileNameLength/2]) - fullname := watch.path + "\\" + name - - var mask uint64 - switch raw.Action { - case syscall.FILE_ACTION_REMOVED: - mask = sys_FS_DELETE_SELF - case syscall.FILE_ACTION_MODIFIED: - mask = sys_FS_MODIFY - case syscall.FILE_ACTION_RENAMED_OLD_NAME: - watch.rename = name - case syscall.FILE_ACTION_RENAMED_NEW_NAME: - if watch.names[watch.rename] != 0 { - watch.names[name] |= watch.names[watch.rename] - delete(watch.names, watch.rename) - mask = sys_FS_MOVE_SELF - } - } - - sendNameEvent := func() { - if w.sendEvent(fullname, watch.names[name]&mask) { - if watch.names[name]&sys_FS_ONESHOT != 0 { - delete(watch.names, name) - } - } - } - if raw.Action != syscall.FILE_ACTION_RENAMED_NEW_NAME { - sendNameEvent() - } - if raw.Action == syscall.FILE_ACTION_REMOVED { - w.sendEvent(fullname, watch.names[name]&sys_FS_IGNORED) - delete(watch.names, name) - } - if w.sendEvent(fullname, watch.mask&toFSnotifyFlags(raw.Action)) { - if watch.mask&sys_FS_ONESHOT != 0 { - watch.mask = 0 - } - } - if raw.Action == syscall.FILE_ACTION_RENAMED_NEW_NAME { - fullname = watch.path + "\\" + watch.rename - sendNameEvent() - } - - // Move to the next event in the buffer - if raw.NextEntryOffset == 0 { - break - } - offset += raw.NextEntryOffset - - // Error! - if offset >= n { - w.Errors <- errors.New("Windows system assumed buffer larger than it is, events have likely been missed.") - break - } - } - - if err := w.startRead(watch); err != nil { - w.Errors <- err - } - } -} - -func (w *Watcher) sendEvent(name string, mask uint64) bool { - if mask == 0 { - return false - } - event := newEvent(name, uint32(mask)) - select { - case ch := <-w.quit: - w.quit <- ch - case w.Events <- event: - } - return true -} - -func toWindowsFlags(mask uint64) uint32 { - var m uint32 - if mask&sys_FS_ACCESS != 0 { - m |= syscall.FILE_NOTIFY_CHANGE_LAST_ACCESS - } - if mask&sys_FS_MODIFY != 0 { - m |= syscall.FILE_NOTIFY_CHANGE_LAST_WRITE - } - if mask&sys_FS_ATTRIB != 0 { - m |= syscall.FILE_NOTIFY_CHANGE_ATTRIBUTES - } - if mask&(sys_FS_MOVE|sys_FS_CREATE|sys_FS_DELETE) != 0 { - m |= syscall.FILE_NOTIFY_CHANGE_FILE_NAME | syscall.FILE_NOTIFY_CHANGE_DIR_NAME - } - return m -} - -func toFSnotifyFlags(action uint32) uint64 { - switch action { - case syscall.FILE_ACTION_ADDED: - return sys_FS_CREATE - case syscall.FILE_ACTION_REMOVED: - return sys_FS_DELETE - case syscall.FILE_ACTION_MODIFIED: - return sys_FS_MODIFY - case syscall.FILE_ACTION_RENAMED_OLD_NAME: - return sys_FS_MOVED_FROM - case syscall.FILE_ACTION_RENAMED_NEW_NAME: - return sys_FS_MOVED_TO - } - return 0 -}