From 8987bc7e00a3d20abbbe7a0d3f1a9508c10cf810 Mon Sep 17 00:00:00 2001 From: Armon Dadgar Date: Mon, 29 Jun 2015 15:05:44 -0700 Subject: [PATCH] Updating Godeps --- Godeps/Godeps.json | 85 +- .../src/github.com/armon/go-metrics/inmem.go | 18 +- .../github.com/armon/go-metrics/inmem_test.go | 9 + .../src/github.com/armon/go-radix/README.md | 2 + .../aws/aws-sdk-go/aws/awserr/error.go | 17 + .../aws/aws-sdk-go/aws/awserr/types.go | 135 ++ .../aws-sdk-go/aws/awsutil/path_value_test.go | 4 +- .../github.com/aws/aws-sdk-go/aws/config.go | 27 +- .../aws/aws-sdk-go/aws/config_test.go | 92 ++ .../aws/credentials/chain_provider.go | 8 +- .../aws/credentials/chain_provider_test.go | 10 +- .../aws-sdk-go/aws/credentials/credentials.go | 47 +- .../aws/credentials/credentials_test.go | 3 +- .../aws/credentials/ec2_role_provider.go | 28 +- .../aws/credentials/ec2_role_provider_test.go | 14 +- .../aws/credentials/env_provider.go | 6 +- .../shared_credentials_provider.go | 10 +- .../aws/credentials/static_provider.go | 4 +- .../stscreds/assume_role_provider.go | 120 ++ .../stscreds/assume_role_provider_test.go | 58 + .../aws/aws-sdk-go/aws/handler_functions.go | 20 +- .../aws-sdk-go/aws/handler_functions_test.go | 6 +- .../aws/aws-sdk-go/aws/param_validator.go | 4 +- .../aws-sdk-go/aws/param_validator_test.go | 10 +- .../github.com/aws/aws-sdk-go/aws/request.go | 9 +- .../aws-sdk-go/aws/request_pagination_test.go | 54 +- .../aws/aws-sdk-go/aws/request_test.go | 37 +- .../github.com/aws/aws-sdk-go/aws/service.go | 11 +- .../github.com/aws/aws-sdk-go/aws/version.go | 2 +- .../internal/endpoints/endpoints.go | 2 + .../internal/endpoints/endpoints_map.go | 42 +- .../internal/protocol/query/build.go | 5 +- .../internal/protocol/query/build_test.go | 224 +-- .../internal/protocol/query/unmarshal.go | 4 +- .../protocol/query/unmarshal_error.go | 8 +- .../internal/protocol/query/unmarshal_test.go | 189 +-- .../internal/protocol/rest/build.go | 13 +- .../internal/protocol/rest/unmarshal.go | 12 +- .../internal/protocol/restxml/build_test.go | 498 +++--- .../internal/protocol/restxml/restxml.go | 8 +- .../protocol/restxml/unmarshal_test.go | 174 +- .../internal/protocol/xml/xmlutil/build.go | 1 + .../protocol/xml/xmlutil/unmarshal.go | 2 +- .../aws/aws-sdk-go/internal/signer/v4/v4.go | 157 +- .../aws-sdk-go/internal/signer/v4/v4_test.go | 109 +- .../aws/aws-sdk-go/service/s3/api.go | 969 ++++------- .../aws-sdk-go/service/s3/bucket_location.go | 4 +- .../aws/aws-sdk-go/service/s3/content_md5.go | 6 +- .../aws-sdk-go/service/s3/customizations.go | 2 +- .../service/s3/customizations_test.go | 8 +- .../aws-sdk-go/service/s3/examples_test.go | 134 +- .../service/s3/s3manager/download.go | 19 +- .../aws-sdk-go/service/s3/s3manager/upload.go | 41 +- .../service/s3/s3manager/upload_test.go | 88 +- .../aws/aws-sdk-go/service/s3/sse.go | 4 +- .../aws-sdk-go/service/s3/unmarshal_error.go | 12 +- .../github.com/coreos/go-etcd/etcd/client.go | 25 +- .../github.com/coreos/go-etcd/etcd/cluster.go | 18 +- .../coreos/go-etcd/etcd/response.generated.go | 1419 +++++++++++++++++ .../coreos/go-etcd/etcd/response.go | 8 +- .../coreos/go-etcd/etcd/response_test.go | 75 + .../src/github.com/go-ldap/ldap/compare.go | 85 + .../src/github.com/go-ldap/ldap/conn.go | 25 +- .../go-ldap/ldap/examples/compare/compare.go | 39 + .../src/github.com/go-ldap/ldap/ldap_test.go | 21 + .../src/github.com/go-ldap/ldap/todo | 19 - .../github.com/go-sql-driver/mysql/AUTHORS | 3 + .../github.com/go-sql-driver/mysql/README.md | 14 +- .../go-sql-driver/mysql/connection.go | 31 +- .../github.com/go-sql-driver/mysql/const.go | 10 +- .../github.com/go-sql-driver/mysql/driver.go | 9 + .../go-sql-driver/mysql/driver_test.go | 43 + .../github.com/go-sql-driver/mysql/errors.go | 20 +- .../github.com/go-sql-driver/mysql/packets.go | 51 +- .../go-sql-driver/mysql/statement.go | 38 + .../github.com/go-sql-driver/mysql/utils.go | 14 +- .../go-sql-driver/mysql/utils_test.go | 26 +- .../google/go-github/github/activity_star.go | 13 +- .../go-github/github/activity_star_test.go | 11 +- .../github.com/google/go-github/github/doc.go | 15 +- .../google/go-github/github/gists.go | 18 + .../google/go-github/github/gists_test.go | 26 + .../google/go-github/github/github.go | 31 +- .../google/go-github/github/github_test.go | 19 + .../google/go-github/github/issues.go | 16 +- .../google/go-github/github/issues_labels.go | 2 +- .../google/go-github/github/issues_test.go | 2 +- .../google/go-github/github/licenses.go | 81 + .../google/go-github/github/licenses_test.go | 64 + .../google/go-github/github/misc.go | 36 + .../google/go-github/github/misc_test.go | 35 +- .../google/go-github/github/orgs_hooks.go | 104 ++ .../go-github/github/orgs_hooks_test.go | 134 ++ .../google/go-github/github/orgs_members.go | 9 - .../go-github/github/orgs_members_test.go | 3 - .../google/go-github/github/orgs_teams.go | 35 - .../go-github/github/orgs_teams_test.go | 43 - .../google/go-github/github/pulls.go | 11 + .../google/go-github/github/pulls_comments.go | 2 +- .../google/go-github/github/pulls_test.go | 35 +- .../google/go-github/github/repos.go | 16 + .../google/go-github/github/repos_commits.go | 3 +- .../google/go-github/github/repos_contents.go | 49 +- .../go-github/github/repos_contents_test.go | 74 +- .../go-github/github/repos_deployments.go | 26 +- .../google/go-github/github/repos_hooks.go | 43 +- .../go-github/github/repos_hooks_test.go | 46 +- .../google/go-github/github/repos_releases.go | 21 +- .../go-github/github/repos_releases_test.go | 40 + .../google/go-github/github/repos_test.go | 9 +- .../hashicorp/consul/api/acl_test.go | 42 +- .../github.com/hashicorp/consul/api/agent.go | 1 + .../hashicorp/consul/api/agent_test.go | 126 +- .../hashicorp/consul/api/api_test.go | 16 + .../hashicorp/consul/api/catalog_test.go | 6 + .../hashicorp/consul/api/event_test.go | 24 +- .../hashicorp/consul/api/health_test.go | 4 + .../src/github.com/hashicorp/consul/api/kv.go | 4 + .../hashicorp/consul/api/kv_test.go | 20 +- .../github.com/hashicorp/consul/api/lock.go | 20 +- .../hashicorp/consul/api/lock_test.go | 7 + .../hashicorp/consul/api/semaphore.go | 5 - .../hashicorp/consul/api/semaphore_test.go | 7 + .../hashicorp/consul/api/session.go | 20 +- .../hashicorp/consul/api/session_test.go | 5 + .../hashicorp/consul/api/status_test.go | 2 + .../hashicorp/go-multierror/flatten.go | 26 + .../hashicorp/go-multierror/flatten_test.go | 48 + .../github.com/hashicorp/golang-lru/lru.go | 23 +- .../hashicorp/golang-lru/lru_test.go | 43 +- .../src/github.com/hashicorp/hcl/README.md | 4 +- .../github.com/hashicorp/hcl/decoder_test.go | 14 + .../src/github.com/hashicorp/hcl/hcl/lex.go | 16 +- .../hashicorp/hcl/hcl/valuetype_string.go | 2 +- .../github.com/hashicorp/logutils/README.md | 2 +- .../src/github.com/kardianos/osext/README.md | 4 +- .../src/github.com/kardianos/osext/osext.go | 8 +- .../github.com/kardianos/osext/osext_test.go | 23 + .../src/github.com/lib/pq/bench_test.go | 10 +- .../_workspace/src/github.com/lib/pq/buf.go | 28 +- .../_workspace/src/github.com/lib/pq/conn.go | 245 ++- .../src/github.com/lib/pq/conn_test.go | 13 +- .../src/github.com/lib/pq/copy_test.go | 14 +- .../src/github.com/lib/pq/encode.go | 31 +- .../src/github.com/lib/pq/encode_test.go | 29 +- .../_workspace/src/github.com/lib/pq/error.go | 13 + .../src/github.com/lib/pq/notify.go | 46 +- .../src/github.com/lib/pq/notify_test.go | 72 + .../src/github.com/mitchellh/cli/README.md | 3 + .../src/github.com/mitchellh/cli/cli.go | 35 +- .../src/github.com/mitchellh/cli/cli_test.go | 72 +- .../mitchellh/mapstructure/.travis.yml | 7 + .../mitchellh/mapstructure/decode_hooks.go | 75 +- .../mapstructure/decode_hooks_test.go | 88 +- .../mitchellh/mapstructure/error.go | 16 + .../mitchellh/mapstructure/mapstructure.go | 87 +- .../mapstructure/mapstructure_test.go | 170 ++ .../mitchellh/reflectwalk/reflectwalk.go | 12 +- .../github.com/samuel/go-zookeeper/zk/conn.go | 39 +- .../github.com/samuel/go-zookeeper/zk/lock.go | 13 +- .../samuel/go-zookeeper/zk/structs.go | 7 + .../samuel/go-zookeeper/zk/structs_test.go | 11 + .../golang.org/x/crypto/ssh/terminal/util.go | 2 +- .../src/golang.org/x/net/context/context.go | 2 +- .../src/golang.org/x/oauth2/README.md | 2 +- .../clientcredentials/clientcredentials.go | 2 +- .../golang.org/x/oauth2/facebook/facebook.go | 2 +- .../src/golang.org/x/oauth2/github/github.go | 2 +- .../src/golang.org/x/oauth2/google/google.go | 2 +- .../src/golang.org/x/oauth2/internal/token.go | 1 + .../src/golang.org/x/oauth2/jws/jws.go | 2 +- .../golang.org/x/oauth2/linkedin/linkedin.go | 2 +- .../src/golang.org/x/oauth2/oauth2.go | 18 +- .../x/oauth2/odnoklassniki/odnoklassniki.go | 2 +- .../src/golang.org/x/oauth2/paypal/paypal.go | 2 +- .../src/golang.org/x/oauth2/token.go | 10 + .../src/golang.org/x/oauth2/transport_test.go | 33 + .../src/golang.org/x/oauth2/vk/vk.go | 2 +- 178 files changed, 6061 insertions(+), 2333 deletions(-) create mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr/types.go create mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config_test.go create mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go create mode 100644 Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go create mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response.generated.go create mode 100644 Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response_test.go create mode 100644 Godeps/_workspace/src/github.com/go-ldap/ldap/compare.go create mode 100644 Godeps/_workspace/src/github.com/go-ldap/ldap/examples/compare/compare.go delete mode 100644 Godeps/_workspace/src/github.com/go-ldap/ldap/todo create mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/licenses.go create mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/licenses_test.go create mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/orgs_hooks.go create mode 100644 Godeps/_workspace/src/github.com/google/go-github/github/orgs_hooks_test.go create mode 100644 Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten.go create mode 100644 Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten_test.go create mode 100644 Godeps/_workspace/src/github.com/mitchellh/mapstructure/.travis.yml diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json index e3a779a57..4757fa2de 100644 --- a/Godeps/Godeps.json +++ b/Godeps/Godeps.json @@ -1,59 +1,62 @@ { "ImportPath": "github.com/hashicorp/vault", "GoVersion": "go1.4.2", + "Packages": [ + "./..." + ], "Deps": [ { "ImportPath": "github.com/armon/go-metrics", - "Rev": "a54701ebec11868993bc198c3f315353e9de2ed6" + "Rev": "b2d95e5291cdbc26997d1301a5e467ecbb240e25" }, { "ImportPath": "github.com/armon/go-radix", - "Rev": "0bab926c3433cfd6490c6d3c504a7b471362390c" + "Rev": "fbd82e84e2b13651f3abc5ffd26b65ba71bc8f93" }, { "ImportPath": "github.com/aws/aws-sdk-go/aws", - "Comment": "v0.6.0", - "Rev": "ea83c25c44525da47e8044bbd21e4045758ea39b" + "Comment": "v0.6.4-5-g127313c", + "Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d" }, { "ImportPath": "github.com/aws/aws-sdk-go/internal/endpoints", - "Comment": "v0.6.0", - "Rev": "ea83c25c44525da47e8044bbd21e4045758ea39b" + "Comment": "v0.6.4-5-g127313c", + "Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d" }, { "ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/query", - "Comment": "v0.6.0", - "Rev": "ea83c25c44525da47e8044bbd21e4045758ea39b" + "Comment": "v0.6.4-5-g127313c", + "Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d" }, { "ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/rest", - "Comment": "v0.6.0", - "Rev": "ea83c25c44525da47e8044bbd21e4045758ea39b" + "Comment": "v0.6.4-5-g127313c", + "Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d" }, { "ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/restxml", - "Comment": "v0.6.0", - "Rev": "ea83c25c44525da47e8044bbd21e4045758ea39b" + "Comment": "v0.6.4-5-g127313c", + "Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d" }, { "ImportPath": "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil", - "Comment": "v0.6.0", - "Rev": "ea83c25c44525da47e8044bbd21e4045758ea39b" + "Comment": "v0.6.4-5-g127313c", + "Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d" }, { "ImportPath": "github.com/aws/aws-sdk-go/internal/signer/v4", - "Comment": "v0.6.0", - "Rev": "ea83c25c44525da47e8044bbd21e4045758ea39b" + "Comment": "v0.6.4-5-g127313c", + "Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d" }, { "ImportPath": "github.com/aws/aws-sdk-go/service/s3", - "Comment": "v0.6.0", - "Rev": "ea83c25c44525da47e8044bbd21e4045758ea39b" + "Comment": "v0.6.4-5-g127313c", + "Rev": "127313c1b41e534a0456a68b6b3a16712dacb35d" }, { "ImportPath": "github.com/coreos/go-etcd/etcd", - "Comment": "v2.0.0-7-g73a8ef7", - "Rev": "73a8ef737e8ea002281a28b4cb92a1de121ad4c6" + "Comment": "v2.0.0-18-gc904d70", + "Rev": "c904d7032a70da6551c43929f199244f6a45f4c1" }, { "ImportPath": "github.com/fatih/structs", @@ -61,17 +64,17 @@ }, { "ImportPath": "github.com/go-ldap/ldap", - "Comment": "v1-8-g4d41e0d", - "Rev": "4d41e0d546efa36b1500653d519d1b39fc007dbd" + "Comment": "v1-14-g406aa05", + "Rev": "406aa05eb8272fb8aa201e410afa6f9fdcb2bf68" }, { "ImportPath": "github.com/go-sql-driver/mysql", - "Comment": "v1.2-88-ga197e5d", - "Rev": "a197e5d40516f2e9f74dcee085a5f2d4604e94df" + "Comment": "v1.2-112-gfb72997", + "Rev": "fb7299726d2e68745a8805b14f2ff44b5c2cfa84" }, { "ImportPath": "github.com/google/go-github/github", - "Rev": "0aaa85be4f3087c6dd815a69e291775d4e83f9ea" + "Rev": "fccd5bb66f985db0a0d150342ca0a9529a23488a" }, { "ImportPath": "github.com/google/go-querystring/query", @@ -99,8 +102,8 @@ }, { "ImportPath": "github.com/hashicorp/consul/api", - "Comment": "v0.5.0-253-g7062ecc", - "Rev": "7062ecc50fef9307e532c4a188da7ce1dd759dde" + "Comment": "v0.5.2-123-gaddb614", + "Rev": "addb6145096bbce6f9dde807a78cad2a4cea3a68" }, { "ImportPath": "github.com/hashicorp/errwrap", @@ -108,7 +111,7 @@ }, { "ImportPath": "github.com/hashicorp/go-multierror", - "Rev": "fcdddc395df1ddf4247c69bd436e84cfa0733f7e" + "Rev": "56912fb08d85084aa318edcf2bba735b97cf35c5" }, { "ImportPath": "github.com/hashicorp/go-syslog", @@ -116,28 +119,28 @@ }, { "ImportPath": "github.com/hashicorp/golang-lru", - "Rev": "d85392d6bc30546d352f52f2632814cde4201d44" + "Rev": "995efda3e073b6946b175ed93901d729ad47466a" }, { "ImportPath": "github.com/hashicorp/hcl", - "Rev": "513e04c400ee2e81e97f5e011c08fb42c6f69b84" + "Rev": "54864211433d45cb780682431585b3e573b49e4a" }, { "ImportPath": "github.com/hashicorp/logutils", - "Rev": "367a65d59043b4f846d179341d138f01f988c186" + "Rev": "0dc08b1671f34c4250ce212759ebd880f743d883" }, { "ImportPath": "github.com/kardianos/osext", - "Rev": "8fef92e41e22a70e700a96b29f066cda30ea24ef" + "Rev": "6e7f843663477789fac7c02def0d0909e969b4e5" }, { "ImportPath": "github.com/lib/pq", - "Comment": "go1.0-cutoff-40-g8910d1c", - "Rev": "8910d1c3a4bda5c97c50bc38543953f1f1e1f8bb" + "Comment": "go1.0-cutoff-51-ga8d8d01", + "Rev": "a8d8d01c4f91602f876bf5aa210274e8203a6b45" }, { "ImportPath": "github.com/mitchellh/cli", - "Rev": "6cc8bc522243675a2882b81662b0b0d2e04b99c9" + "Rev": "8102d0ed5ea2709ade1243798785888175f6e415" }, { "ImportPath": "github.com/mitchellh/copystructure", @@ -149,11 +152,11 @@ }, { "ImportPath": "github.com/mitchellh/mapstructure", - "Rev": "442e588f213303bec7936deba67901f8fc8f18b1" + "Rev": "2caf8efc93669b6c43e0441cdc6aed17546c96f3" }, { "ImportPath": "github.com/mitchellh/reflectwalk", - "Rev": "242be0c275dedfba00a616563e6db75ab8f279ec" + "Rev": "eecf4c70c626c7cfbb95c90195bc34d386c74ac6" }, { "ImportPath": "github.com/ryanuber/columnize", @@ -162,7 +165,7 @@ }, { "ImportPath": "github.com/samuel/go-zookeeper/zk", - "Rev": "d0e0d8e11f318e000a8cc434616d69e329edc374" + "Rev": "c86eba8e7e95efab81f6c0455332e49d39aed12f" }, { "ImportPath": "github.com/ugorji/go/codec", @@ -174,15 +177,15 @@ }, { "ImportPath": "golang.org/x/crypto/ssh/terminal", - "Rev": "59435533c88bd0b1254c738244da1fe96b59d05d" + "Rev": "cc04154d65fb9296747569b107cfd05380b1ea3e" }, { "ImportPath": "golang.org/x/net/context", - "Rev": "a8c61998a557a37435f719980da368469c10bfed" + "Rev": "d9558e5c97f85372afee28cf2b6059d7d3818919" }, { "ImportPath": "golang.org/x/oauth2", - "Rev": "ec6d5d770f531108a6464462b2201b74fcd09314" + "Rev": "b5adcc2dcdf009d0391547edc6ecbaff889f5bb9" }, { "ImportPath": "gopkg.in/asn1-ber.v1", diff --git a/Godeps/_workspace/src/github.com/armon/go-metrics/inmem.go b/Godeps/_workspace/src/github.com/armon/go-metrics/inmem.go index 0749229bf..da5032960 100644 --- a/Godeps/_workspace/src/github.com/armon/go-metrics/inmem.go +++ b/Godeps/_workspace/src/github.com/armon/go-metrics/inmem.go @@ -65,11 +65,12 @@ func NewIntervalMetrics(intv time.Time) *IntervalMetrics { // AggregateSample is used to hold aggregate metrics // about a sample type AggregateSample struct { - Count int // The count of emitted pairs - Sum float64 // The sum of values - SumSq float64 // The sum of squared values - Min float64 // Minimum value - Max float64 // Maximum value + Count int // The count of emitted pairs + Sum float64 // The sum of values + SumSq float64 // The sum of squared values + Min float64 // Minimum value + Max float64 // Maximum value + LastUpdated time.Time // When value was last updated } // Computes a Stddev of the values @@ -101,16 +102,17 @@ func (a *AggregateSample) Ingest(v float64) { if v > a.Max || a.Count == 1 { a.Max = v } + a.LastUpdated = time.Now() } func (a *AggregateSample) String() string { if a.Count == 0 { return "Count: 0" } else if a.Stddev() == 0 { - return fmt.Sprintf("Count: %d Sum: %0.3f", a.Count, a.Sum) + return fmt.Sprintf("Count: %d Sum: %0.3f LastUpdated: %s", a.Count, a.Sum, a.LastUpdated) } else { - return fmt.Sprintf("Count: %d Min: %0.3f Mean: %0.3f Max: %0.3f Stddev: %0.3f Sum: %0.3f", - a.Count, a.Min, a.Mean(), a.Max, a.Stddev(), a.Sum) + return fmt.Sprintf("Count: %d Min: %0.3f Mean: %0.3f Max: %0.3f Stddev: %0.3f Sum: %0.3f LastUpdated: %s", + a.Count, a.Min, a.Mean(), a.Max, a.Stddev(), a.Sum, a.LastUpdated) } } diff --git a/Godeps/_workspace/src/github.com/armon/go-metrics/inmem_test.go b/Godeps/_workspace/src/github.com/armon/go-metrics/inmem_test.go index 14ba31b38..228a2fc1a 100644 --- a/Godeps/_workspace/src/github.com/armon/go-metrics/inmem_test.go +++ b/Godeps/_workspace/src/github.com/armon/go-metrics/inmem_test.go @@ -63,6 +63,15 @@ func TestInmemSink(t *testing.T) { t.Fatalf("bad val: %v", agg) } + if agg.LastUpdated.IsZero() { + t.Fatalf("agg.LastUpdated is not set: %v", agg) + } + + diff := time.Now().Sub(agg.LastUpdated).Seconds() + if diff > 1 { + t.Fatalf("time diff too great: %f", diff) + } + if agg = intvM.Samples["foo.bar"]; agg == nil { t.Fatalf("missing sample") } diff --git a/Godeps/_workspace/src/github.com/armon/go-radix/README.md b/Godeps/_workspace/src/github.com/armon/go-radix/README.md index c054fe86c..26f42a283 100644 --- a/Godeps/_workspace/src/github.com/armon/go-radix/README.md +++ b/Godeps/_workspace/src/github.com/armon/go-radix/README.md @@ -10,6 +10,8 @@ As a radix tree, it provides the following: * Minimum / Maximum value lookups * Ordered iteration +For an immutable variant, see [go-immutable-radix](https://github.com/hashicorp/go-immutable-radix). + Documentation ============= diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr/error.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr/error.go index cf54d89d1..99d8c1843 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr/error.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr/error.go @@ -42,6 +42,17 @@ type Error interface { OrigErr() error } +// New returns an Error object described by the code, message, and origErr. +// +// If origErr satisfies the Error interface it will not be wrapped within a new +// Error object and will instead be returned. +func New(code, message string, origErr error) Error { + if e, ok := origErr.(Error); ok && e != nil { + return e + } + return newBaseError(code, message, origErr) +} + // A RequestFailure is an interface to extract request failure information from // an Error such as the request ID of the failed request returned by a service. // RequestFailures may not always have a requestID value if the request failed @@ -86,3 +97,9 @@ type RequestFailure interface { // to a connection error. RequestID() string } + +// NewRequestFailure returns a new request error wrapper for the given Error +// provided. +func NewRequestFailure(err Error, statusCode int, reqID string) RequestFailure { + return newRequestError(err, statusCode, reqID) +} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr/types.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr/types.go new file mode 100644 index 000000000..418fc4c14 --- /dev/null +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr/types.go @@ -0,0 +1,135 @@ +package awserr + +import "fmt" + +// SprintError returns a string of the formatted error code. +// +// Both extra and origErr are optional. If they are included their lines +// will be added, but if they are not included their lines will be ignored. +func SprintError(code, message, extra string, origErr error) string { + msg := fmt.Sprintf("%s: %s", code, message) + if extra != "" { + msg = fmt.Sprintf("%s\n\t%s", msg, extra) + } + if origErr != nil { + msg = fmt.Sprintf("%s\ncaused by: %s", msg, origErr.Error()) + } + return msg +} + +// A baseError wraps the code and message which defines an error. It also +// can be used to wrap an original error object. +// +// Should be used as the root for errors satisfying the awserr.Error. Also +// for any error which does not fit into a specific error wrapper type. +type baseError struct { + // Classification of error + code string + + // Detailed information about error + message string + + // Optional original error this error is based off of. Allows building + // chained errors. + origErr error +} + +// newBaseError returns an error object for the code, message, and err. +// +// code is a short no whitespace phrase depicting the classification of +// the error that is being created. +// +// message is the free flow string containing detailed information about the error. +// +// origErr is the error object which will be nested under the new error to be returned. +func newBaseError(code, message string, origErr error) *baseError { + return &baseError{ + code: code, + message: message, + origErr: origErr, + } +} + +// Error returns the string representation of the error. +// +// See ErrorWithExtra for formatting. +// +// Satisfies the error interface. +func (b baseError) Error() string { + return SprintError(b.code, b.message, "", b.origErr) +} + +// String returns the string representation of the error. +// Alias for Error to satisfy the stringer interface. +func (b baseError) String() string { + return b.Error() +} + +// Code returns the short phrase depicting the classification of the error. +func (b baseError) Code() string { + return b.code +} + +// Message returns the error details message. +func (b baseError) Message() string { + return b.message +} + +// OrigErr returns the original error if one was set. Nil is returned if no error +// was set. +func (b baseError) OrigErr() error { + return b.origErr +} + +// So that the Error interface type can be included as an anonymous field +// in the requestError struct and not conflict with the error.Error() method. +type awsError Error + +// A requestError wraps a request or service error. +// +// Composed of baseError for code, message, and original error. +type requestError struct { + awsError + statusCode int + requestID string +} + +// newRequestError returns a wrapped error with additional information for request +// status code, and service requestID. +// +// Should be used to wrap all request which involve service requests. Even if +// the request failed without a service response, but had an HTTP status code +// that may be meaningful. +// +// Also wraps original errors via the baseError. +func newRequestError(err Error, statusCode int, requestID string) *requestError { + return &requestError{ + awsError: err, + statusCode: statusCode, + requestID: requestID, + } +} + +// Error returns the string representation of the error. +// Satisfies the error interface. +func (r requestError) Error() string { + extra := fmt.Sprintf("status code: %d, request id: [%s]", + r.statusCode, r.requestID) + return SprintError(r.Code(), r.Message(), extra, r.OrigErr()) +} + +// String returns the string representation of the error. +// Alias for Error to satisfy the stringer interface. +func (r requestError) String() string { + return r.Error() +} + +// StatusCode returns the wrapped status code for the error +func (r requestError) StatusCode() int { + return r.statusCode +} + +// RequestID returns the wrapped requestID +func (r requestError) RequestID() string { + return r.requestID +} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go index 1262cf6be..ed10aec19 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awsutil/path_value_test.go @@ -16,8 +16,8 @@ type Struct struct { } var data = Struct{ - A: []Struct{Struct{C: "value1"}, Struct{C: "value2"}, Struct{C: "value3"}}, - z: []Struct{Struct{C: "value1"}, Struct{C: "value2"}, Struct{C: "value3"}}, + A: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}}, + z: []Struct{{C: "value1"}, {C: "value2"}, {C: "value3"}}, B: &Struct{B: &Struct{C: "terminal"}, D: &Struct{C: "terminal2"}}, C: "initial", } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config.go index bd805f36b..469907071 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config.go @@ -68,6 +68,7 @@ func (c Config) Copy() Config { dst.DisableSSL = c.DisableSSL dst.ManualSend = c.ManualSend dst.HTTPClient = c.HTTPClient + dst.LogHTTPBody = c.LogHTTPBody dst.LogLevel = c.LogLevel dst.Logger = c.Logger dst.MaxRetries = c.MaxRetries @@ -90,79 +91,79 @@ func (c Config) Merge(newcfg *Config) *Config { cfg := Config{} - if newcfg != nil && newcfg.Credentials != nil { + if newcfg.Credentials != nil { cfg.Credentials = newcfg.Credentials } else { cfg.Credentials = c.Credentials } - if newcfg != nil && newcfg.Endpoint != "" { + if newcfg.Endpoint != "" { cfg.Endpoint = newcfg.Endpoint } else { cfg.Endpoint = c.Endpoint } - if newcfg != nil && newcfg.Region != "" { + if newcfg.Region != "" { cfg.Region = newcfg.Region } else { cfg.Region = c.Region } - if newcfg != nil && newcfg.DisableSSL { + if newcfg.DisableSSL { cfg.DisableSSL = newcfg.DisableSSL } else { cfg.DisableSSL = c.DisableSSL } - if newcfg != nil && newcfg.ManualSend { + if newcfg.ManualSend { cfg.ManualSend = newcfg.ManualSend } else { cfg.ManualSend = c.ManualSend } - if newcfg != nil && newcfg.HTTPClient != nil { + if newcfg.HTTPClient != nil { cfg.HTTPClient = newcfg.HTTPClient } else { cfg.HTTPClient = c.HTTPClient } - if newcfg != nil && newcfg.LogHTTPBody { + if newcfg.LogHTTPBody { cfg.LogHTTPBody = newcfg.LogHTTPBody } else { cfg.LogHTTPBody = c.LogHTTPBody } - if newcfg != nil && newcfg.LogLevel != 0 { + if newcfg.LogLevel != 0 { cfg.LogLevel = newcfg.LogLevel } else { cfg.LogLevel = c.LogLevel } - if newcfg != nil && newcfg.Logger != nil { + if newcfg.Logger != nil { cfg.Logger = newcfg.Logger } else { cfg.Logger = c.Logger } - if newcfg != nil && newcfg.MaxRetries != DefaultRetries { + if newcfg.MaxRetries != DefaultRetries { cfg.MaxRetries = newcfg.MaxRetries } else { cfg.MaxRetries = c.MaxRetries } - if newcfg != nil && newcfg.DisableParamValidation { + if newcfg.DisableParamValidation { cfg.DisableParamValidation = newcfg.DisableParamValidation } else { cfg.DisableParamValidation = c.DisableParamValidation } - if newcfg != nil && newcfg.DisableComputeChecksums { + if newcfg.DisableComputeChecksums { cfg.DisableComputeChecksums = newcfg.DisableComputeChecksums } else { cfg.DisableComputeChecksums = c.DisableComputeChecksums } - if newcfg != nil && newcfg.S3ForcePathStyle { + if newcfg.S3ForcePathStyle { cfg.S3ForcePathStyle = newcfg.S3ForcePathStyle } else { cfg.S3ForcePathStyle = c.S3ForcePathStyle diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config_test.go new file mode 100644 index 000000000..fc5a77bd0 --- /dev/null +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/config_test.go @@ -0,0 +1,92 @@ +package aws + +import ( + "net/http" + "os" + "reflect" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws/credentials" +) + +var testCredentials = credentials.NewChainCredentials([]credentials.Provider{ + &credentials.EnvProvider{}, + &credentials.SharedCredentialsProvider{ + Filename: "TestFilename", + Profile: "TestProfile"}, + &credentials.EC2RoleProvider{ExpiryWindow: 5 * time.Minute}, +}) + +var copyTestConfig = Config{ + Credentials: testCredentials, + Endpoint: "CopyTestEndpoint", + Region: "COPY_TEST_AWS_REGION", + DisableSSL: true, + ManualSend: true, + HTTPClient: http.DefaultClient, + LogHTTPBody: true, + LogLevel: 2, + Logger: os.Stdout, + MaxRetries: DefaultRetries, + DisableParamValidation: true, + DisableComputeChecksums: true, + S3ForcePathStyle: true, +} + +func TestCopy(t *testing.T) { + want := copyTestConfig + got := copyTestConfig.Copy() + if !reflect.DeepEqual(got, want) { + t.Errorf("Copy() = %+v", got) + t.Errorf(" want %+v", want) + } +} + +func TestCopyReturnsNewInstance(t *testing.T) { + want := copyTestConfig + got := copyTestConfig.Copy() + if &got == &want { + t.Errorf("Copy() = %p; want different instance as source %p", &got, &want) + } +} + +var mergeTestZeroValueConfig = Config{MaxRetries: DefaultRetries} + +var mergeTestConfig = Config{ + Credentials: testCredentials, + Endpoint: "MergeTestEndpoint", + Region: "MERGE_TEST_AWS_REGION", + DisableSSL: true, + ManualSend: true, + HTTPClient: http.DefaultClient, + LogHTTPBody: true, + LogLevel: 2, + Logger: os.Stdout, + MaxRetries: 10, + DisableParamValidation: true, + DisableComputeChecksums: true, + S3ForcePathStyle: true, +} + +var mergeTests = []struct { + cfg *Config + in *Config + want *Config +}{ + {&Config{}, nil, &Config{}}, + {&Config{}, &mergeTestZeroValueConfig, &Config{}}, + {&Config{}, &mergeTestConfig, &mergeTestConfig}, +} + +func TestMerge(t *testing.T) { + for _, tt := range mergeTests { + got := tt.cfg.Merge(tt.in) + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Config %+v", tt.cfg) + t.Errorf(" Merge(%+v)", tt.in) + t.Errorf(" got %+v", got) + t.Errorf(" want %+v", tt.want) + } + } +} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go index 196be7c17..ce66dc831 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go @@ -1,13 +1,13 @@ package credentials import ( - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" ) var ( // ErrNoValidProvidersFoundInChain Is returned when there are no valid // providers in the ChainProvider. - ErrNoValidProvidersFoundInChain = apierr.New("NoCredentialProviders", "no valid providers in chain", nil) + ErrNoValidProvidersFoundInChain = awserr.New("NoCredentialProviders", "no valid providers in chain", nil) ) // A ChainProvider will search for a provider which returns credentials @@ -36,7 +36,9 @@ var ( // &EnvProvider{}, // &EC2RoleProvider{}, // }) -// creds.Retrieve() +// +// // Usage of ChainCredentials with aws.Config +// svc := ec2.New(&aws.Config{Credentials: creds}) // type ChainProvider struct { Providers []Provider diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go index 1a275fcac..4fba22f29 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/chain_provider_test.go @@ -3,15 +3,15 @@ package credentials import ( "testing" - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" "github.com/stretchr/testify/assert" ) func TestChainProviderGet(t *testing.T) { p := &ChainProvider{ Providers: []Provider{ - &stubProvider{err: apierr.New("FirstError", "first provider error", nil)}, - &stubProvider{err: apierr.New("SecondError", "second provider error", nil)}, + &stubProvider{err: awserr.New("FirstError", "first provider error", nil)}, + &stubProvider{err: awserr.New("SecondError", "second provider error", nil)}, &stubProvider{ creds: Value{ AccessKeyID: "AKID", @@ -62,8 +62,8 @@ func TestChainProviderWithNoProvider(t *testing.T) { func TestChainProviderWithNoValidProvider(t *testing.T) { p := &ChainProvider{ Providers: []Provider{ - &stubProvider{err: apierr.New("FirstError", "first provider error", nil)}, - &stubProvider{err: apierr.New("SecondError", "second provider error", nil)}, + &stubProvider{err: awserr.New("FirstError", "first provider error", nil)}, + &stubProvider{err: awserr.New("SecondError", "second provider error", nil)}, }, } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/credentials.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/credentials.go index 6f6ec0312..3d6ac4d29 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/credentials.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/credentials.go @@ -93,6 +93,50 @@ type Provider interface { IsExpired() bool } +// A Expiry provides shared expiration logic to be used by credentials +// providers to implement expiry functionality. +// +// The best method to use this struct is as an anonymous field within the +// provider's struct. +// +// Example: +// type EC2RoleProvider struct { +// Expiry +// ... +// } +type Expiry struct { + // The date/time when to expire on + expiration time.Time + + // If set will be used by IsExpired to determine the current time. + // Defaults to time.Now if CurrentTime is not set. Available for testing + // to be able to mock out the current time. + CurrentTime func() time.Time +} + +// SetExpiration sets the expiration IsExpired will check when called. +// +// If window is greater than 0 the expiration time will be reduced by the +// window value. +// +// Using a window is helpful to trigger credentials to expire sooner than +// the expiration time given to ensure no requests are made with expired +// tokens. +func (e *Expiry) SetExpiration(expiration time.Time, window time.Duration) { + e.expiration = expiration + if window > 0 { + e.expiration = e.expiration.Add(-window) + } +} + +// IsExpired returns if the credentials are expired. +func (e *Expiry) IsExpired() bool { + if e.CurrentTime == nil { + e.CurrentTime = time.Now + } + return e.expiration.Before(e.CurrentTime()) +} + // A Credentials provides synchronous safe retrieval of AWS credentials Value. // Credentials will cache the credentials value until they expire. Once the value // expires the next Get will attempt to retrieve valid credentials. @@ -173,6 +217,3 @@ func (c *Credentials) IsExpired() bool { func (c *Credentials) isExpired() bool { return c.forceRefresh || c.provider.IsExpired() } - -// Provide a stub-able time.Now for unit tests so expiry can be tested. -var currentTime = time.Now diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go index 779bb0da4..99c2b4774 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/credentials_test.go @@ -4,7 +4,6 @@ import ( "testing" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/internal/apierr" "github.com/stretchr/testify/assert" ) @@ -40,7 +39,7 @@ func TestCredentialsGet(t *testing.T) { } func TestCredentialsGetWithError(t *testing.T) { - c := NewCredentials(&stubProvider{err: apierr.New("provider error", "", nil), expired: true}) + c := NewCredentials(&stubProvider{err: awserr.New("provider error", "", nil), expired: true}) _, err := c.Get() assert.Equal(t, "provider error", err.(awserr.Error).Code(), "Expected provider error") diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/ec2_role_provider.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/ec2_role_provider.go index ed0c8ba9c..7691b624f 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/ec2_role_provider.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/ec2_role_provider.go @@ -7,7 +7,7 @@ import ( "net/http" "time" - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" ) const metadataCredentialsEndpoint = "http://169.254.169.254/latest/meta-data/iam/security-credentials/" @@ -33,6 +33,8 @@ const metadataCredentialsEndpoint = "http://169.254.169.254/latest/meta-data/iam // } // type EC2RoleProvider struct { + Expiry + // Endpoint must be fully quantified URL Endpoint string @@ -49,9 +51,6 @@ type EC2RoleProvider struct { // // If ExpiryWindow is 0 or less it will be ignored. ExpiryWindow time.Duration - - // The date/time at which the credentials expire. - expiresOn time.Time } // NewEC2RoleCredentials returns a pointer to a new Credentials object @@ -91,7 +90,7 @@ func (m *EC2RoleProvider) Retrieve() (Value, error) { } if len(credsList) == 0 { - return Value{}, apierr.New("EmptyEC2RoleList", "empty EC2 Role list", nil) + return Value{}, awserr.New("EmptyEC2RoleList", "empty EC2 Role list", nil) } credsName := credsList[0] @@ -100,11 +99,7 @@ func (m *EC2RoleProvider) Retrieve() (Value, error) { return Value{}, err } - m.expiresOn = roleCreds.Expiration - if m.ExpiryWindow > 0 { - // Offset based on expiry window if set. - m.expiresOn = m.expiresOn.Add(-m.ExpiryWindow) - } + m.SetExpiration(roleCreds.Expiration, m.ExpiryWindow) return Value{ AccessKeyID: roleCreds.AccessKeyID, @@ -113,11 +108,6 @@ func (m *EC2RoleProvider) Retrieve() (Value, error) { }, nil } -// IsExpired returns if the credentials are expired. -func (m *EC2RoleProvider) IsExpired() bool { - return m.expiresOn.Before(currentTime()) -} - // A ec2RoleCredRespBody provides the shape for deserializing credential // request responses. type ec2RoleCredRespBody struct { @@ -132,7 +122,7 @@ type ec2RoleCredRespBody struct { func requestCredList(client *http.Client, endpoint string) ([]string, error) { resp, err := client.Get(endpoint) if err != nil { - return nil, apierr.New("ListEC2Role", "failed to list EC2 Roles", err) + return nil, awserr.New("ListEC2Role", "failed to list EC2 Roles", err) } defer resp.Body.Close() @@ -143,7 +133,7 @@ func requestCredList(client *http.Client, endpoint string) ([]string, error) { } if err := s.Err(); err != nil { - return nil, apierr.New("ReadEC2Role", "failed to read list of EC2 Roles", err) + return nil, awserr.New("ReadEC2Role", "failed to read list of EC2 Roles", err) } return credsList, nil @@ -156,7 +146,7 @@ func requestCredList(client *http.Client, endpoint string) ([]string, error) { func requestCred(client *http.Client, endpoint, credsName string) (*ec2RoleCredRespBody, error) { resp, err := client.Get(endpoint + credsName) if err != nil { - return nil, apierr.New("GetEC2RoleCredentials", + return nil, awserr.New("GetEC2RoleCredentials", fmt.Sprintf("failed to get %s EC2 Role credentials", credsName), err) } @@ -164,7 +154,7 @@ func requestCred(client *http.Client, endpoint, credsName string) (*ec2RoleCredR respCreds := &ec2RoleCredRespBody{} if err := json.NewDecoder(resp.Body).Decode(respCreds); err != nil { - return nil, apierr.New("DecodeEC2RoleCredentials", + return nil, awserr.New("DecodeEC2RoleCredentials", fmt.Sprintf("failed to decode %s EC2 Role credentials", credsName), err) } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/ec2_role_provider_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/ec2_role_provider_test.go index 5232a1dca..da1549a4f 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/ec2_role_provider_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/ec2_role_provider_test.go @@ -45,10 +45,7 @@ func TestEC2RoleProviderIsExpired(t *testing.T) { defer server.Close() p := &EC2RoleProvider{Client: http.DefaultClient, Endpoint: server.URL} - defer func() { - currentTime = time.Now - }() - currentTime = func() time.Time { + p.CurrentTime = func() time.Time { return time.Date(2014, 12, 15, 21, 26, 0, 0, time.UTC) } @@ -59,7 +56,7 @@ func TestEC2RoleProviderIsExpired(t *testing.T) { assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve.") - currentTime = func() time.Time { + p.CurrentTime = func() time.Time { return time.Date(3014, 12, 15, 21, 26, 0, 0, time.UTC) } @@ -71,10 +68,7 @@ func TestEC2RoleProviderExpiryWindowIsExpired(t *testing.T) { defer server.Close() p := &EC2RoleProvider{Client: http.DefaultClient, Endpoint: server.URL, ExpiryWindow: time.Hour * 1} - defer func() { - currentTime = time.Now - }() - currentTime = func() time.Time { + p.CurrentTime = func() time.Time { return time.Date(2014, 12, 15, 0, 51, 37, 0, time.UTC) } @@ -85,7 +79,7 @@ func TestEC2RoleProviderExpiryWindowIsExpired(t *testing.T) { assert.False(t, p.IsExpired(), "Expect creds to not be expired after retrieve.") - currentTime = func() time.Time { + p.CurrentTime = func() time.Time { return time.Date(2014, 12, 16, 0, 55, 37, 0, time.UTC) } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go index e9c575292..3e556be7f 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go @@ -3,16 +3,16 @@ package credentials import ( "os" - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" ) var ( // ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be // found in the process's environment. - ErrAccessKeyIDNotFound = apierr.New("EnvAccessKeyNotFound", "AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment", nil) + ErrAccessKeyIDNotFound = awserr.New("EnvAccessKeyNotFound", "AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment", nil) // ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key // can't be found in the process's environment. - ErrSecretAccessKeyNotFound = apierr.New("EnvSecretNotFound", "AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment", nil) + ErrSecretAccessKeyNotFound = awserr.New("EnvSecretNotFound", "AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment", nil) ) // A EnvProvider retrieves credentials from the environment variables of the diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go index d61b140be..7367f733a 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go @@ -7,12 +7,12 @@ import ( "github.com/vaughan0/go-ini" - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" ) var ( // ErrSharedCredentialsHomeNotFound is emitted when the user directory cannot be found. - ErrSharedCredentialsHomeNotFound = apierr.New("UserHomeNotFound", "user home directory not found.", nil) + ErrSharedCredentialsHomeNotFound = awserr.New("UserHomeNotFound", "user home directory not found.", nil) ) // A SharedCredentialsProvider retrieves credentials from the current user's home @@ -72,20 +72,20 @@ func (p *SharedCredentialsProvider) IsExpired() bool { func loadProfile(filename, profile string) (Value, error) { config, err := ini.LoadFile(filename) if err != nil { - return Value{}, apierr.New("SharedCredsLoad", "failed to load shared credentials file", err) + return Value{}, awserr.New("SharedCredsLoad", "failed to load shared credentials file", err) } iniProfile := config.Section(profile) id, ok := iniProfile["aws_access_key_id"] if !ok { - return Value{}, apierr.New("SharedCredsAccessKey", + return Value{}, awserr.New("SharedCredsAccessKey", fmt.Sprintf("shared credentials %s in %s did not contain aws_access_key_id", profile, filename), nil) } secret, ok := iniProfile["aws_secret_access_key"] if !ok { - return Value{}, apierr.New("SharedCredsSecret", + return Value{}, awserr.New("SharedCredsSecret", fmt.Sprintf("shared credentials %s in %s did not contain aws_secret_access_key", profile, filename), nil) } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go index 4466cd263..a11471362 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go @@ -1,12 +1,12 @@ package credentials import ( - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" ) var ( // ErrStaticCredentialsEmpty is emitted when static credentials are empty. - ErrStaticCredentialsEmpty = apierr.New("EmptyStaticCreds", "static credentials are empty", nil) + ErrStaticCredentialsEmpty = awserr.New("EmptyStaticCreds", "static credentials are empty", nil) ) // A StaticProvider is a set of credentials which are set pragmatically, diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go new file mode 100644 index 000000000..1499b4497 --- /dev/null +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go @@ -0,0 +1,120 @@ +// Package stscreds are credential Providers to retrieve STS AWS credentials. +// +// STS provides multiple ways to retrieve credentials which can be used when making +// future AWS service API operation calls. +package stscreds + +import ( + "fmt" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/credentials" + "github.com/aws/aws-sdk-go/service/sts" + "time" +) + +// AssumeRoler represents the minimal subset of the STS client API used by this provider. +type AssumeRoler interface { + AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) +} + +// AssumeRoleProvider retrieves temporary credentials from the STS service, and +// keeps track of their expiration time. This provider must be used explicitly, +// as it is not included in the credentials chain. +// +// Example how to configure a service to use this provider: +// +// config := &aws.Config{ +// Credentials: stscreds.NewCredentials(nil, "arn-of-the-role-to-assume", 10*time.Second), +// }) +// // Use config for creating your AWS service. +// +// Example how to obtain customised credentials: +// +// provider := &stscreds.Provider{ +// // Extend the duration to 1 hour. +// Duration: time.Hour, +// // Custom role name. +// RoleSessionName: "custom-session-name", +// } +// creds := credentials.NewCredentials(provider) +// +type AssumeRoleProvider struct { + credentials.Expiry + + // Custom STS client. If not set the default STS client will be used. + Client AssumeRoler + + // Role to be assumed. + RoleARN string + + // Session name, if you wish to reuse the credentials elsewhere. + RoleSessionName string + + // Expiry duration of the STS credentials. Defaults to 15 minutes if not set. + Duration time.Duration + + // ExpiryWindow will allow the credentials to trigger refreshing prior to + // the credentials actually expiring. This is beneficial so race conditions + // with expiring credentials do not cause request to fail unexpectedly + // due to ExpiredTokenException exceptions. + // + // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true + // 10 seconds before the credentials are actually expired. + // + // If ExpiryWindow is 0 or less it will be ignored. + ExpiryWindow time.Duration +} + +// NewCredentials returns a pointer to a new Credentials object wrapping the +// AssumeRoleProvider. The credentials will expire every 15 minutes and the +// role will be named after a nanosecond timestamp of this operation. +// +// The sts and roleARN parameters are used for building the "AssumeRole" call. +// Pass nil as sts to use the default client. +// +// Window is the expiry window that will be subtracted from the expiry returned +// by the role credential request. This is done so that the credentials will +// expire sooner than their actual lifespan. +func NewCredentials(client AssumeRoler, roleARN string, window time.Duration) *credentials.Credentials { + return credentials.NewCredentials(&AssumeRoleProvider{ + Client: client, + RoleARN: roleARN, + ExpiryWindow: window, + }) +} + +// Retrieve generates a new set of temporary credentials using STS. +func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) { + + // Apply defaults where parameters are not set. + if p.Client == nil { + p.Client = sts.New(nil) + } + if p.RoleSessionName == "" { + // Try to work out a role name that will hopefully end up unique. + p.RoleSessionName = fmt.Sprintf("%d", time.Now().UTC().UnixNano()) + } + if p.Duration == 0 { + // Expire as often as AWS permits. + p.Duration = 15 * time.Minute + } + + roleOutput, err := p.Client.AssumeRole(&sts.AssumeRoleInput{ + DurationSeconds: aws.Long(int64(p.Duration / time.Second)), + RoleARN: aws.String(p.RoleARN), + RoleSessionName: aws.String(p.RoleSessionName), + }) + + if err != nil { + return credentials.Value{}, err + } + + // We will proactively generate new credentials before they expire. + p.SetExpiration(*roleOutput.Credentials.Expiration, p.ExpiryWindow) + + return credentials.Value{ + AccessKeyID: *roleOutput.Credentials.AccessKeyID, + SecretAccessKey: *roleOutput.Credentials.SecretAccessKey, + SessionToken: *roleOutput.Credentials.SessionToken, + }, nil +} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go new file mode 100644 index 000000000..98b769002 --- /dev/null +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider_test.go @@ -0,0 +1,58 @@ +package stscreds + +import ( + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/sts" + "github.com/stretchr/testify/assert" + "testing" + "time" +) + +type stubSTS struct { +} + +func (s *stubSTS) AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) { + expiry := time.Now().Add(60 * time.Minute) + return &sts.AssumeRoleOutput{ + Credentials: &sts.Credentials{ + // Just reflect the role arn to the provider. + AccessKeyID: input.RoleARN, + SecretAccessKey: aws.String("assumedSecretAccessKey"), + SessionToken: aws.String("assumedSessionToken"), + Expiration: &expiry, + }, + }, nil +} + +func TestAssumeRoleProvider(t *testing.T) { + stub := &stubSTS{} + p := &AssumeRoleProvider{ + Client: stub, + RoleARN: "roleARN", + } + + creds, err := p.Retrieve() + assert.Nil(t, err, "Expect no error") + + assert.Equal(t, "roleARN", creds.AccessKeyID, "Expect access key ID to be reflected role ARN") + assert.Equal(t, "assumedSecretAccessKey", creds.SecretAccessKey, "Expect secret access key to match") + assert.Equal(t, "assumedSessionToken", creds.SessionToken, "Expect session token to match") +} + +func BenchmarkAssumeRoleProvider(b *testing.B) { + stub := &stubSTS{} + p := &AssumeRoleProvider{ + Client: stub, + RoleARN: "roleARN", + } + + b.ResetTimer() + b.RunParallel(func(pb *testing.PB) { + for pb.Next() { + _, err := p.Retrieve() + if err != nil { + b.Fatal(err) + } + } + }) +} diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/handler_functions.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/handler_functions.go index e15ab8291..a2a88a919 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/handler_functions.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/handler_functions.go @@ -12,7 +12,6 @@ import ( "time" "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/internal/apierr" ) var sleepDelay = func(delay time.Duration) { @@ -80,8 +79,17 @@ func SendHandler(r *Request) { return } } + if r.HTTPRequest == nil { + // Add a dummy request response object to ensure the HTTPResponse + // value is consistent. + r.HTTPResponse = &http.Response{ + StatusCode: int(0), + Status: http.StatusText(int(0)), + Body: ioutil.NopCloser(bytes.NewReader([]byte{})), + } + } // Catch all other request errors. - r.Error = apierr.New("RequestError", "send request failed", err) + r.Error = awserr.New("RequestError", "send request failed", err) r.Retryable.Set(true) // network errors are retryable } } @@ -90,7 +98,7 @@ func SendHandler(r *Request) { func ValidateResponseHandler(r *Request) { if r.HTTPResponse.StatusCode == 0 || r.HTTPResponse.StatusCode >= 300 { // this may be replaced by an UnmarshalError handler - r.Error = apierr.New("UnknownError", "unknown error", nil) + r.Error = awserr.New("UnknownError", "unknown error", nil) } } @@ -114,8 +122,6 @@ func AfterRetryHandler(r *Request) { if err, ok := r.Error.(awserr.Error); ok { if isCodeExpiredCreds(err.Code()) { r.Config.Credentials.Expire() - // The credentials will need to be resigned with new credentials - r.signed = false } } } @@ -128,11 +134,11 @@ func AfterRetryHandler(r *Request) { var ( // ErrMissingRegion is an error that is returned if region configuration is // not found. - ErrMissingRegion error = apierr.New("MissingRegion", "could not find region configuration", nil) + ErrMissingRegion error = awserr.New("MissingRegion", "could not find region configuration", nil) // ErrMissingEndpoint is an error that is returned if an endpoint cannot be // resolved for a service. - ErrMissingEndpoint error = apierr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil) + ErrMissingEndpoint error = awserr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil) ) // ValidateEndpointHandler is a request handler to validate a request had the diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/handler_functions_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/handler_functions_test.go index 822db9fe2..c6a30c0fc 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/handler_functions_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/handler_functions_test.go @@ -5,8 +5,8 @@ import ( "os" "testing" + "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/internal/apierr" "github.com/stretchr/testify/assert" ) @@ -56,11 +56,11 @@ func TestAfterRetryRefreshCreds(t *testing.T) { svc.Handlers.Clear() svc.Handlers.ValidateResponse.PushBack(func(r *Request) { - r.Error = apierr.New("UnknownError", "", nil) + r.Error = awserr.New("UnknownError", "", nil) r.HTTPResponse = &http.Response{StatusCode: 400} }) svc.Handlers.UnmarshalError.PushBack(func(r *Request) { - r.Error = apierr.New("ExpiredTokenException", "", nil) + r.Error = awserr.New("ExpiredTokenException", "", nil) }) svc.Handlers.AfterRetry.PushBack(func(r *Request) { AfterRetryHandler(r) diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/param_validator.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/param_validator.go index 7c1377281..b4e95cebd 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/param_validator.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/param_validator.go @@ -5,7 +5,7 @@ import ( "reflect" "strings" - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" ) // ValidateParameters is a request handler to validate the input parameters. @@ -18,7 +18,7 @@ func ValidateParameters(r *Request) { if count := len(v.errors); count > 0 { format := "%d validation errors:\n- %s" msg := fmt.Sprintf(format, count, strings.Join(v.errors, "\n- ")) - r.Error = apierr.New("InvalidParameter", msg, nil) + r.Error = awserr.New("InvalidParameter", msg, nil) } } } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/param_validator_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/param_validator_test.go index 665156730..b8239f4a7 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/param_validator_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/param_validator_test.go @@ -41,8 +41,8 @@ func TestNoErrors(t *testing.T) { input := &StructShape{ RequiredList: []*ConditionalStructShape{}, RequiredMap: map[string]*ConditionalStructShape{ - "key1": &ConditionalStructShape{Name: aws.String("Name")}, - "key2": &ConditionalStructShape{Name: aws.String("Name")}, + "key1": {Name: aws.String("Name")}, + "key2": {Name: aws.String("Name")}, }, RequiredBool: aws.Boolean(true), OptionalStruct: &ConditionalStructShape{Name: aws.String("Name")}, @@ -65,10 +65,10 @@ func TestMissingRequiredParameters(t *testing.T) { func TestNestedMissingRequiredParameters(t *testing.T) { input := &StructShape{ - RequiredList: []*ConditionalStructShape{&ConditionalStructShape{}}, + RequiredList: []*ConditionalStructShape{{}}, RequiredMap: map[string]*ConditionalStructShape{ - "key1": &ConditionalStructShape{Name: aws.String("Name")}, - "key2": &ConditionalStructShape{}, + "key1": {Name: aws.String("Name")}, + "key2": {}, }, RequiredBool: aws.Boolean(true), OptionalStruct: &ConditionalStructShape{}, diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request.go index 6473a642a..68d1a4dd1 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request.go @@ -32,8 +32,7 @@ type Request struct { Retryable SettableBool RetryDelay time.Duration - built bool - signed bool + built bool } // An Operation is the service API operation to be made. @@ -164,17 +163,12 @@ func (r *Request) Build() error { // Send will build the request prior to signing. All Sign Handlers will // be executed in the order they were set. func (r *Request) Sign() error { - if r.signed { - return r.Error - } - r.Build() if r.Error != nil { return r.Error } r.Handlers.Sign.Run(r) - r.signed = r.Error != nil return r.Error } @@ -203,6 +197,7 @@ func (r *Request) Send() error { if r.Error != nil { return r.Error } + continue } r.Handlers.UnmarshalMeta.Run(r) diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request_pagination_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request_pagination_test.go index eabd9aea7..35b7ee8d9 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request_pagination_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request_pagination_test.go @@ -19,9 +19,9 @@ func TestPagination(t *testing.T) { reqNum := 0 resps := []*dynamodb.ListTablesOutput{ - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table5")}}, + {TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, + {TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, + {TableNames: []*string{aws.String("Table5")}}, } db.Handlers.Send.Clear() // mock sending @@ -71,9 +71,9 @@ func TestPaginationEachPage(t *testing.T) { reqNum := 0 resps := []*dynamodb.ListTablesOutput{ - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table5")}}, + {TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, + {TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, + {TableNames: []*string{aws.String("Table5")}}, } db.Handlers.Send.Clear() // mock sending @@ -124,9 +124,9 @@ func TestPaginationEarlyExit(t *testing.T) { reqNum := 0 resps := []*dynamodb.ListTablesOutput{ - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("Table5")}}, + {TableNames: []*string{aws.String("Table1"), aws.String("Table2")}, LastEvaluatedTableName: aws.String("Table2")}, + {TableNames: []*string{aws.String("Table3"), aws.String("Table4")}, LastEvaluatedTableName: aws.String("Table4")}, + {TableNames: []*string{aws.String("Table5")}}, } db.Handlers.Send.Clear() // mock sending @@ -189,10 +189,10 @@ func TestPaginationTruncation(t *testing.T) { reqNum := &count resps := []*s3.ListObjectsOutput{ - &s3.ListObjectsOutput{IsTruncated: aws.Boolean(true), Contents: []*s3.Object{&s3.Object{Key: aws.String("Key1")}}}, - &s3.ListObjectsOutput{IsTruncated: aws.Boolean(true), Contents: []*s3.Object{&s3.Object{Key: aws.String("Key2")}}}, - &s3.ListObjectsOutput{IsTruncated: aws.Boolean(false), Contents: []*s3.Object{&s3.Object{Key: aws.String("Key3")}}}, - &s3.ListObjectsOutput{IsTruncated: aws.Boolean(true), Contents: []*s3.Object{&s3.Object{Key: aws.String("Key4")}}}, + {IsTruncated: aws.Boolean(true), Contents: []*s3.Object{{Key: aws.String("Key1")}}}, + {IsTruncated: aws.Boolean(true), Contents: []*s3.Object{{Key: aws.String("Key2")}}}, + {IsTruncated: aws.Boolean(false), Contents: []*s3.Object{{Key: aws.String("Key3")}}}, + {IsTruncated: aws.Boolean(true), Contents: []*s3.Object{{Key: aws.String("Key4")}}}, } client.Handlers.Send.Clear() // mock sending @@ -232,20 +232,20 @@ func TestPaginationTruncation(t *testing.T) { // Benchmarks var benchResps = []*dynamodb.ListTablesOutput{ - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, - &dynamodb.ListTablesOutput{TableNames: []*string{aws.String("TABLE")}}, + {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, + {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, + {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, + {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, + {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, + {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, + {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, + {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, + {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, + {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, + {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, + {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, + {TableNames: []*string{aws.String("TABLE"), aws.String("NXT")}, LastEvaluatedTableName: aws.String("NXT")}, + {TableNames: []*string{aws.String("TABLE")}}, } var benchDb = func() *dynamodb.DynamoDB { diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request_test.go index 27507f039..fcb471872 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/request_test.go @@ -13,7 +13,6 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/internal/apierr" "github.com/stretchr/testify/assert" ) @@ -36,12 +35,12 @@ func unmarshal(req *Request) { func unmarshalError(req *Request) { bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body) if err != nil { - req.Error = apierr.New("UnmarshaleError", req.HTTPResponse.Status, err) + req.Error = awserr.New("UnmarshaleError", req.HTTPResponse.Status, err) return } if len(bodyBytes) == 0 { - req.Error = apierr.NewRequestError( - apierr.New("UnmarshaleError", req.HTTPResponse.Status, fmt.Errorf("empty body")), + req.Error = awserr.NewRequestFailure( + awserr.New("UnmarshaleError", req.HTTPResponse.Status, fmt.Errorf("empty body")), req.HTTPResponse.StatusCode, "", ) @@ -49,11 +48,11 @@ func unmarshalError(req *Request) { } var jsonErr jsonErrorResponse if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil { - req.Error = apierr.New("UnmarshaleError", "JSON unmarshal", err) + req.Error = awserr.New("UnmarshaleError", "JSON unmarshal", err) return } - req.Error = apierr.NewRequestError( - apierr.New(jsonErr.Code, jsonErr.Message, nil), + req.Error = awserr.NewRequestFailure( + awserr.New(jsonErr.Code, jsonErr.Message, nil), req.HTTPResponse.StatusCode, "", ) @@ -68,9 +67,9 @@ type jsonErrorResponse struct { func TestRequestRecoverRetry5xx(t *testing.T) { reqNum := 0 reqs := []http.Response{ - http.Response{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - http.Response{StatusCode: 501, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - http.Response{StatusCode: 200, Body: body(`{"data":"valid"}`)}, + {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, + {StatusCode: 501, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, + {StatusCode: 200, Body: body(`{"data":"valid"}`)}, } s := NewService(&Config{MaxRetries: 10}) @@ -94,9 +93,9 @@ func TestRequestRecoverRetry5xx(t *testing.T) { func TestRequestRecoverRetry4xxRetryable(t *testing.T) { reqNum := 0 reqs := []http.Response{ - http.Response{StatusCode: 400, Body: body(`{"__type":"Throttling","message":"Rate exceeded."}`)}, - http.Response{StatusCode: 429, Body: body(`{"__type":"ProvisionedThroughputExceededException","message":"Rate exceeded."}`)}, - http.Response{StatusCode: 200, Body: body(`{"data":"valid"}`)}, + {StatusCode: 400, Body: body(`{"__type":"Throttling","message":"Rate exceeded."}`)}, + {StatusCode: 429, Body: body(`{"__type":"ProvisionedThroughputExceededException","message":"Rate exceeded."}`)}, + {StatusCode: 200, Body: body(`{"data":"valid"}`)}, } s := NewService(&Config{MaxRetries: 10}) @@ -148,10 +147,10 @@ func TestRequestExhaustRetries(t *testing.T) { reqNum := 0 reqs := []http.Response{ - http.Response{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - http.Response{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - http.Response{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, - http.Response{StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, + {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, + {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, + {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, + {StatusCode: 500, Body: body(`{"__type":"UnknownError","message":"An error occurred."}`)}, } s := NewService(&Config{MaxRetries: -1}) @@ -181,8 +180,8 @@ func TestRequestExhaustRetries(t *testing.T) { func TestRequestRecoverExpiredCreds(t *testing.T) { reqNum := 0 reqs := []http.Response{ - http.Response{StatusCode: 400, Body: body(`{"__type":"ExpiredTokenException","message":"expired token"}`)}, - http.Response{StatusCode: 200, Body: body(`{"data":"valid"}`)}, + {StatusCode: 400, Body: body(`{"__type":"ExpiredTokenException","message":"expired token"}`)}, + {StatusCode: 200, Body: body(`{"data":"valid"}`)}, } s := NewService(&Config{MaxRetries: 10, Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "")}) diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service.go index 3e862f8ea..42d1be4ee 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/service.go @@ -136,17 +136,18 @@ func retryRules(r *Request) time.Duration { // retryableCodes is a collection of service response codes which are retry-able // without any further action. var retryableCodes = map[string]struct{}{ - "ProvisionedThroughputExceededException": struct{}{}, - "Throttling": struct{}{}, + "RequestError": {}, + "ProvisionedThroughputExceededException": {}, + "Throttling": {}, } // credsExpiredCodes is a collection of error codes which signify the credentials // need to be refreshed. Expired tokens require refreshing of credentials, and // resigning before the request can be retried. var credsExpiredCodes = map[string]struct{}{ - "ExpiredToken": struct{}{}, - "ExpiredTokenException": struct{}{}, - "RequestExpired": struct{}{}, // EC2 Only + "ExpiredToken": {}, + "ExpiredTokenException": {}, + "RequestExpired": {}, // EC2 Only } func isCodeRetryable(code string) bool { diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/version.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/version.go index 7c156dbe2..94b8c729f 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/version.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/version.go @@ -5,4 +5,4 @@ package aws const SDKName = "aws-sdk-go" // SDKVersion is the version of this SDK -const SDKVersion = "0.6.0" +const SDKVersion = "0.6.4" diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/endpoints/endpoints.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/endpoints/endpoints.go index 8298a5b20..d040cccd5 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/endpoints/endpoints.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/endpoints/endpoints.go @@ -1,6 +1,8 @@ +// Package endpoints validates regional endpoints for services. package endpoints //go:generate go run ../model/cli/gen-endpoints/main.go endpoints.json endpoints_map.go +//go:generate gofmt -s -w endpoints_map.go import "strings" diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/endpoints/endpoints_map.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/endpoints/endpoints_map.go index 637fcbe43..894c1a643 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/endpoints/endpoints_map.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/endpoints/endpoints_map.go @@ -15,74 +15,74 @@ type endpointEntry struct { var endpointsMap = endpointStruct{ Version: 2, Endpoints: map[string]endpointEntry{ - "*/*": endpointEntry{ + "*/*": { Endpoint: "{service}.{region}.amazonaws.com", }, - "*/cloudfront": endpointEntry{ + "*/cloudfront": { Endpoint: "cloudfront.amazonaws.com", SigningRegion: "us-east-1", }, - "*/cloudsearchdomain": endpointEntry{ + "*/cloudsearchdomain": { Endpoint: "", SigningRegion: "us-east-1", }, - "*/iam": endpointEntry{ + "*/iam": { Endpoint: "iam.amazonaws.com", SigningRegion: "us-east-1", }, - "*/importexport": endpointEntry{ + "*/importexport": { Endpoint: "importexport.amazonaws.com", SigningRegion: "us-east-1", }, - "*/route53": endpointEntry{ + "*/route53": { Endpoint: "route53.amazonaws.com", SigningRegion: "us-east-1", }, - "*/sts": endpointEntry{ + "*/sts": { Endpoint: "sts.amazonaws.com", SigningRegion: "us-east-1", }, - "ap-northeast-1/s3": endpointEntry{ + "ap-northeast-1/s3": { Endpoint: "s3-{region}.amazonaws.com", }, - "ap-southeast-1/s3": endpointEntry{ + "ap-southeast-1/s3": { Endpoint: "s3-{region}.amazonaws.com", }, - "ap-southeast-2/s3": endpointEntry{ + "ap-southeast-2/s3": { Endpoint: "s3-{region}.amazonaws.com", }, - "cn-north-1/*": endpointEntry{ + "cn-north-1/*": { Endpoint: "{service}.{region}.amazonaws.com.cn", }, - "eu-central-1/s3": endpointEntry{ + "eu-central-1/s3": { Endpoint: "{service}.{region}.amazonaws.com", }, - "eu-west-1/s3": endpointEntry{ + "eu-west-1/s3": { Endpoint: "s3-{region}.amazonaws.com", }, - "sa-east-1/s3": endpointEntry{ + "sa-east-1/s3": { Endpoint: "s3-{region}.amazonaws.com", }, - "us-east-1/s3": endpointEntry{ + "us-east-1/s3": { Endpoint: "s3.amazonaws.com", }, - "us-east-1/sdb": endpointEntry{ + "us-east-1/sdb": { Endpoint: "sdb.amazonaws.com", SigningRegion: "us-east-1", }, - "us-gov-west-1/iam": endpointEntry{ + "us-gov-west-1/iam": { Endpoint: "iam.us-gov.amazonaws.com", }, - "us-gov-west-1/s3": endpointEntry{ + "us-gov-west-1/s3": { Endpoint: "s3-{region}.amazonaws.com", }, - "us-gov-west-1/sts": endpointEntry{ + "us-gov-west-1/sts": { Endpoint: "sts.us-gov-west-1.amazonaws.com", }, - "us-west-1/s3": endpointEntry{ + "us-west-1/s3": { Endpoint: "s3-{region}.amazonaws.com", }, - "us-west-2/s3": endpointEntry{ + "us-west-2/s3": { Endpoint: "s3-{region}.amazonaws.com", }, }, diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build.go index c7c95627d..c4d8dd263 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build.go @@ -1,3 +1,4 @@ +// Package query provides serialisation of AWS query requests, and responses. package query //go:generate go run ../../fixtures/protocol/generate.go ../../fixtures/protocol/input/query.json build_test.go @@ -6,7 +7,7 @@ import ( "net/url" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/internal/protocol/query/queryutil" ) @@ -17,7 +18,7 @@ func Build(r *aws.Request) { "Version": {r.Service.APIVersion}, } if err := queryutil.Parse(body, r.Params, false); err != nil { - r.Error = apierr.New("Marshal", "failed encoding Query request", err) + r.Error = awserr.New("SerializationError", "failed encoding Query request", err) return } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build_test.go index da266758b..b54829838 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/build_test.go @@ -1,10 +1,6 @@ package query_test import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/protocol/query" - "github.com/aws/aws-sdk-go/internal/signer/v4" - "bytes" "encoding/json" "encoding/xml" @@ -15,7 +11,10 @@ import ( "testing" "time" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/internal/protocol/query" "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" + "github.com/aws/aws-sdk-go/internal/signer/v4" "github.com/aws/aws-sdk-go/internal/util" "github.com/stretchr/testify/assert" ) @@ -63,20 +62,19 @@ func (c *InputService1ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService1TestCaseOperation1 = "OperationName" + // InputService1TestCaseOperation1Request generates a request for the InputService1TestCaseOperation1 operation. func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputShape) (req *aws.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) { - - if opInputService1TestCaseOperation1 == nil { - opInputService1TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService1TestCaseOperation1, } if input == nil { input = &InputService1TestShapeInputShape{} } - req = c.newRequest(opInputService1TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService1TestShapeInputService1TestCaseOperation1Output{} req.Data = output return @@ -88,8 +86,6 @@ func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *Input return out, err } -var opInputService1TestCaseOperation1 *aws.Operation - type InputService1TestShapeInputService1TestCaseOperation1Output struct { metadataInputService1TestShapeInputService1TestCaseOperation1Output `json:"-" xml:"-"` } @@ -142,20 +138,19 @@ func (c *InputService2ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService2TestCaseOperation1 = "OperationName" + // InputService2TestCaseOperation1Request generates a request for the InputService2TestCaseOperation1 operation. func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputShape) (req *aws.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) { - - if opInputService2TestCaseOperation1 == nil { - opInputService2TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService2TestCaseOperation1, } if input == nil { input = &InputService2TestShapeInputShape{} } - req = c.newRequest(opInputService2TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService2TestShapeInputService2TestCaseOperation1Output{} req.Data = output return @@ -167,8 +162,6 @@ func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *Input return out, err } -var opInputService2TestCaseOperation1 *aws.Operation - type InputService2TestShapeInputService2TestCaseOperation1Output struct { metadataInputService2TestShapeInputService2TestCaseOperation1Output `json:"-" xml:"-"` } @@ -229,20 +222,19 @@ func (c *InputService3ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService3TestCaseOperation1 = "OperationName" + // InputService3TestCaseOperation1Request generates a request for the InputService3TestCaseOperation1 operation. func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputShape) (req *aws.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) { - - if opInputService3TestCaseOperation1 == nil { - opInputService3TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService3TestCaseOperation1, } if input == nil { input = &InputService3TestShapeInputShape{} } - req = c.newRequest(opInputService3TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService3TestShapeInputService3TestCaseOperation1Output{} req.Data = output return @@ -254,22 +246,19 @@ func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *Input return out, err } -var opInputService3TestCaseOperation1 *aws.Operation +const opInputService3TestCaseOperation2 = "OperationName" // InputService3TestCaseOperation2Request generates a request for the InputService3TestCaseOperation2 operation. func (c *InputService3ProtocolTest) InputService3TestCaseOperation2Request(input *InputService3TestShapeInputShape) (req *aws.Request, output *InputService3TestShapeInputService3TestCaseOperation2Output) { - - if opInputService3TestCaseOperation2 == nil { - opInputService3TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService3TestCaseOperation2, } if input == nil { input = &InputService3TestShapeInputShape{} } - req = c.newRequest(opInputService3TestCaseOperation2, input, output) + req = c.newRequest(op, input, output) output = &InputService3TestShapeInputService3TestCaseOperation2Output{} req.Data = output return @@ -281,8 +270,6 @@ func (c *InputService3ProtocolTest) InputService3TestCaseOperation2(input *Input return out, err } -var opInputService3TestCaseOperation2 *aws.Operation - type InputService3TestShapeInputService3TestCaseOperation1Output struct { metadataInputService3TestShapeInputService3TestCaseOperation1Output `json:"-" xml:"-"` } @@ -341,20 +328,19 @@ func (c *InputService4ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService4TestCaseOperation1 = "OperationName" + // InputService4TestCaseOperation1Request generates a request for the InputService4TestCaseOperation1 operation. func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputShape) (req *aws.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) { - - if opInputService4TestCaseOperation1 == nil { - opInputService4TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService4TestCaseOperation1, } if input == nil { input = &InputService4TestShapeInputShape{} } - req = c.newRequest(opInputService4TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService4TestShapeInputService4TestCaseOperation1Output{} req.Data = output return @@ -366,22 +352,19 @@ func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *Input return out, err } -var opInputService4TestCaseOperation1 *aws.Operation +const opInputService4TestCaseOperation2 = "OperationName" // InputService4TestCaseOperation2Request generates a request for the InputService4TestCaseOperation2 operation. func (c *InputService4ProtocolTest) InputService4TestCaseOperation2Request(input *InputService4TestShapeInputShape) (req *aws.Request, output *InputService4TestShapeInputService4TestCaseOperation2Output) { - - if opInputService4TestCaseOperation2 == nil { - opInputService4TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService4TestCaseOperation2, } if input == nil { input = &InputService4TestShapeInputShape{} } - req = c.newRequest(opInputService4TestCaseOperation2, input, output) + req = c.newRequest(op, input, output) output = &InputService4TestShapeInputService4TestCaseOperation2Output{} req.Data = output return @@ -393,8 +376,6 @@ func (c *InputService4ProtocolTest) InputService4TestCaseOperation2(input *Input return out, err } -var opInputService4TestCaseOperation2 *aws.Operation - type InputService4TestShapeInputService4TestCaseOperation1Output struct { metadataInputService4TestShapeInputService4TestCaseOperation1Output `json:"-" xml:"-"` } @@ -455,20 +436,19 @@ func (c *InputService5ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService5TestCaseOperation1 = "OperationName" + // InputService5TestCaseOperation1Request generates a request for the InputService5TestCaseOperation1 operation. func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputShape) (req *aws.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) { - - if opInputService5TestCaseOperation1 == nil { - opInputService5TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService5TestCaseOperation1, } if input == nil { input = &InputService5TestShapeInputShape{} } - req = c.newRequest(opInputService5TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService5TestShapeInputService5TestCaseOperation1Output{} req.Data = output return @@ -480,22 +460,19 @@ func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *Input return out, err } -var opInputService5TestCaseOperation1 *aws.Operation +const opInputService5TestCaseOperation2 = "OperationName" // InputService5TestCaseOperation2Request generates a request for the InputService5TestCaseOperation2 operation. func (c *InputService5ProtocolTest) InputService5TestCaseOperation2Request(input *InputService5TestShapeInputShape) (req *aws.Request, output *InputService5TestShapeInputService5TestCaseOperation2Output) { - - if opInputService5TestCaseOperation2 == nil { - opInputService5TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService5TestCaseOperation2, } if input == nil { input = &InputService5TestShapeInputShape{} } - req = c.newRequest(opInputService5TestCaseOperation2, input, output) + req = c.newRequest(op, input, output) output = &InputService5TestShapeInputService5TestCaseOperation2Output{} req.Data = output return @@ -507,8 +484,6 @@ func (c *InputService5ProtocolTest) InputService5TestCaseOperation2(input *Input return out, err } -var opInputService5TestCaseOperation2 *aws.Operation - type InputService5TestShapeInputService5TestCaseOperation1Output struct { metadataInputService5TestShapeInputService5TestCaseOperation1Output `json:"-" xml:"-"` } @@ -567,20 +542,19 @@ func (c *InputService6ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService6TestCaseOperation1 = "OperationName" + // InputService6TestCaseOperation1Request generates a request for the InputService6TestCaseOperation1 operation. func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputShape) (req *aws.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) { - - if opInputService6TestCaseOperation1 == nil { - opInputService6TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService6TestCaseOperation1, } if input == nil { input = &InputService6TestShapeInputShape{} } - req = c.newRequest(opInputService6TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService6TestShapeInputService6TestCaseOperation1Output{} req.Data = output return @@ -592,8 +566,6 @@ func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *Input return out, err } -var opInputService6TestCaseOperation1 *aws.Operation - type InputService6TestShapeInputService6TestCaseOperation1Output struct { metadataInputService6TestShapeInputService6TestCaseOperation1Output `json:"-" xml:"-"` } @@ -644,20 +616,19 @@ func (c *InputService7ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService7TestCaseOperation1 = "OperationName" + // InputService7TestCaseOperation1Request generates a request for the InputService7TestCaseOperation1 operation. func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputShape) (req *aws.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) { - - if opInputService7TestCaseOperation1 == nil { - opInputService7TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService7TestCaseOperation1, } if input == nil { input = &InputService7TestShapeInputShape{} } - req = c.newRequest(opInputService7TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService7TestShapeInputService7TestCaseOperation1Output{} req.Data = output return @@ -669,8 +640,6 @@ func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *Input return out, err } -var opInputService7TestCaseOperation1 *aws.Operation - type InputService7TestShapeInputService7TestCaseOperation1Output struct { metadataInputService7TestShapeInputService7TestCaseOperation1Output `json:"-" xml:"-"` } @@ -721,20 +690,19 @@ func (c *InputService8ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService8TestCaseOperation1 = "OperationName" + // InputService8TestCaseOperation1Request generates a request for the InputService8TestCaseOperation1 operation. func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputShape) (req *aws.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) { - - if opInputService8TestCaseOperation1 == nil { - opInputService8TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService8TestCaseOperation1, } if input == nil { input = &InputService8TestShapeInputShape{} } - req = c.newRequest(opInputService8TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService8TestShapeInputService8TestCaseOperation1Output{} req.Data = output return @@ -746,8 +714,6 @@ func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *Input return out, err } -var opInputService8TestCaseOperation1 *aws.Operation - type InputService8TestShapeInputService8TestCaseOperation1Output struct { metadataInputService8TestShapeInputService8TestCaseOperation1Output `json:"-" xml:"-"` } @@ -798,20 +764,19 @@ func (c *InputService9ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService9TestCaseOperation1 = "OperationName" + // InputService9TestCaseOperation1Request generates a request for the InputService9TestCaseOperation1 operation. func (c *InputService9ProtocolTest) InputService9TestCaseOperation1Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation1Output) { - - if opInputService9TestCaseOperation1 == nil { - opInputService9TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService9TestCaseOperation1, } if input == nil { input = &InputService9TestShapeInputShape{} } - req = c.newRequest(opInputService9TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService9TestShapeInputService9TestCaseOperation1Output{} req.Data = output return @@ -823,22 +788,19 @@ func (c *InputService9ProtocolTest) InputService9TestCaseOperation1(input *Input return out, err } -var opInputService9TestCaseOperation1 *aws.Operation +const opInputService9TestCaseOperation2 = "OperationName" // InputService9TestCaseOperation2Request generates a request for the InputService9TestCaseOperation2 operation. func (c *InputService9ProtocolTest) InputService9TestCaseOperation2Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation2Output) { - - if opInputService9TestCaseOperation2 == nil { - opInputService9TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService9TestCaseOperation2, } if input == nil { input = &InputService9TestShapeInputShape{} } - req = c.newRequest(opInputService9TestCaseOperation2, input, output) + req = c.newRequest(op, input, output) output = &InputService9TestShapeInputService9TestCaseOperation2Output{} req.Data = output return @@ -850,22 +812,19 @@ func (c *InputService9ProtocolTest) InputService9TestCaseOperation2(input *Input return out, err } -var opInputService9TestCaseOperation2 *aws.Operation +const opInputService9TestCaseOperation3 = "OperationName" // InputService9TestCaseOperation3Request generates a request for the InputService9TestCaseOperation3 operation. func (c *InputService9ProtocolTest) InputService9TestCaseOperation3Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation3Output) { - - if opInputService9TestCaseOperation3 == nil { - opInputService9TestCaseOperation3 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService9TestCaseOperation3, } if input == nil { input = &InputService9TestShapeInputShape{} } - req = c.newRequest(opInputService9TestCaseOperation3, input, output) + req = c.newRequest(op, input, output) output = &InputService9TestShapeInputService9TestCaseOperation3Output{} req.Data = output return @@ -877,22 +836,19 @@ func (c *InputService9ProtocolTest) InputService9TestCaseOperation3(input *Input return out, err } -var opInputService9TestCaseOperation3 *aws.Operation +const opInputService9TestCaseOperation4 = "OperationName" // InputService9TestCaseOperation4Request generates a request for the InputService9TestCaseOperation4 operation. func (c *InputService9ProtocolTest) InputService9TestCaseOperation4Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation4Output) { - - if opInputService9TestCaseOperation4 == nil { - opInputService9TestCaseOperation4 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService9TestCaseOperation4, } if input == nil { input = &InputService9TestShapeInputShape{} } - req = c.newRequest(opInputService9TestCaseOperation4, input, output) + req = c.newRequest(op, input, output) output = &InputService9TestShapeInputService9TestCaseOperation4Output{} req.Data = output return @@ -904,22 +860,19 @@ func (c *InputService9ProtocolTest) InputService9TestCaseOperation4(input *Input return out, err } -var opInputService9TestCaseOperation4 *aws.Operation +const opInputService9TestCaseOperation5 = "OperationName" // InputService9TestCaseOperation5Request generates a request for the InputService9TestCaseOperation5 operation. func (c *InputService9ProtocolTest) InputService9TestCaseOperation5Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation5Output) { - - if opInputService9TestCaseOperation5 == nil { - opInputService9TestCaseOperation5 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService9TestCaseOperation5, } if input == nil { input = &InputService9TestShapeInputShape{} } - req = c.newRequest(opInputService9TestCaseOperation5, input, output) + req = c.newRequest(op, input, output) output = &InputService9TestShapeInputService9TestCaseOperation5Output{} req.Data = output return @@ -931,22 +884,19 @@ func (c *InputService9ProtocolTest) InputService9TestCaseOperation5(input *Input return out, err } -var opInputService9TestCaseOperation5 *aws.Operation +const opInputService9TestCaseOperation6 = "OperationName" // InputService9TestCaseOperation6Request generates a request for the InputService9TestCaseOperation6 operation. func (c *InputService9ProtocolTest) InputService9TestCaseOperation6Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation6Output) { - - if opInputService9TestCaseOperation6 == nil { - opInputService9TestCaseOperation6 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opInputService9TestCaseOperation6, } if input == nil { input = &InputService9TestShapeInputShape{} } - req = c.newRequest(opInputService9TestCaseOperation6, input, output) + req = c.newRequest(op, input, output) output = &InputService9TestShapeInputService9TestCaseOperation6Output{} req.Data = output return @@ -958,8 +908,6 @@ func (c *InputService9ProtocolTest) InputService9TestCaseOperation6(input *Input return out, err } -var opInputService9TestCaseOperation6 *aws.Operation - type InputService9TestShapeInputService9TestCaseOperation1Output struct { metadataInputService9TestShapeInputService9TestCaseOperation1Output `json:"-" xml:"-"` } @@ -1442,10 +1390,10 @@ func TestInputService9ProtocolTestRecursiveShapesCase4(t *testing.T) { input := &InputService9TestShapeInputShape{ RecursiveStruct: &InputService9TestShapeRecursiveStructType{ RecursiveList: []*InputService9TestShapeRecursiveStructType{ - &InputService9TestShapeRecursiveStructType{ + { NoRecurse: aws.String("foo"), }, - &InputService9TestShapeRecursiveStructType{ + { NoRecurse: aws.String("bar"), }, }, @@ -1477,10 +1425,10 @@ func TestInputService9ProtocolTestRecursiveShapesCase5(t *testing.T) { input := &InputService9TestShapeInputShape{ RecursiveStruct: &InputService9TestShapeRecursiveStructType{ RecursiveList: []*InputService9TestShapeRecursiveStructType{ - &InputService9TestShapeRecursiveStructType{ + { NoRecurse: aws.String("foo"), }, - &InputService9TestShapeRecursiveStructType{ + { RecursiveStruct: &InputService9TestShapeRecursiveStructType{ NoRecurse: aws.String("bar"), }, @@ -1514,10 +1462,10 @@ func TestInputService9ProtocolTestRecursiveShapesCase6(t *testing.T) { input := &InputService9TestShapeInputShape{ RecursiveStruct: &InputService9TestShapeRecursiveStructType{ RecursiveMap: map[string]*InputService9TestShapeRecursiveStructType{ - "bar": &InputService9TestShapeRecursiveStructType{ + "bar": { NoRecurse: aws.String("bar"), }, - "foo": &InputService9TestShapeRecursiveStructType{ + "foo": { NoRecurse: aws.String("foo"), }, }, diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal.go index 8acdd2274..e8cfa926b 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal.go @@ -6,7 +6,7 @@ import ( "encoding/xml" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" ) @@ -17,7 +17,7 @@ func Unmarshal(r *aws.Request) { decoder := xml.NewDecoder(r.HTTPResponse.Body) err := xmlutil.UnmarshalXML(r.Data, decoder, r.Operation.Name+"Result") if err != nil { - r.Error = apierr.New("Unmarshal", "failed decoding Query response", err) + r.Error = awserr.New("SerializationError", "failed decoding Query response", err) return } } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_error.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_error.go index deb529524..d88ee3358 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_error.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_error.go @@ -5,7 +5,7 @@ import ( "io" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" ) type xmlErrorResponse struct { @@ -22,10 +22,10 @@ func UnmarshalError(r *aws.Request) { resp := &xmlErrorResponse{} err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp) if err != nil && err != io.EOF { - r.Error = apierr.New("Unmarshal", "failed to decode query XML error response", err) + r.Error = awserr.New("SerializationError", "failed to decode query XML error response", err) } else { - r.Error = apierr.NewRequestError( - apierr.New(resp.Code, resp.Message, nil), + r.Error = awserr.NewRequestFailure( + awserr.New(resp.Code, resp.Message, nil), r.HTTPResponse.StatusCode, resp.RequestID, ) diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_test.go index a17f56ccd..924d3d4e8 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/query/unmarshal_test.go @@ -1,10 +1,6 @@ package query_test import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/protocol/query" - "github.com/aws/aws-sdk-go/internal/signer/v4" - "bytes" "encoding/json" "encoding/xml" @@ -15,7 +11,10 @@ import ( "testing" "time" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/internal/protocol/query" "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" + "github.com/aws/aws-sdk-go/internal/signer/v4" "github.com/aws/aws-sdk-go/internal/util" "github.com/stretchr/testify/assert" ) @@ -63,20 +62,19 @@ func (c *OutputService1ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService1TestCaseOperation1 = "OperationName" + // OutputService1TestCaseOperation1Request generates a request for the OutputService1TestCaseOperation1 operation. func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *aws.Request, output *OutputService1TestShapeOutputShape) { - - if opOutputService1TestCaseOperation1 == nil { - opOutputService1TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService1TestCaseOperation1, } if input == nil { input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{} } - req = c.newRequest(opOutputService1TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService1TestShapeOutputShape{} req.Data = output return @@ -88,8 +86,6 @@ func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *Out return out, err } -var opOutputService1TestCaseOperation1 *aws.Operation - type OutputService1TestShapeOutputService1TestCaseOperation1Input struct { metadataOutputService1TestShapeOutputService1TestCaseOperation1Input `json:"-" xml:"-"` } @@ -156,20 +152,19 @@ func (c *OutputService2ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService2TestCaseOperation1 = "OperationName" + // OutputService2TestCaseOperation1Request generates a request for the OutputService2TestCaseOperation1 operation. func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *aws.Request, output *OutputService2TestShapeOutputShape) { - - if opOutputService2TestCaseOperation1 == nil { - opOutputService2TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService2TestCaseOperation1, } if input == nil { input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} } - req = c.newRequest(opOutputService2TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService2TestShapeOutputShape{} req.Data = output return @@ -181,8 +176,6 @@ func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *Out return out, err } -var opOutputService2TestCaseOperation1 *aws.Operation - type OutputService2TestShapeOutputService2TestCaseOperation1Input struct { metadataOutputService2TestShapeOutputService2TestCaseOperation1Input `json:"-" xml:"-"` } @@ -235,20 +228,19 @@ func (c *OutputService3ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService3TestCaseOperation1 = "OperationName" + // OutputService3TestCaseOperation1Request generates a request for the OutputService3TestCaseOperation1 operation. func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *aws.Request, output *OutputService3TestShapeOutputShape) { - - if opOutputService3TestCaseOperation1 == nil { - opOutputService3TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService3TestCaseOperation1, } if input == nil { input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} } - req = c.newRequest(opOutputService3TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService3TestShapeOutputShape{} req.Data = output return @@ -260,8 +252,6 @@ func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *Out return out, err } -var opOutputService3TestCaseOperation1 *aws.Operation - type OutputService3TestShapeOutputService3TestCaseOperation1Input struct { metadataOutputService3TestShapeOutputService3TestCaseOperation1Input `json:"-" xml:"-"` } @@ -312,20 +302,19 @@ func (c *OutputService4ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService4TestCaseOperation1 = "OperationName" + // OutputService4TestCaseOperation1Request generates a request for the OutputService4TestCaseOperation1 operation. func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *aws.Request, output *OutputService4TestShapeOutputShape) { - - if opOutputService4TestCaseOperation1 == nil { - opOutputService4TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService4TestCaseOperation1, } if input == nil { input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} } - req = c.newRequest(opOutputService4TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService4TestShapeOutputShape{} req.Data = output return @@ -337,8 +326,6 @@ func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *Out return out, err } -var opOutputService4TestCaseOperation1 *aws.Operation - type OutputService4TestShapeOutputService4TestCaseOperation1Input struct { metadataOutputService4TestShapeOutputService4TestCaseOperation1Input `json:"-" xml:"-"` } @@ -389,20 +376,19 @@ func (c *OutputService5ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService5TestCaseOperation1 = "OperationName" + // OutputService5TestCaseOperation1Request generates a request for the OutputService5TestCaseOperation1 operation. func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *aws.Request, output *OutputService5TestShapeOutputShape) { - - if opOutputService5TestCaseOperation1 == nil { - opOutputService5TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService5TestCaseOperation1, } if input == nil { input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} } - req = c.newRequest(opOutputService5TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService5TestShapeOutputShape{} req.Data = output return @@ -414,8 +400,6 @@ func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *Out return out, err } -var opOutputService5TestCaseOperation1 *aws.Operation - type OutputService5TestShapeOutputService5TestCaseOperation1Input struct { metadataOutputService5TestShapeOutputService5TestCaseOperation1Input `json:"-" xml:"-"` } @@ -466,20 +450,19 @@ func (c *OutputService6ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService6TestCaseOperation1 = "OperationName" + // OutputService6TestCaseOperation1Request generates a request for the OutputService6TestCaseOperation1 operation. func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *aws.Request, output *OutputService6TestShapeOutputShape) { - - if opOutputService6TestCaseOperation1 == nil { - opOutputService6TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService6TestCaseOperation1, } if input == nil { input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} } - req = c.newRequest(opOutputService6TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService6TestShapeOutputShape{} req.Data = output return @@ -491,8 +474,6 @@ func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *Out return out, err } -var opOutputService6TestCaseOperation1 *aws.Operation - type OutputService6TestShapeOutputService6TestCaseOperation1Input struct { metadataOutputService6TestShapeOutputService6TestCaseOperation1Input `json:"-" xml:"-"` } @@ -543,20 +524,19 @@ func (c *OutputService7ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService7TestCaseOperation1 = "OperationName" + // OutputService7TestCaseOperation1Request generates a request for the OutputService7TestCaseOperation1 operation. func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *aws.Request, output *OutputService7TestShapeOutputShape) { - - if opOutputService7TestCaseOperation1 == nil { - opOutputService7TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService7TestCaseOperation1, } if input == nil { input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} } - req = c.newRequest(opOutputService7TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService7TestShapeOutputShape{} req.Data = output return @@ -568,8 +548,6 @@ func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *Out return out, err } -var opOutputService7TestCaseOperation1 *aws.Operation - type OutputService7TestShapeOutputService7TestCaseOperation1Input struct { metadataOutputService7TestShapeOutputService7TestCaseOperation1Input `json:"-" xml:"-"` } @@ -620,20 +598,19 @@ func (c *OutputService8ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService8TestCaseOperation1 = "OperationName" + // OutputService8TestCaseOperation1Request generates a request for the OutputService8TestCaseOperation1 operation. func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *aws.Request, output *OutputService8TestShapeOutputShape) { - - if opOutputService8TestCaseOperation1 == nil { - opOutputService8TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService8TestCaseOperation1, } if input == nil { input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} } - req = c.newRequest(opOutputService8TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService8TestShapeOutputShape{} req.Data = output return @@ -645,8 +622,6 @@ func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *Out return out, err } -var opOutputService8TestCaseOperation1 *aws.Operation - type OutputService8TestShapeOutputService8TestCaseOperation1Input struct { metadataOutputService8TestShapeOutputService8TestCaseOperation1Input `json:"-" xml:"-"` } @@ -711,20 +686,19 @@ func (c *OutputService9ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService9TestCaseOperation1 = "OperationName" + // OutputService9TestCaseOperation1Request generates a request for the OutputService9TestCaseOperation1 operation. func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *aws.Request, output *OutputService9TestShapeOutputShape) { - - if opOutputService9TestCaseOperation1 == nil { - opOutputService9TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService9TestCaseOperation1, } if input == nil { input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{} } - req = c.newRequest(opOutputService9TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService9TestShapeOutputShape{} req.Data = output return @@ -736,8 +710,6 @@ func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *Out return out, err } -var opOutputService9TestCaseOperation1 *aws.Operation - type OutputService9TestShapeOutputService9TestCaseOperation1Input struct { metadataOutputService9TestShapeOutputService9TestCaseOperation1Input `json:"-" xml:"-"` } @@ -802,20 +774,19 @@ func (c *OutputService10ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService10TestCaseOperation1 = "OperationName" + // OutputService10TestCaseOperation1Request generates a request for the OutputService10TestCaseOperation1 operation. func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1Request(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (req *aws.Request, output *OutputService10TestShapeOutputShape) { - - if opOutputService10TestCaseOperation1 == nil { - opOutputService10TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService10TestCaseOperation1, } if input == nil { input = &OutputService10TestShapeOutputService10TestCaseOperation1Input{} } - req = c.newRequest(opOutputService10TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService10TestShapeOutputShape{} req.Data = output return @@ -827,8 +798,6 @@ func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1(input *O return out, err } -var opOutputService10TestCaseOperation1 *aws.Operation - type OutputService10TestShapeOutputService10TestCaseOperation1Input struct { metadataOutputService10TestShapeOutputService10TestCaseOperation1Input `json:"-" xml:"-"` } @@ -879,20 +848,19 @@ func (c *OutputService11ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService11TestCaseOperation1 = "OperationName" + // OutputService11TestCaseOperation1Request generates a request for the OutputService11TestCaseOperation1 operation. func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1Request(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (req *aws.Request, output *OutputService11TestShapeOutputShape) { - - if opOutputService11TestCaseOperation1 == nil { - opOutputService11TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService11TestCaseOperation1, } if input == nil { input = &OutputService11TestShapeOutputService11TestCaseOperation1Input{} } - req = c.newRequest(opOutputService11TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService11TestShapeOutputShape{} req.Data = output return @@ -904,8 +872,6 @@ func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1(input *O return out, err } -var opOutputService11TestCaseOperation1 *aws.Operation - type OutputService11TestShapeOutputService11TestCaseOperation1Input struct { metadataOutputService11TestShapeOutputService11TestCaseOperation1Input `json:"-" xml:"-"` } @@ -966,20 +932,19 @@ func (c *OutputService12ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService12TestCaseOperation1 = "OperationName" + // OutputService12TestCaseOperation1Request generates a request for the OutputService12TestCaseOperation1 operation. func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1Request(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (req *aws.Request, output *OutputService12TestShapeOutputShape) { - - if opOutputService12TestCaseOperation1 == nil { - opOutputService12TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService12TestCaseOperation1, } if input == nil { input = &OutputService12TestShapeOutputService12TestCaseOperation1Input{} } - req = c.newRequest(opOutputService12TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService12TestShapeOutputShape{} req.Data = output return @@ -991,8 +956,6 @@ func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1(input *O return out, err } -var opOutputService12TestCaseOperation1 *aws.Operation - type OutputService12TestShapeOutputService12TestCaseOperation1Input struct { metadataOutputService12TestShapeOutputService12TestCaseOperation1Input `json:"-" xml:"-"` } @@ -1043,20 +1006,19 @@ func (c *OutputService13ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService13TestCaseOperation1 = "OperationName" + // OutputService13TestCaseOperation1Request generates a request for the OutputService13TestCaseOperation1 operation. func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1Request(input *OutputService13TestShapeOutputService13TestCaseOperation1Input) (req *aws.Request, output *OutputService13TestShapeOutputShape) { - - if opOutputService13TestCaseOperation1 == nil { - opOutputService13TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService13TestCaseOperation1, } if input == nil { input = &OutputService13TestShapeOutputService13TestCaseOperation1Input{} } - req = c.newRequest(opOutputService13TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService13TestShapeOutputShape{} req.Data = output return @@ -1068,8 +1030,6 @@ func (c *OutputService13ProtocolTest) OutputService13TestCaseOperation1(input *O return out, err } -var opOutputService13TestCaseOperation1 *aws.Operation - type OutputService13TestShapeOutputService13TestCaseOperation1Input struct { metadataOutputService13TestShapeOutputService13TestCaseOperation1Input `json:"-" xml:"-"` } @@ -1120,20 +1080,19 @@ func (c *OutputService14ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService14TestCaseOperation1 = "OperationName" + // OutputService14TestCaseOperation1Request generates a request for the OutputService14TestCaseOperation1 operation. func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1Request(input *OutputService14TestShapeOutputService14TestCaseOperation1Input) (req *aws.Request, output *OutputService14TestShapeOutputShape) { - - if opOutputService14TestCaseOperation1 == nil { - opOutputService14TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService14TestCaseOperation1, } if input == nil { input = &OutputService14TestShapeOutputService14TestCaseOperation1Input{} } - req = c.newRequest(opOutputService14TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService14TestShapeOutputShape{} req.Data = output return @@ -1145,8 +1104,6 @@ func (c *OutputService14ProtocolTest) OutputService14TestCaseOperation1(input *O return out, err } -var opOutputService14TestCaseOperation1 *aws.Operation - type OutputService14TestShapeOutputService14TestCaseOperation1Input struct { metadataOutputService14TestShapeOutputService14TestCaseOperation1Input `json:"-" xml:"-"` } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/build.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/build.go index aa5493849..cd5eef235 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/build.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/build.go @@ -1,3 +1,4 @@ +// Package rest provides RESTful serialisation of AWS requests and responses. package rest import ( @@ -13,7 +14,7 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" ) // RFC822 returns an RFC822 formatted timestamp for AWS protocols @@ -101,7 +102,7 @@ func buildBody(r *aws.Request, v reflect.Value) { case string: r.SetStringBody(reader) default: - r.Error = apierr.New("Marshal", + r.Error = awserr.New("SerializationError", "failed to encode REST request", fmt.Errorf("unknown payload type %s", payload.Type())) } @@ -114,7 +115,7 @@ func buildBody(r *aws.Request, v reflect.Value) { func buildHeader(r *aws.Request, v reflect.Value, name string) { str, err := convertType(v) if err != nil { - r.Error = apierr.New("Marshal", "failed to encode REST request", err) + r.Error = awserr.New("SerializationError", "failed to encode REST request", err) } else if str != nil { r.HTTPRequest.Header.Add(name, *str) } @@ -124,7 +125,7 @@ func buildHeaderMap(r *aws.Request, v reflect.Value, prefix string) { for _, key := range v.MapKeys() { str, err := convertType(v.MapIndex(key)) if err != nil { - r.Error = apierr.New("Marshal", "failed to encode REST request", err) + r.Error = awserr.New("SerializationError", "failed to encode REST request", err) } else if str != nil { r.HTTPRequest.Header.Add(prefix+key.String(), *str) } @@ -134,7 +135,7 @@ func buildHeaderMap(r *aws.Request, v reflect.Value, prefix string) { func buildURI(r *aws.Request, v reflect.Value, name string) { value, err := convertType(v) if err != nil { - r.Error = apierr.New("Marshal", "failed to encode REST request", err) + r.Error = awserr.New("SerializationError", "failed to encode REST request", err) } else if value != nil { uri := r.HTTPRequest.URL.Path uri = strings.Replace(uri, "{"+name+"}", EscapePath(*value, true), -1) @@ -146,7 +147,7 @@ func buildURI(r *aws.Request, v reflect.Value, name string) { func buildQueryString(r *aws.Request, v reflect.Value, name string, query url.Values) { str, err := convertType(v) if err != nil { - r.Error = apierr.New("Marshal", "failed to encode REST request", err) + r.Error = awserr.New("SerializationError", "failed to encode REST request", err) } else if str != nil { query.Set(name, *str) } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/unmarshal.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/unmarshal.go index 009c5c950..a4155f166 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/unmarshal.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/rest/unmarshal.go @@ -11,7 +11,7 @@ import ( "time" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" ) // Unmarshal unmarshals the REST component of a response in a REST service. @@ -34,14 +34,14 @@ func unmarshalBody(r *aws.Request, v reflect.Value) { case []byte: b, err := ioutil.ReadAll(r.HTTPResponse.Body) if err != nil { - r.Error = apierr.New("Unmarshal", "failed to decode REST response", err) + r.Error = awserr.New("SerializationError", "failed to decode REST response", err) } else { payload.Set(reflect.ValueOf(b)) } case *string: b, err := ioutil.ReadAll(r.HTTPResponse.Body) if err != nil { - r.Error = apierr.New("Unmarshal", "failed to decode REST response", err) + r.Error = awserr.New("SerializationError", "failed to decode REST response", err) } else { str := string(b) payload.Set(reflect.ValueOf(&str)) @@ -53,7 +53,7 @@ func unmarshalBody(r *aws.Request, v reflect.Value) { case "aws.ReadSeekCloser", "io.ReadCloser": payload.Set(reflect.ValueOf(r.HTTPResponse.Body)) default: - r.Error = apierr.New("Unmarshal", + r.Error = awserr.New("SerializationError", "failed to decode REST response", fmt.Errorf("unknown payload type %s", payload.Type())) } @@ -83,14 +83,14 @@ func unmarshalLocationElements(r *aws.Request, v reflect.Value) { case "header": err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name)) if err != nil { - r.Error = apierr.New("Unmarshal", "failed to decode REST response", err) + r.Error = awserr.New("SerializationError", "failed to decode REST response", err) break } case "headers": prefix := field.Tag.Get("locationName") err := unmarshalHeaderMap(m, r.HTTPResponse.Header, prefix) if err != nil { - r.Error = apierr.New("Unmarshal", "failed to decode REST response", err) + r.Error = awserr.New("SerializationError", "failed to decode REST response", err) break } } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/build_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/build_test.go index 17c0d91cc..6fcd3f8dc 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/build_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/build_test.go @@ -1,10 +1,6 @@ package restxml_test import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/protocol/restxml" - "github.com/aws/aws-sdk-go/internal/signer/v4" - "bytes" "encoding/json" "encoding/xml" @@ -15,7 +11,10 @@ import ( "testing" "time" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/internal/protocol/restxml" "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" + "github.com/aws/aws-sdk-go/internal/signer/v4" "github.com/aws/aws-sdk-go/internal/util" "github.com/stretchr/testify/assert" ) @@ -63,22 +62,21 @@ func (c *InputService1ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService1TestCaseOperation1 = "OperationName" + // InputService1TestCaseOperation1Request generates a request for the InputService1TestCaseOperation1 operation. func (c *InputService1ProtocolTest) InputService1TestCaseOperation1Request(input *InputService1TestShapeInputShape) (req *aws.Request, output *InputService1TestShapeInputService1TestCaseOperation1Output) { - - if opInputService1TestCaseOperation1 == nil { - opInputService1TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } + op := &aws.Operation{ + Name: opInputService1TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/2014-01-01/hostedzone", } if input == nil { input = &InputService1TestShapeInputShape{} } - req = c.newRequest(opInputService1TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService1TestShapeInputService1TestCaseOperation1Output{} req.Data = output return @@ -90,24 +88,21 @@ func (c *InputService1ProtocolTest) InputService1TestCaseOperation1(input *Input return out, err } -var opInputService1TestCaseOperation1 *aws.Operation +const opInputService1TestCaseOperation2 = "OperationName" // InputService1TestCaseOperation2Request generates a request for the InputService1TestCaseOperation2 operation. func (c *InputService1ProtocolTest) InputService1TestCaseOperation2Request(input *InputService1TestShapeInputShape) (req *aws.Request, output *InputService1TestShapeInputService1TestCaseOperation2Output) { - - if opInputService1TestCaseOperation2 == nil { - opInputService1TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "PUT", - HTTPPath: "/2014-01-01/hostedzone", - } + op := &aws.Operation{ + Name: opInputService1TestCaseOperation2, + HTTPMethod: "PUT", + HTTPPath: "/2014-01-01/hostedzone", } if input == nil { input = &InputService1TestShapeInputShape{} } - req = c.newRequest(opInputService1TestCaseOperation2, input, output) + req = c.newRequest(op, input, output) output = &InputService1TestShapeInputService1TestCaseOperation2Output{} req.Data = output return @@ -119,8 +114,6 @@ func (c *InputService1ProtocolTest) InputService1TestCaseOperation2(input *Input return out, err } -var opInputService1TestCaseOperation2 *aws.Operation - type InputService1TestShapeInputService1TestCaseOperation1Output struct { metadataInputService1TestShapeInputService1TestCaseOperation1Output `json:"-" xml:"-"` } @@ -181,22 +174,21 @@ func (c *InputService2ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService2TestCaseOperation1 = "OperationName" + // InputService2TestCaseOperation1Request generates a request for the InputService2TestCaseOperation1 operation. func (c *InputService2ProtocolTest) InputService2TestCaseOperation1Request(input *InputService2TestShapeInputShape) (req *aws.Request, output *InputService2TestShapeInputService2TestCaseOperation1Output) { - - if opInputService2TestCaseOperation1 == nil { - opInputService2TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } + op := &aws.Operation{ + Name: opInputService2TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/2014-01-01/hostedzone", } if input == nil { input = &InputService2TestShapeInputShape{} } - req = c.newRequest(opInputService2TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService2TestShapeInputService2TestCaseOperation1Output{} req.Data = output return @@ -208,8 +200,6 @@ func (c *InputService2ProtocolTest) InputService2TestCaseOperation1(input *Input return out, err } -var opInputService2TestCaseOperation1 *aws.Operation - type InputService2TestShapeInputService2TestCaseOperation1Output struct { metadataInputService2TestShapeInputService2TestCaseOperation1Output `json:"-" xml:"-"` } @@ -266,22 +256,21 @@ func (c *InputService3ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService3TestCaseOperation1 = "OperationName" + // InputService3TestCaseOperation1Request generates a request for the InputService3TestCaseOperation1 operation. func (c *InputService3ProtocolTest) InputService3TestCaseOperation1Request(input *InputService3TestShapeInputShape) (req *aws.Request, output *InputService3TestShapeInputService3TestCaseOperation1Output) { - - if opInputService3TestCaseOperation1 == nil { - opInputService3TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } + op := &aws.Operation{ + Name: opInputService3TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/2014-01-01/hostedzone", } if input == nil { input = &InputService3TestShapeInputShape{} } - req = c.newRequest(opInputService3TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService3TestShapeInputService3TestCaseOperation1Output{} req.Data = output return @@ -293,8 +282,6 @@ func (c *InputService3ProtocolTest) InputService3TestCaseOperation1(input *Input return out, err } -var opInputService3TestCaseOperation1 *aws.Operation - type InputService3TestShapeInputService3TestCaseOperation1Output struct { metadataInputService3TestShapeInputService3TestCaseOperation1Output `json:"-" xml:"-"` } @@ -359,22 +346,21 @@ func (c *InputService4ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService4TestCaseOperation1 = "OperationName" + // InputService4TestCaseOperation1Request generates a request for the InputService4TestCaseOperation1 operation. func (c *InputService4ProtocolTest) InputService4TestCaseOperation1Request(input *InputService4TestShapeInputShape) (req *aws.Request, output *InputService4TestShapeInputService4TestCaseOperation1Output) { - - if opInputService4TestCaseOperation1 == nil { - opInputService4TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } + op := &aws.Operation{ + Name: opInputService4TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/2014-01-01/hostedzone", } if input == nil { input = &InputService4TestShapeInputShape{} } - req = c.newRequest(opInputService4TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService4TestShapeInputService4TestCaseOperation1Output{} req.Data = output return @@ -386,8 +372,6 @@ func (c *InputService4ProtocolTest) InputService4TestCaseOperation1(input *Input return out, err } -var opInputService4TestCaseOperation1 *aws.Operation - type InputService4TestShapeInputService4TestCaseOperation1Output struct { metadataInputService4TestShapeInputService4TestCaseOperation1Output `json:"-" xml:"-"` } @@ -452,22 +436,21 @@ func (c *InputService5ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService5TestCaseOperation1 = "OperationName" + // InputService5TestCaseOperation1Request generates a request for the InputService5TestCaseOperation1 operation. func (c *InputService5ProtocolTest) InputService5TestCaseOperation1Request(input *InputService5TestShapeInputShape) (req *aws.Request, output *InputService5TestShapeInputService5TestCaseOperation1Output) { - - if opInputService5TestCaseOperation1 == nil { - opInputService5TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } + op := &aws.Operation{ + Name: opInputService5TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/2014-01-01/hostedzone", } if input == nil { input = &InputService5TestShapeInputShape{} } - req = c.newRequest(opInputService5TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService5TestShapeInputService5TestCaseOperation1Output{} req.Data = output return @@ -479,8 +462,6 @@ func (c *InputService5ProtocolTest) InputService5TestCaseOperation1(input *Input return out, err } -var opInputService5TestCaseOperation1 *aws.Operation - type InputService5TestShapeInputService5TestCaseOperation1Output struct { metadataInputService5TestShapeInputService5TestCaseOperation1Output `json:"-" xml:"-"` } @@ -531,22 +512,21 @@ func (c *InputService6ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService6TestCaseOperation1 = "OperationName" + // InputService6TestCaseOperation1Request generates a request for the InputService6TestCaseOperation1 operation. func (c *InputService6ProtocolTest) InputService6TestCaseOperation1Request(input *InputService6TestShapeInputShape) (req *aws.Request, output *InputService6TestShapeInputService6TestCaseOperation1Output) { - - if opInputService6TestCaseOperation1 == nil { - opInputService6TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } + op := &aws.Operation{ + Name: opInputService6TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/2014-01-01/hostedzone", } if input == nil { input = &InputService6TestShapeInputShape{} } - req = c.newRequest(opInputService6TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService6TestShapeInputService6TestCaseOperation1Output{} req.Data = output return @@ -558,8 +538,6 @@ func (c *InputService6ProtocolTest) InputService6TestCaseOperation1(input *Input return out, err } -var opInputService6TestCaseOperation1 *aws.Operation - type InputService6TestShapeInputService6TestCaseOperation1Output struct { metadataInputService6TestShapeInputService6TestCaseOperation1Output `json:"-" xml:"-"` } @@ -610,22 +588,21 @@ func (c *InputService7ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService7TestCaseOperation1 = "OperationName" + // InputService7TestCaseOperation1Request generates a request for the InputService7TestCaseOperation1 operation. func (c *InputService7ProtocolTest) InputService7TestCaseOperation1Request(input *InputService7TestShapeInputShape) (req *aws.Request, output *InputService7TestShapeInputService7TestCaseOperation1Output) { - - if opInputService7TestCaseOperation1 == nil { - opInputService7TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } + op := &aws.Operation{ + Name: opInputService7TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/2014-01-01/hostedzone", } if input == nil { input = &InputService7TestShapeInputShape{} } - req = c.newRequest(opInputService7TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService7TestShapeInputService7TestCaseOperation1Output{} req.Data = output return @@ -637,8 +614,6 @@ func (c *InputService7ProtocolTest) InputService7TestCaseOperation1(input *Input return out, err } -var opInputService7TestCaseOperation1 *aws.Operation - type InputService7TestShapeInputService7TestCaseOperation1Output struct { metadataInputService7TestShapeInputService7TestCaseOperation1Output `json:"-" xml:"-"` } @@ -689,22 +664,21 @@ func (c *InputService8ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService8TestCaseOperation1 = "OperationName" + // InputService8TestCaseOperation1Request generates a request for the InputService8TestCaseOperation1 operation. func (c *InputService8ProtocolTest) InputService8TestCaseOperation1Request(input *InputService8TestShapeInputShape) (req *aws.Request, output *InputService8TestShapeInputService8TestCaseOperation1Output) { - - if opInputService8TestCaseOperation1 == nil { - opInputService8TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } + op := &aws.Operation{ + Name: opInputService8TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/2014-01-01/hostedzone", } if input == nil { input = &InputService8TestShapeInputShape{} } - req = c.newRequest(opInputService8TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService8TestShapeInputService8TestCaseOperation1Output{} req.Data = output return @@ -716,8 +690,6 @@ func (c *InputService8ProtocolTest) InputService8TestCaseOperation1(input *Input return out, err } -var opInputService8TestCaseOperation1 *aws.Operation - type InputService8TestShapeInputService8TestCaseOperation1Output struct { metadataInputService8TestShapeInputService8TestCaseOperation1Output `json:"-" xml:"-"` } @@ -768,22 +740,21 @@ func (c *InputService9ProtocolTest) newRequest(op *aws.Operation, params, data i return req } +const opInputService9TestCaseOperation1 = "OperationName" + // InputService9TestCaseOperation1Request generates a request for the InputService9TestCaseOperation1 operation. func (c *InputService9ProtocolTest) InputService9TestCaseOperation1Request(input *InputService9TestShapeInputShape) (req *aws.Request, output *InputService9TestShapeInputService9TestCaseOperation1Output) { - - if opInputService9TestCaseOperation1 == nil { - opInputService9TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } + op := &aws.Operation{ + Name: opInputService9TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/2014-01-01/hostedzone", } if input == nil { input = &InputService9TestShapeInputShape{} } - req = c.newRequest(opInputService9TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService9TestShapeInputService9TestCaseOperation1Output{} req.Data = output return @@ -795,8 +766,6 @@ func (c *InputService9ProtocolTest) InputService9TestCaseOperation1(input *Input return out, err } -var opInputService9TestCaseOperation1 *aws.Operation - type InputService9TestShapeInputService9TestCaseOperation1Output struct { metadataInputService9TestShapeInputService9TestCaseOperation1Output `json:"-" xml:"-"` } @@ -857,22 +826,21 @@ func (c *InputService10ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opInputService10TestCaseOperation1 = "OperationName" + // InputService10TestCaseOperation1Request generates a request for the InputService10TestCaseOperation1 operation. func (c *InputService10ProtocolTest) InputService10TestCaseOperation1Request(input *InputService10TestShapeInputShape) (req *aws.Request, output *InputService10TestShapeInputService10TestCaseOperation1Output) { - - if opInputService10TestCaseOperation1 == nil { - opInputService10TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/2014-01-01/hostedzone", - } + op := &aws.Operation{ + Name: opInputService10TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/2014-01-01/hostedzone", } if input == nil { input = &InputService10TestShapeInputShape{} } - req = c.newRequest(opInputService10TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService10TestShapeInputService10TestCaseOperation1Output{} req.Data = output return @@ -884,8 +852,6 @@ func (c *InputService10ProtocolTest) InputService10TestCaseOperation1(input *Inp return out, err } -var opInputService10TestCaseOperation1 *aws.Operation - type InputService10TestShapeInputService10TestCaseOperation1Output struct { metadataInputService10TestShapeInputService10TestCaseOperation1Output `json:"-" xml:"-"` } @@ -948,22 +914,21 @@ func (c *InputService11ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opInputService11TestCaseOperation1 = "OperationName" + // InputService11TestCaseOperation1Request generates a request for the InputService11TestCaseOperation1 operation. func (c *InputService11ProtocolTest) InputService11TestCaseOperation1Request(input *InputService11TestShapeInputShape) (req *aws.Request, output *InputService11TestShapeInputService11TestCaseOperation1Output) { - - if opInputService11TestCaseOperation1 == nil { - opInputService11TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } + op := &aws.Operation{ + Name: opInputService11TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/", } if input == nil { input = &InputService11TestShapeInputShape{} } - req = c.newRequest(opInputService11TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService11TestShapeInputService11TestCaseOperation1Output{} req.Data = output return @@ -975,8 +940,6 @@ func (c *InputService11ProtocolTest) InputService11TestCaseOperation1(input *Inp return out, err } -var opInputService11TestCaseOperation1 *aws.Operation - type InputService11TestShapeInputService11TestCaseOperation1Output struct { metadataInputService11TestShapeInputService11TestCaseOperation1Output `json:"-" xml:"-"` } @@ -1027,22 +990,21 @@ func (c *InputService12ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opInputService12TestCaseOperation1 = "OperationName" + // InputService12TestCaseOperation1Request generates a request for the InputService12TestCaseOperation1 operation. func (c *InputService12ProtocolTest) InputService12TestCaseOperation1Request(input *InputService12TestShapeInputShape) (req *aws.Request, output *InputService12TestShapeInputService12TestCaseOperation1Output) { - - if opInputService12TestCaseOperation1 == nil { - opInputService12TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } + op := &aws.Operation{ + Name: opInputService12TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/", } if input == nil { input = &InputService12TestShapeInputShape{} } - req = c.newRequest(opInputService12TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService12TestShapeInputService12TestCaseOperation1Output{} req.Data = output return @@ -1054,8 +1016,6 @@ func (c *InputService12ProtocolTest) InputService12TestCaseOperation1(input *Inp return out, err } -var opInputService12TestCaseOperation1 *aws.Operation - type InputService12TestShapeInputService12TestCaseOperation1Output struct { metadataInputService12TestShapeInputService12TestCaseOperation1Output `json:"-" xml:"-"` } @@ -1106,22 +1066,21 @@ func (c *InputService13ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opInputService13TestCaseOperation1 = "OperationName" + // InputService13TestCaseOperation1Request generates a request for the InputService13TestCaseOperation1 operation. func (c *InputService13ProtocolTest) InputService13TestCaseOperation1Request(input *InputService13TestShapeInputShape) (req *aws.Request, output *InputService13TestShapeInputService13TestCaseOperation1Output) { - - if opInputService13TestCaseOperation1 == nil { - opInputService13TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } + op := &aws.Operation{ + Name: opInputService13TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/", } if input == nil { input = &InputService13TestShapeInputShape{} } - req = c.newRequest(opInputService13TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService13TestShapeInputService13TestCaseOperation1Output{} req.Data = output return @@ -1133,24 +1092,21 @@ func (c *InputService13ProtocolTest) InputService13TestCaseOperation1(input *Inp return out, err } -var opInputService13TestCaseOperation1 *aws.Operation +const opInputService13TestCaseOperation2 = "OperationName" // InputService13TestCaseOperation2Request generates a request for the InputService13TestCaseOperation2 operation. func (c *InputService13ProtocolTest) InputService13TestCaseOperation2Request(input *InputService13TestShapeInputShape) (req *aws.Request, output *InputService13TestShapeInputService13TestCaseOperation2Output) { - - if opInputService13TestCaseOperation2 == nil { - opInputService13TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } + op := &aws.Operation{ + Name: opInputService13TestCaseOperation2, + HTTPMethod: "POST", + HTTPPath: "/", } if input == nil { input = &InputService13TestShapeInputShape{} } - req = c.newRequest(opInputService13TestCaseOperation2, input, output) + req = c.newRequest(op, input, output) output = &InputService13TestShapeInputService13TestCaseOperation2Output{} req.Data = output return @@ -1162,8 +1118,6 @@ func (c *InputService13ProtocolTest) InputService13TestCaseOperation2(input *Inp return out, err } -var opInputService13TestCaseOperation2 *aws.Operation - type InputService13TestShapeInputService13TestCaseOperation1Output struct { metadataInputService13TestShapeInputService13TestCaseOperation1Output `json:"-" xml:"-"` } @@ -1222,22 +1176,21 @@ func (c *InputService14ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opInputService14TestCaseOperation1 = "OperationName" + // InputService14TestCaseOperation1Request generates a request for the InputService14TestCaseOperation1 operation. func (c *InputService14ProtocolTest) InputService14TestCaseOperation1Request(input *InputService14TestShapeInputShape) (req *aws.Request, output *InputService14TestShapeInputService14TestCaseOperation1Output) { - - if opInputService14TestCaseOperation1 == nil { - opInputService14TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } + op := &aws.Operation{ + Name: opInputService14TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/", } if input == nil { input = &InputService14TestShapeInputShape{} } - req = c.newRequest(opInputService14TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService14TestShapeInputService14TestCaseOperation1Output{} req.Data = output return @@ -1249,24 +1202,21 @@ func (c *InputService14ProtocolTest) InputService14TestCaseOperation1(input *Inp return out, err } -var opInputService14TestCaseOperation1 *aws.Operation +const opInputService14TestCaseOperation2 = "OperationName" // InputService14TestCaseOperation2Request generates a request for the InputService14TestCaseOperation2 operation. func (c *InputService14ProtocolTest) InputService14TestCaseOperation2Request(input *InputService14TestShapeInputShape) (req *aws.Request, output *InputService14TestShapeInputService14TestCaseOperation2Output) { - - if opInputService14TestCaseOperation2 == nil { - opInputService14TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } + op := &aws.Operation{ + Name: opInputService14TestCaseOperation2, + HTTPMethod: "POST", + HTTPPath: "/", } if input == nil { input = &InputService14TestShapeInputShape{} } - req = c.newRequest(opInputService14TestCaseOperation2, input, output) + req = c.newRequest(op, input, output) output = &InputService14TestShapeInputService14TestCaseOperation2Output{} req.Data = output return @@ -1278,24 +1228,21 @@ func (c *InputService14ProtocolTest) InputService14TestCaseOperation2(input *Inp return out, err } -var opInputService14TestCaseOperation2 *aws.Operation +const opInputService14TestCaseOperation3 = "OperationName" // InputService14TestCaseOperation3Request generates a request for the InputService14TestCaseOperation3 operation. func (c *InputService14ProtocolTest) InputService14TestCaseOperation3Request(input *InputService14TestShapeInputShape) (req *aws.Request, output *InputService14TestShapeInputService14TestCaseOperation3Output) { - - if opInputService14TestCaseOperation3 == nil { - opInputService14TestCaseOperation3 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } + op := &aws.Operation{ + Name: opInputService14TestCaseOperation3, + HTTPMethod: "POST", + HTTPPath: "/", } if input == nil { input = &InputService14TestShapeInputShape{} } - req = c.newRequest(opInputService14TestCaseOperation3, input, output) + req = c.newRequest(op, input, output) output = &InputService14TestShapeInputService14TestCaseOperation3Output{} req.Data = output return @@ -1307,8 +1254,6 @@ func (c *InputService14ProtocolTest) InputService14TestCaseOperation3(input *Inp return out, err } -var opInputService14TestCaseOperation3 *aws.Operation - type InputService14TestShapeFooShape struct { Baz *string `locationName:"baz" type:"string"` @@ -1385,22 +1330,21 @@ func (c *InputService15ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opInputService15TestCaseOperation1 = "OperationName" + // InputService15TestCaseOperation1Request generates a request for the InputService15TestCaseOperation1 operation. func (c *InputService15ProtocolTest) InputService15TestCaseOperation1Request(input *InputService15TestShapeInputShape) (req *aws.Request, output *InputService15TestShapeInputService15TestCaseOperation1Output) { - - if opInputService15TestCaseOperation1 == nil { - opInputService15TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/", - } + op := &aws.Operation{ + Name: opInputService15TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/", } if input == nil { input = &InputService15TestShapeInputShape{} } - req = c.newRequest(opInputService15TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService15TestShapeInputService15TestCaseOperation1Output{} req.Data = output return @@ -1412,8 +1356,6 @@ func (c *InputService15ProtocolTest) InputService15TestCaseOperation1(input *Inp return out, err } -var opInputService15TestCaseOperation1 *aws.Operation - type InputService15TestShapeGrant struct { Grantee *InputService15TestShapeGrantee `type:"structure"` @@ -1486,22 +1428,21 @@ func (c *InputService16ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opInputService16TestCaseOperation1 = "OperationName" + // InputService16TestCaseOperation1Request generates a request for the InputService16TestCaseOperation1 operation. func (c *InputService16ProtocolTest) InputService16TestCaseOperation1Request(input *InputService16TestShapeInputShape) (req *aws.Request, output *InputService16TestShapeInputService16TestCaseOperation1Output) { - - if opInputService16TestCaseOperation1 == nil { - opInputService16TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}", - } + op := &aws.Operation{ + Name: opInputService16TestCaseOperation1, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}/{Key+}", } if input == nil { input = &InputService16TestShapeInputShape{} } - req = c.newRequest(opInputService16TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService16TestShapeInputService16TestCaseOperation1Output{} req.Data = output return @@ -1513,8 +1454,6 @@ func (c *InputService16ProtocolTest) InputService16TestCaseOperation1(input *Inp return out, err } -var opInputService16TestCaseOperation1 *aws.Operation - type InputService16TestShapeInputService16TestCaseOperation1Output struct { metadataInputService16TestShapeInputService16TestCaseOperation1Output `json:"-" xml:"-"` } @@ -1567,22 +1506,21 @@ func (c *InputService17ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opInputService17TestCaseOperation1 = "OperationName" + // InputService17TestCaseOperation1Request generates a request for the InputService17TestCaseOperation1 operation. func (c *InputService17ProtocolTest) InputService17TestCaseOperation1Request(input *InputService17TestShapeInputShape) (req *aws.Request, output *InputService17TestShapeInputService17TestCaseOperation1Output) { - - if opInputService17TestCaseOperation1 == nil { - opInputService17TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } + op := &aws.Operation{ + Name: opInputService17TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/path", } if input == nil { input = &InputService17TestShapeInputShape{} } - req = c.newRequest(opInputService17TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService17TestShapeInputService17TestCaseOperation1Output{} req.Data = output return @@ -1594,24 +1532,21 @@ func (c *InputService17ProtocolTest) InputService17TestCaseOperation1(input *Inp return out, err } -var opInputService17TestCaseOperation1 *aws.Operation +const opInputService17TestCaseOperation2 = "OperationName" // InputService17TestCaseOperation2Request generates a request for the InputService17TestCaseOperation2 operation. func (c *InputService17ProtocolTest) InputService17TestCaseOperation2Request(input *InputService17TestShapeInputShape) (req *aws.Request, output *InputService17TestShapeInputService17TestCaseOperation2Output) { - - if opInputService17TestCaseOperation2 == nil { - opInputService17TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path?abc=mno", - } + op := &aws.Operation{ + Name: opInputService17TestCaseOperation2, + HTTPMethod: "POST", + HTTPPath: "/path?abc=mno", } if input == nil { input = &InputService17TestShapeInputShape{} } - req = c.newRequest(opInputService17TestCaseOperation2, input, output) + req = c.newRequest(op, input, output) output = &InputService17TestShapeInputService17TestCaseOperation2Output{} req.Data = output return @@ -1623,8 +1558,6 @@ func (c *InputService17ProtocolTest) InputService17TestCaseOperation2(input *Inp return out, err } -var opInputService17TestCaseOperation2 *aws.Operation - type InputService17TestShapeInputService17TestCaseOperation1Output struct { metadataInputService17TestShapeInputService17TestCaseOperation1Output `json:"-" xml:"-"` } @@ -1683,22 +1616,21 @@ func (c *InputService18ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opInputService18TestCaseOperation1 = "OperationName" + // InputService18TestCaseOperation1Request generates a request for the InputService18TestCaseOperation1 operation. func (c *InputService18ProtocolTest) InputService18TestCaseOperation1Request(input *InputService18TestShapeInputShape) (req *aws.Request, output *InputService18TestShapeInputService18TestCaseOperation1Output) { - - if opInputService18TestCaseOperation1 == nil { - opInputService18TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } + op := &aws.Operation{ + Name: opInputService18TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/path", } if input == nil { input = &InputService18TestShapeInputShape{} } - req = c.newRequest(opInputService18TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService18TestShapeInputService18TestCaseOperation1Output{} req.Data = output return @@ -1710,24 +1642,21 @@ func (c *InputService18ProtocolTest) InputService18TestCaseOperation1(input *Inp return out, err } -var opInputService18TestCaseOperation1 *aws.Operation +const opInputService18TestCaseOperation2 = "OperationName" // InputService18TestCaseOperation2Request generates a request for the InputService18TestCaseOperation2 operation. func (c *InputService18ProtocolTest) InputService18TestCaseOperation2Request(input *InputService18TestShapeInputShape) (req *aws.Request, output *InputService18TestShapeInputService18TestCaseOperation2Output) { - - if opInputService18TestCaseOperation2 == nil { - opInputService18TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } + op := &aws.Operation{ + Name: opInputService18TestCaseOperation2, + HTTPMethod: "POST", + HTTPPath: "/path", } if input == nil { input = &InputService18TestShapeInputShape{} } - req = c.newRequest(opInputService18TestCaseOperation2, input, output) + req = c.newRequest(op, input, output) output = &InputService18TestShapeInputService18TestCaseOperation2Output{} req.Data = output return @@ -1739,24 +1668,21 @@ func (c *InputService18ProtocolTest) InputService18TestCaseOperation2(input *Inp return out, err } -var opInputService18TestCaseOperation2 *aws.Operation +const opInputService18TestCaseOperation3 = "OperationName" // InputService18TestCaseOperation3Request generates a request for the InputService18TestCaseOperation3 operation. func (c *InputService18ProtocolTest) InputService18TestCaseOperation3Request(input *InputService18TestShapeInputShape) (req *aws.Request, output *InputService18TestShapeInputService18TestCaseOperation3Output) { - - if opInputService18TestCaseOperation3 == nil { - opInputService18TestCaseOperation3 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } + op := &aws.Operation{ + Name: opInputService18TestCaseOperation3, + HTTPMethod: "POST", + HTTPPath: "/path", } if input == nil { input = &InputService18TestShapeInputShape{} } - req = c.newRequest(opInputService18TestCaseOperation3, input, output) + req = c.newRequest(op, input, output) output = &InputService18TestShapeInputService18TestCaseOperation3Output{} req.Data = output return @@ -1768,24 +1694,21 @@ func (c *InputService18ProtocolTest) InputService18TestCaseOperation3(input *Inp return out, err } -var opInputService18TestCaseOperation3 *aws.Operation +const opInputService18TestCaseOperation4 = "OperationName" // InputService18TestCaseOperation4Request generates a request for the InputService18TestCaseOperation4 operation. func (c *InputService18ProtocolTest) InputService18TestCaseOperation4Request(input *InputService18TestShapeInputShape) (req *aws.Request, output *InputService18TestShapeInputService18TestCaseOperation4Output) { - - if opInputService18TestCaseOperation4 == nil { - opInputService18TestCaseOperation4 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } + op := &aws.Operation{ + Name: opInputService18TestCaseOperation4, + HTTPMethod: "POST", + HTTPPath: "/path", } if input == nil { input = &InputService18TestShapeInputShape{} } - req = c.newRequest(opInputService18TestCaseOperation4, input, output) + req = c.newRequest(op, input, output) output = &InputService18TestShapeInputService18TestCaseOperation4Output{} req.Data = output return @@ -1797,24 +1720,21 @@ func (c *InputService18ProtocolTest) InputService18TestCaseOperation4(input *Inp return out, err } -var opInputService18TestCaseOperation4 *aws.Operation +const opInputService18TestCaseOperation5 = "OperationName" // InputService18TestCaseOperation5Request generates a request for the InputService18TestCaseOperation5 operation. func (c *InputService18ProtocolTest) InputService18TestCaseOperation5Request(input *InputService18TestShapeInputShape) (req *aws.Request, output *InputService18TestShapeInputService18TestCaseOperation5Output) { - - if opInputService18TestCaseOperation5 == nil { - opInputService18TestCaseOperation5 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } + op := &aws.Operation{ + Name: opInputService18TestCaseOperation5, + HTTPMethod: "POST", + HTTPPath: "/path", } if input == nil { input = &InputService18TestShapeInputShape{} } - req = c.newRequest(opInputService18TestCaseOperation5, input, output) + req = c.newRequest(op, input, output) output = &InputService18TestShapeInputService18TestCaseOperation5Output{} req.Data = output return @@ -1826,24 +1746,21 @@ func (c *InputService18ProtocolTest) InputService18TestCaseOperation5(input *Inp return out, err } -var opInputService18TestCaseOperation5 *aws.Operation +const opInputService18TestCaseOperation6 = "OperationName" // InputService18TestCaseOperation6Request generates a request for the InputService18TestCaseOperation6 operation. func (c *InputService18ProtocolTest) InputService18TestCaseOperation6Request(input *InputService18TestShapeInputShape) (req *aws.Request, output *InputService18TestShapeInputService18TestCaseOperation6Output) { - - if opInputService18TestCaseOperation6 == nil { - opInputService18TestCaseOperation6 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } + op := &aws.Operation{ + Name: opInputService18TestCaseOperation6, + HTTPMethod: "POST", + HTTPPath: "/path", } if input == nil { input = &InputService18TestShapeInputShape{} } - req = c.newRequest(opInputService18TestCaseOperation6, input, output) + req = c.newRequest(op, input, output) output = &InputService18TestShapeInputService18TestCaseOperation6Output{} req.Data = output return @@ -1855,8 +1772,6 @@ func (c *InputService18ProtocolTest) InputService18TestCaseOperation6(input *Inp return out, err } -var opInputService18TestCaseOperation6 *aws.Operation - type InputService18TestShapeInputService18TestCaseOperation1Output struct { metadataInputService18TestShapeInputService18TestCaseOperation1Output `json:"-" xml:"-"` } @@ -1963,22 +1878,21 @@ func (c *InputService19ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opInputService19TestCaseOperation1 = "OperationName" + // InputService19TestCaseOperation1Request generates a request for the InputService19TestCaseOperation1 operation. func (c *InputService19ProtocolTest) InputService19TestCaseOperation1Request(input *InputService19TestShapeInputShape) (req *aws.Request, output *InputService19TestShapeInputService19TestCaseOperation1Output) { - - if opInputService19TestCaseOperation1 == nil { - opInputService19TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - HTTPMethod: "POST", - HTTPPath: "/path", - } + op := &aws.Operation{ + Name: opInputService19TestCaseOperation1, + HTTPMethod: "POST", + HTTPPath: "/path", } if input == nil { input = &InputService19TestShapeInputShape{} } - req = c.newRequest(opInputService19TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &InputService19TestShapeInputService19TestCaseOperation1Output{} req.Data = output return @@ -1990,8 +1904,6 @@ func (c *InputService19ProtocolTest) InputService19TestCaseOperation1(input *Inp return out, err } -var opInputService19TestCaseOperation1 *aws.Operation - type InputService19TestShapeInputService19TestCaseOperation1Output struct { metadataInputService19TestShapeInputService19TestCaseOperation1Output `json:"-" xml:"-"` } @@ -2280,13 +2192,13 @@ func TestInputService9ProtocolTestListOfStructuresCase1(t *testing.T) { input := &InputService9TestShapeInputShape{ ListParam: []*InputService9TestShapeSingleFieldStruct{ - &InputService9TestShapeSingleFieldStruct{ + { Element: aws.String("one"), }, - &InputService9TestShapeSingleFieldStruct{ + { Element: aws.String("two"), }, - &InputService9TestShapeSingleFieldStruct{ + { Element: aws.String("three"), }, }, @@ -2701,10 +2613,10 @@ func TestInputService18ProtocolTestRecursiveShapesCase4(t *testing.T) { input := &InputService18TestShapeInputShape{ RecursiveStruct: &InputService18TestShapeRecursiveStructType{ RecursiveList: []*InputService18TestShapeRecursiveStructType{ - &InputService18TestShapeRecursiveStructType{ + { NoRecurse: aws.String("foo"), }, - &InputService18TestShapeRecursiveStructType{ + { NoRecurse: aws.String("bar"), }, }, @@ -2736,10 +2648,10 @@ func TestInputService18ProtocolTestRecursiveShapesCase5(t *testing.T) { input := &InputService18TestShapeInputShape{ RecursiveStruct: &InputService18TestShapeRecursiveStructType{ RecursiveList: []*InputService18TestShapeRecursiveStructType{ - &InputService18TestShapeRecursiveStructType{ + { NoRecurse: aws.String("foo"), }, - &InputService18TestShapeRecursiveStructType{ + { RecursiveStruct: &InputService18TestShapeRecursiveStructType{ NoRecurse: aws.String("bar"), }, @@ -2773,10 +2685,10 @@ func TestInputService18ProtocolTestRecursiveShapesCase6(t *testing.T) { input := &InputService18TestShapeInputShape{ RecursiveStruct: &InputService18TestShapeRecursiveStructType{ RecursiveMap: map[string]*InputService18TestShapeRecursiveStructType{ - "bar": &InputService18TestShapeRecursiveStructType{ + "bar": { NoRecurse: aws.String("bar"), }, - "foo": &InputService18TestShapeRecursiveStructType{ + "foo": { NoRecurse: aws.String("foo"), }, }, diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/restxml.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/restxml.go index cd4187738..d6cbff4f2 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/restxml.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/restxml.go @@ -1,3 +1,5 @@ +// Package restxml provides RESTful XML serialisation of AWS +// requests and responses. package restxml //go:generate go run ../../fixtures/protocol/generate.go ../../fixtures/protocol/input/rest-xml.json build_test.go @@ -8,7 +10,7 @@ import ( "encoding/xml" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/internal/protocol/query" "github.com/aws/aws-sdk-go/internal/protocol/rest" "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" @@ -22,7 +24,7 @@ func Build(r *aws.Request) { var buf bytes.Buffer err := xmlutil.BuildXML(r.Params, xml.NewEncoder(&buf)) if err != nil { - r.Error = apierr.New("Marshal", "failed to enode rest XML request", err) + r.Error = awserr.New("SerializationError", "failed to enode rest XML request", err) return } r.SetBufferBody(buf.Bytes()) @@ -36,7 +38,7 @@ func Unmarshal(r *aws.Request) { decoder := xml.NewDecoder(r.HTTPResponse.Body) err := xmlutil.UnmarshalXML(r.Data, decoder, "") if err != nil { - r.Error = apierr.New("Unmarshal", "failed to decode REST XML response", err) + r.Error = awserr.New("SerializationError", "failed to decode REST XML response", err) return } } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/unmarshal_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/unmarshal_test.go index 3016d33cf..7efb93d15 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/unmarshal_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/restxml/unmarshal_test.go @@ -1,10 +1,6 @@ package restxml_test import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/protocol/restxml" - "github.com/aws/aws-sdk-go/internal/signer/v4" - "bytes" "encoding/json" "encoding/xml" @@ -15,7 +11,10 @@ import ( "testing" "time" + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/internal/protocol/restxml" "github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil" + "github.com/aws/aws-sdk-go/internal/signer/v4" "github.com/aws/aws-sdk-go/internal/util" "github.com/stretchr/testify/assert" ) @@ -63,20 +62,19 @@ func (c *OutputService1ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService1TestCaseOperation1 = "OperationName" + // OutputService1TestCaseOperation1Request generates a request for the OutputService1TestCaseOperation1 operation. func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1Request(input *OutputService1TestShapeOutputService1TestCaseOperation1Input) (req *aws.Request, output *OutputService1TestShapeOutputShape) { - - if opOutputService1TestCaseOperation1 == nil { - opOutputService1TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService1TestCaseOperation1, } if input == nil { input = &OutputService1TestShapeOutputService1TestCaseOperation1Input{} } - req = c.newRequest(opOutputService1TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService1TestShapeOutputShape{} req.Data = output return @@ -88,22 +86,19 @@ func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation1(input *Out return out, err } -var opOutputService1TestCaseOperation1 *aws.Operation +const opOutputService1TestCaseOperation2 = "OperationName" // OutputService1TestCaseOperation2Request generates a request for the OutputService1TestCaseOperation2 operation. func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation2Request(input *OutputService1TestShapeOutputService1TestCaseOperation2Input) (req *aws.Request, output *OutputService1TestShapeOutputShape) { - - if opOutputService1TestCaseOperation2 == nil { - opOutputService1TestCaseOperation2 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService1TestCaseOperation2, } if input == nil { input = &OutputService1TestShapeOutputService1TestCaseOperation2Input{} } - req = c.newRequest(opOutputService1TestCaseOperation2, input, output) + req = c.newRequest(op, input, output) output = &OutputService1TestShapeOutputShape{} req.Data = output return @@ -115,8 +110,6 @@ func (c *OutputService1ProtocolTest) OutputService1TestCaseOperation2(input *Out return out, err } -var opOutputService1TestCaseOperation2 *aws.Operation - type OutputService1TestShapeOutputService1TestCaseOperation1Input struct { metadataOutputService1TestShapeOutputService1TestCaseOperation1Input `json:"-" xml:"-"` } @@ -195,20 +188,19 @@ func (c *OutputService2ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService2TestCaseOperation1 = "OperationName" + // OutputService2TestCaseOperation1Request generates a request for the OutputService2TestCaseOperation1 operation. func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1Request(input *OutputService2TestShapeOutputService2TestCaseOperation1Input) (req *aws.Request, output *OutputService2TestShapeOutputShape) { - - if opOutputService2TestCaseOperation1 == nil { - opOutputService2TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService2TestCaseOperation1, } if input == nil { input = &OutputService2TestShapeOutputService2TestCaseOperation1Input{} } - req = c.newRequest(opOutputService2TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService2TestShapeOutputShape{} req.Data = output return @@ -220,8 +212,6 @@ func (c *OutputService2ProtocolTest) OutputService2TestCaseOperation1(input *Out return out, err } -var opOutputService2TestCaseOperation1 *aws.Operation - type OutputService2TestShapeOutputService2TestCaseOperation1Input struct { metadataOutputService2TestShapeOutputService2TestCaseOperation1Input `json:"-" xml:"-"` } @@ -272,20 +262,19 @@ func (c *OutputService3ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService3TestCaseOperation1 = "OperationName" + // OutputService3TestCaseOperation1Request generates a request for the OutputService3TestCaseOperation1 operation. func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1Request(input *OutputService3TestShapeOutputService3TestCaseOperation1Input) (req *aws.Request, output *OutputService3TestShapeOutputShape) { - - if opOutputService3TestCaseOperation1 == nil { - opOutputService3TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService3TestCaseOperation1, } if input == nil { input = &OutputService3TestShapeOutputService3TestCaseOperation1Input{} } - req = c.newRequest(opOutputService3TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService3TestShapeOutputShape{} req.Data = output return @@ -297,8 +286,6 @@ func (c *OutputService3ProtocolTest) OutputService3TestCaseOperation1(input *Out return out, err } -var opOutputService3TestCaseOperation1 *aws.Operation - type OutputService3TestShapeOutputService3TestCaseOperation1Input struct { metadataOutputService3TestShapeOutputService3TestCaseOperation1Input `json:"-" xml:"-"` } @@ -349,20 +336,19 @@ func (c *OutputService4ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService4TestCaseOperation1 = "OperationName" + // OutputService4TestCaseOperation1Request generates a request for the OutputService4TestCaseOperation1 operation. func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1Request(input *OutputService4TestShapeOutputService4TestCaseOperation1Input) (req *aws.Request, output *OutputService4TestShapeOutputShape) { - - if opOutputService4TestCaseOperation1 == nil { - opOutputService4TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService4TestCaseOperation1, } if input == nil { input = &OutputService4TestShapeOutputService4TestCaseOperation1Input{} } - req = c.newRequest(opOutputService4TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService4TestShapeOutputShape{} req.Data = output return @@ -374,8 +360,6 @@ func (c *OutputService4ProtocolTest) OutputService4TestCaseOperation1(input *Out return out, err } -var opOutputService4TestCaseOperation1 *aws.Operation - type OutputService4TestShapeOutputService4TestCaseOperation1Input struct { metadataOutputService4TestShapeOutputService4TestCaseOperation1Input `json:"-" xml:"-"` } @@ -426,20 +410,19 @@ func (c *OutputService5ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService5TestCaseOperation1 = "OperationName" + // OutputService5TestCaseOperation1Request generates a request for the OutputService5TestCaseOperation1 operation. func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1Request(input *OutputService5TestShapeOutputService5TestCaseOperation1Input) (req *aws.Request, output *OutputService5TestShapeOutputShape) { - - if opOutputService5TestCaseOperation1 == nil { - opOutputService5TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService5TestCaseOperation1, } if input == nil { input = &OutputService5TestShapeOutputService5TestCaseOperation1Input{} } - req = c.newRequest(opOutputService5TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService5TestShapeOutputShape{} req.Data = output return @@ -451,8 +434,6 @@ func (c *OutputService5ProtocolTest) OutputService5TestCaseOperation1(input *Out return out, err } -var opOutputService5TestCaseOperation1 *aws.Operation - type OutputService5TestShapeOutputService5TestCaseOperation1Input struct { metadataOutputService5TestShapeOutputService5TestCaseOperation1Input `json:"-" xml:"-"` } @@ -503,20 +484,19 @@ func (c *OutputService6ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService6TestCaseOperation1 = "OperationName" + // OutputService6TestCaseOperation1Request generates a request for the OutputService6TestCaseOperation1 operation. func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1Request(input *OutputService6TestShapeOutputService6TestCaseOperation1Input) (req *aws.Request, output *OutputService6TestShapeOutputShape) { - - if opOutputService6TestCaseOperation1 == nil { - opOutputService6TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService6TestCaseOperation1, } if input == nil { input = &OutputService6TestShapeOutputService6TestCaseOperation1Input{} } - req = c.newRequest(opOutputService6TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService6TestShapeOutputShape{} req.Data = output return @@ -528,8 +508,6 @@ func (c *OutputService6ProtocolTest) OutputService6TestCaseOperation1(input *Out return out, err } -var opOutputService6TestCaseOperation1 *aws.Operation - type OutputService6TestShapeOutputService6TestCaseOperation1Input struct { metadataOutputService6TestShapeOutputService6TestCaseOperation1Input `json:"-" xml:"-"` } @@ -590,20 +568,19 @@ func (c *OutputService7ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService7TestCaseOperation1 = "OperationName" + // OutputService7TestCaseOperation1Request generates a request for the OutputService7TestCaseOperation1 operation. func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1Request(input *OutputService7TestShapeOutputService7TestCaseOperation1Input) (req *aws.Request, output *OutputService7TestShapeOutputShape) { - - if opOutputService7TestCaseOperation1 == nil { - opOutputService7TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService7TestCaseOperation1, } if input == nil { input = &OutputService7TestShapeOutputService7TestCaseOperation1Input{} } - req = c.newRequest(opOutputService7TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService7TestShapeOutputShape{} req.Data = output return @@ -615,8 +592,6 @@ func (c *OutputService7ProtocolTest) OutputService7TestCaseOperation1(input *Out return out, err } -var opOutputService7TestCaseOperation1 *aws.Operation - type OutputService7TestShapeOutputService7TestCaseOperation1Input struct { metadataOutputService7TestShapeOutputService7TestCaseOperation1Input `json:"-" xml:"-"` } @@ -667,20 +642,19 @@ func (c *OutputService8ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService8TestCaseOperation1 = "OperationName" + // OutputService8TestCaseOperation1Request generates a request for the OutputService8TestCaseOperation1 operation. func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1Request(input *OutputService8TestShapeOutputService8TestCaseOperation1Input) (req *aws.Request, output *OutputService8TestShapeOutputShape) { - - if opOutputService8TestCaseOperation1 == nil { - opOutputService8TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService8TestCaseOperation1, } if input == nil { input = &OutputService8TestShapeOutputService8TestCaseOperation1Input{} } - req = c.newRequest(opOutputService8TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService8TestShapeOutputShape{} req.Data = output return @@ -692,8 +666,6 @@ func (c *OutputService8ProtocolTest) OutputService8TestCaseOperation1(input *Out return out, err } -var opOutputService8TestCaseOperation1 *aws.Operation - type OutputService8TestShapeOutputService8TestCaseOperation1Input struct { metadataOutputService8TestShapeOutputService8TestCaseOperation1Input `json:"-" xml:"-"` } @@ -744,20 +716,19 @@ func (c *OutputService9ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService9TestCaseOperation1 = "OperationName" + // OutputService9TestCaseOperation1Request generates a request for the OutputService9TestCaseOperation1 operation. func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1Request(input *OutputService9TestShapeOutputService9TestCaseOperation1Input) (req *aws.Request, output *OutputService9TestShapeOutputShape) { - - if opOutputService9TestCaseOperation1 == nil { - opOutputService9TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService9TestCaseOperation1, } if input == nil { input = &OutputService9TestShapeOutputService9TestCaseOperation1Input{} } - req = c.newRequest(opOutputService9TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService9TestShapeOutputShape{} req.Data = output return @@ -769,8 +740,6 @@ func (c *OutputService9ProtocolTest) OutputService9TestCaseOperation1(input *Out return out, err } -var opOutputService9TestCaseOperation1 *aws.Operation - type OutputService9TestShapeOutputService9TestCaseOperation1Input struct { metadataOutputService9TestShapeOutputService9TestCaseOperation1Input `json:"-" xml:"-"` } @@ -833,20 +802,19 @@ func (c *OutputService10ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService10TestCaseOperation1 = "OperationName" + // OutputService10TestCaseOperation1Request generates a request for the OutputService10TestCaseOperation1 operation. func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1Request(input *OutputService10TestShapeOutputService10TestCaseOperation1Input) (req *aws.Request, output *OutputService10TestShapeOutputShape) { - - if opOutputService10TestCaseOperation1 == nil { - opOutputService10TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService10TestCaseOperation1, } if input == nil { input = &OutputService10TestShapeOutputService10TestCaseOperation1Input{} } - req = c.newRequest(opOutputService10TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService10TestShapeOutputShape{} req.Data = output return @@ -858,8 +826,6 @@ func (c *OutputService10ProtocolTest) OutputService10TestCaseOperation1(input *O return out, err } -var opOutputService10TestCaseOperation1 *aws.Operation - type OutputService10TestShapeOutputService10TestCaseOperation1Input struct { metadataOutputService10TestShapeOutputService10TestCaseOperation1Input `json:"-" xml:"-"` } @@ -910,20 +876,19 @@ func (c *OutputService11ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService11TestCaseOperation1 = "OperationName" + // OutputService11TestCaseOperation1Request generates a request for the OutputService11TestCaseOperation1 operation. func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1Request(input *OutputService11TestShapeOutputService11TestCaseOperation1Input) (req *aws.Request, output *OutputService11TestShapeOutputShape) { - - if opOutputService11TestCaseOperation1 == nil { - opOutputService11TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService11TestCaseOperation1, } if input == nil { input = &OutputService11TestShapeOutputService11TestCaseOperation1Input{} } - req = c.newRequest(opOutputService11TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService11TestShapeOutputShape{} req.Data = output return @@ -935,8 +900,6 @@ func (c *OutputService11ProtocolTest) OutputService11TestCaseOperation1(input *O return out, err } -var opOutputService11TestCaseOperation1 *aws.Operation - type OutputService11TestShapeOutputService11TestCaseOperation1Input struct { metadataOutputService11TestShapeOutputService11TestCaseOperation1Input `json:"-" xml:"-"` } @@ -1003,20 +966,19 @@ func (c *OutputService12ProtocolTest) newRequest(op *aws.Operation, params, data return req } +const opOutputService12TestCaseOperation1 = "OperationName" + // OutputService12TestCaseOperation1Request generates a request for the OutputService12TestCaseOperation1 operation. func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1Request(input *OutputService12TestShapeOutputService12TestCaseOperation1Input) (req *aws.Request, output *OutputService12TestShapeOutputShape) { - - if opOutputService12TestCaseOperation1 == nil { - opOutputService12TestCaseOperation1 = &aws.Operation{ - Name: "OperationName", - } + op := &aws.Operation{ + Name: opOutputService12TestCaseOperation1, } if input == nil { input = &OutputService12TestShapeOutputService12TestCaseOperation1Input{} } - req = c.newRequest(opOutputService12TestCaseOperation1, input, output) + req = c.newRequest(op, input, output) output = &OutputService12TestShapeOutputShape{} req.Data = output return @@ -1028,8 +990,6 @@ func (c *OutputService12ProtocolTest) OutputService12TestCaseOperation1(input *O return out, err } -var opOutputService12TestCaseOperation1 *aws.Operation - type OutputService12TestShapeOutputService12TestCaseOperation1Input struct { metadataOutputService12TestShapeOutputService12TestCaseOperation1Input `json:"-" xml:"-"` } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil/build.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil/build.go index 8791bfdab..d3db25023 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil/build.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil/build.go @@ -1,3 +1,4 @@ +// Package xmlutil provides XML serialisation of AWS requests and responses. package xmlutil import ( diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil/unmarshal.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil/unmarshal.go index a7b7a60b2..5e4fe210b 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil/unmarshal.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/protocol/xml/xmlutil/unmarshal.go @@ -114,7 +114,7 @@ func parseStruct(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { for _, a := range node.Attr { if name == a.Name.Local { // turn this into a text node for de-serializing - elems = []*XMLNode{&XMLNode{Text: a.Value}} + elems = []*XMLNode{{Text: a.Value}} } } } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4.go index 05d5dad7d..6fef0d666 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4.go @@ -1,3 +1,4 @@ +// Package v4 implements signing for AWS V4 signer package v4 import ( @@ -33,18 +34,17 @@ var ignoredHeaders = map[string]bool{ } type signer struct { - Request *http.Request - Time time.Time - ExpireTime time.Duration - ServiceName string - Region string - AccessKeyID string - SecretAccessKey string - SessionToken string - Query url.Values - Body io.ReadSeeker - Debug uint - Logger io.Writer + Request *http.Request + Time time.Time + ExpireTime time.Duration + ServiceName string + Region string + CredValues credentials.Value + Credentials *credentials.Credentials + Query url.Values + Body io.ReadSeeker + Debug uint + Logger io.Writer isPresign bool formattedTime string @@ -70,11 +70,6 @@ func Sign(req *aws.Request) { if req.Service.Config.Credentials == credentials.AnonymousCredentials { return } - creds, err := req.Service.Config.Credentials.Get() - if err != nil { - req.Error = err - return - } region := req.Service.SigningRegion if region == "" { @@ -87,56 +82,84 @@ func Sign(req *aws.Request) { } s := signer{ - Request: req.HTTPRequest, - Time: req.Time, - ExpireTime: req.ExpireTime, - Query: req.HTTPRequest.URL.Query(), - Body: req.Body, - ServiceName: name, - Region: region, - AccessKeyID: creds.AccessKeyID, - SecretAccessKey: creds.SecretAccessKey, - SessionToken: creds.SessionToken, - Debug: req.Service.Config.LogLevel, - Logger: req.Service.Config.Logger, + Request: req.HTTPRequest, + Time: req.Time, + ExpireTime: req.ExpireTime, + Query: req.HTTPRequest.URL.Query(), + Body: req.Body, + ServiceName: name, + Region: region, + Credentials: req.Service.Config.Credentials, + Debug: req.Service.Config.LogLevel, + Logger: req.Service.Config.Logger, } - s.sign() - return + + req.Error = s.sign() } -func (v4 *signer) sign() { +func (v4 *signer) sign() error { if v4.ExpireTime != 0 { v4.isPresign = true } + if v4.isRequestSigned() { + if !v4.Credentials.IsExpired() { + // If the request is already signed, and the credentials have not + // expired yet ignore the signing request. + return nil + } + + // The credentials have expired for this request. The current signing + // is invalid, and needs to be request because the request will fail. + if v4.isPresign { + v4.removePresign() + // Update the request's query string to ensure the values stays in + // sync in the case retrieving the new credentials fails. + v4.Request.URL.RawQuery = v4.Query.Encode() + } + } + + var err error + v4.CredValues, err = v4.Credentials.Get() + if err != nil { + return err + } + if v4.isPresign { v4.Query.Set("X-Amz-Algorithm", authHeaderPrefix) - if v4.SessionToken != "" { - v4.Query.Set("X-Amz-Security-Token", v4.SessionToken) + if v4.CredValues.SessionToken != "" { + v4.Query.Set("X-Amz-Security-Token", v4.CredValues.SessionToken) } else { v4.Query.Del("X-Amz-Security-Token") } - } else if v4.SessionToken != "" { - v4.Request.Header.Set("X-Amz-Security-Token", v4.SessionToken) + } else if v4.CredValues.SessionToken != "" { + v4.Request.Header.Set("X-Amz-Security-Token", v4.CredValues.SessionToken) } v4.build() if v4.Debug > 0 { - out := v4.Logger - fmt.Fprintf(out, "---[ CANONICAL STRING ]-----------------------------\n") - fmt.Fprintln(out, v4.canonicalString) - fmt.Fprintf(out, "---[ STRING TO SIGN ]--------------------------------\n") - fmt.Fprintln(out, v4.stringToSign) - if v4.isPresign { - fmt.Fprintf(out, "---[ SIGNED URL ]--------------------------------\n") - fmt.Fprintln(out, v4.Request.URL) - } - fmt.Fprintf(out, "-----------------------------------------------------\n") + v4.logSigningInfo() } + + return nil +} + +func (v4 *signer) logSigningInfo() { + out := v4.Logger + fmt.Fprintf(out, "---[ CANONICAL STRING ]-----------------------------\n") + fmt.Fprintln(out, v4.canonicalString) + fmt.Fprintf(out, "---[ STRING TO SIGN ]--------------------------------\n") + fmt.Fprintln(out, v4.stringToSign) + if v4.isPresign { + fmt.Fprintf(out, "---[ SIGNED URL ]--------------------------------\n") + fmt.Fprintln(out, v4.Request.URL) + } + fmt.Fprintf(out, "-----------------------------------------------------\n") } func (v4 *signer) build() { + v4.buildTime() // no depends v4.buildCredentialString() // no depends if v4.isPresign { @@ -151,7 +174,7 @@ func (v4 *signer) build() { v4.Request.URL.RawQuery += "&X-Amz-Signature=" + v4.signature } else { parts := []string{ - authHeaderPrefix + " Credential=" + v4.AccessKeyID + "/" + v4.credentialString, + authHeaderPrefix + " Credential=" + v4.CredValues.AccessKeyID + "/" + v4.credentialString, "SignedHeaders=" + v4.signedHeaders, "Signature=" + v4.signature, } @@ -181,7 +204,7 @@ func (v4 *signer) buildCredentialString() { }, "/") if v4.isPresign { - v4.Query.Set("X-Amz-Credential", v4.AccessKeyID+"/"+v4.credentialString) + v4.Query.Set("X-Amz-Credential", v4.CredValues.AccessKeyID+"/"+v4.credentialString) } } @@ -268,7 +291,7 @@ func (v4 *signer) buildStringToSign() { } func (v4 *signer) buildSignature() { - secret := v4.SecretAccessKey + secret := v4.CredValues.SecretAccessKey date := makeHmac([]byte("AWS4"+secret), []byte(v4.formattedShortTime)) region := makeHmac(date, []byte(v4.Region)) service := makeHmac(region, []byte(v4.ServiceName)) @@ -292,6 +315,29 @@ func (v4 *signer) bodyDigest() string { return hash } +// isRequestSigned returns if the request is currently signed or presigned +func (v4 *signer) isRequestSigned() bool { + if v4.isPresign && v4.Query.Get("X-Amz-Signature") != "" { + return true + } + if v4.Request.Header.Get("Authorization") != "" { + return true + } + + return false +} + +// unsign removes signing flags for both signed and presigned requests. +func (v4 *signer) removePresign() { + v4.Query.Del("X-Amz-Algorithm") + v4.Query.Del("X-Amz-Signature") + v4.Query.Del("X-Amz-Security-Token") + v4.Query.Del("X-Amz-Date") + v4.Query.Del("X-Amz-Expires") + v4.Query.Del("X-Amz-Credential") + v4.Query.Del("X-Amz-SignedHeaders") +} + func makeHmac(key []byte, data []byte) []byte { hash := hmac.New(sha256.New, key) hash.Write(data) @@ -305,21 +351,10 @@ func makeSha256(data []byte) []byte { } func makeSha256Reader(reader io.ReadSeeker) []byte { - packet := make([]byte, 4096) hash := sha256.New() - start, _ := reader.Seek(0, 1) defer reader.Seek(start, 0) - for { - n, err := reader.Read(packet) - if n > 0 { - hash.Write(packet[0:n]) - } - if err == io.EOF || n == 0 { - break - } - } - + io.Copy(hash, reader) return hash.Sum(nil) } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4_test.go index 20f655ac6..99966f809 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/internal/signer/v4/v4_test.go @@ -22,16 +22,14 @@ func buildSigner(serviceName string, region string, signTime time.Time, expireTi req.Header.Add("X-Amz-Meta-Other-Header", "some-value=!@#$%^&* (+)") return signer{ - Request: req, - Time: signTime, - ExpireTime: expireTime, - Query: req.URL.Query(), - Body: reader, - ServiceName: serviceName, - Region: region, - AccessKeyID: "AKID", - SecretAccessKey: "SECRET", - SessionToken: "SESSION", + Request: req, + Time: signTime, + ExpireTime: expireTime, + Query: req.URL.Query(), + Body: reader, + ServiceName: serviceName, + Region: region, + Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), } } @@ -141,6 +139,97 @@ func TestAnonymousCredentials(t *testing.T) { assert.Empty(t, hQ.Get("X-Amz-Date")) } +func TestIgnoreResignRequestWithValidCreds(t *testing.T) { + r := aws.NewRequest( + aws.NewService(&aws.Config{ + Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), + Region: "us-west-2", + }), + &aws.Operation{ + Name: "BatchGetItem", + HTTPMethod: "POST", + HTTPPath: "/", + }, + nil, + nil, + ) + + Sign(r) + sig := r.HTTPRequest.Header.Get("Authorization") + + Sign(r) + assert.Equal(t, sig, r.HTTPRequest.Header.Get("Authorization")) +} + +func TestIgnorePreResignRequestWithValidCreds(t *testing.T) { + r := aws.NewRequest( + aws.NewService(&aws.Config{ + Credentials: credentials.NewStaticCredentials("AKID", "SECRET", "SESSION"), + Region: "us-west-2", + }), + &aws.Operation{ + Name: "BatchGetItem", + HTTPMethod: "POST", + HTTPPath: "/", + }, + nil, + nil, + ) + r.ExpireTime = time.Minute * 10 + + Sign(r) + sig := r.HTTPRequest.Header.Get("X-Amz-Signature") + + Sign(r) + assert.Equal(t, sig, r.HTTPRequest.Header.Get("X-Amz-Signature")) +} + +func TestResignRequestExpiredCreds(t *testing.T) { + creds := credentials.NewStaticCredentials("AKID", "SECRET", "SESSION") + r := aws.NewRequest( + aws.NewService(&aws.Config{Credentials: creds}), + &aws.Operation{ + Name: "BatchGetItem", + HTTPMethod: "POST", + HTTPPath: "/", + }, + nil, + nil, + ) + Sign(r) + querySig := r.HTTPRequest.Header.Get("Authorization") + + creds.Expire() + + Sign(r) + assert.NotEqual(t, querySig, r.HTTPRequest.Header.Get("Authorization")) +} + +func TestPreResignRequestExpiredCreds(t *testing.T) { + provider := &credentials.StaticProvider{credentials.Value{"AKID", "SECRET", "SESSION"}} + creds := credentials.NewCredentials(provider) + r := aws.NewRequest( + aws.NewService(&aws.Config{Credentials: creds}), + &aws.Operation{ + Name: "BatchGetItem", + HTTPMethod: "POST", + HTTPPath: "/", + }, + nil, + nil, + ) + r.ExpireTime = time.Minute * 10 + + Sign(r) + querySig := r.HTTPRequest.URL.Query().Get("X-Amz-Signature") + + creds.Expire() + r.Time = time.Now().Add(time.Hour * 48) + + Sign(r) + assert.NotEqual(t, querySig, r.HTTPRequest.URL.Query().Get("X-Amz-Signature")) +} + func BenchmarkPresignRequest(b *testing.B) { signer := buildSigner("dynamodb", "us-east-1", time.Now(), 300*time.Second, "{}") for i := 0; i < b.N; i++ { diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/api.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/api.go index c1293baf5..e70258332 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/api.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/api.go @@ -5,32 +5,26 @@ package s3 import ( "io" - "sync" "time" "github.com/aws/aws-sdk-go/aws" ) -var oprw sync.Mutex +const opAbortMultipartUpload = "AbortMultipartUpload" // AbortMultipartUploadRequest generates a request for the AbortMultipartUpload operation. func (c *S3) AbortMultipartUploadRequest(input *AbortMultipartUploadInput) (req *aws.Request, output *AbortMultipartUploadOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opAbortMultipartUpload == nil { - opAbortMultipartUpload = &aws.Operation{ - Name: "AbortMultipartUpload", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}/{Key+}", - } + op := &aws.Operation{ + Name: opAbortMultipartUpload, + HTTPMethod: "DELETE", + HTTPPath: "/{Bucket}/{Key+}", } if input == nil { input = &AbortMultipartUploadInput{} } - req = c.newRequest(opAbortMultipartUpload, input, output) + req = c.newRequest(op, input, output) output = &AbortMultipartUploadOutput{} req.Data = output return @@ -47,26 +41,21 @@ func (c *S3) AbortMultipartUpload(input *AbortMultipartUploadInput) (*AbortMulti return out, err } -var opAbortMultipartUpload *aws.Operation +const opCompleteMultipartUpload = "CompleteMultipartUpload" // CompleteMultipartUploadRequest generates a request for the CompleteMultipartUpload operation. func (c *S3) CompleteMultipartUploadRequest(input *CompleteMultipartUploadInput) (req *aws.Request, output *CompleteMultipartUploadOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opCompleteMultipartUpload == nil { - opCompleteMultipartUpload = &aws.Operation{ - Name: "CompleteMultipartUpload", - HTTPMethod: "POST", - HTTPPath: "/{Bucket}/{Key+}", - } + op := &aws.Operation{ + Name: opCompleteMultipartUpload, + HTTPMethod: "POST", + HTTPPath: "/{Bucket}/{Key+}", } if input == nil { input = &CompleteMultipartUploadInput{} } - req = c.newRequest(opCompleteMultipartUpload, input, output) + req = c.newRequest(op, input, output) output = &CompleteMultipartUploadOutput{} req.Data = output return @@ -79,26 +68,21 @@ func (c *S3) CompleteMultipartUpload(input *CompleteMultipartUploadInput) (*Comp return out, err } -var opCompleteMultipartUpload *aws.Operation +const opCopyObject = "CopyObject" // CopyObjectRequest generates a request for the CopyObject operation. func (c *S3) CopyObjectRequest(input *CopyObjectInput) (req *aws.Request, output *CopyObjectOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opCopyObject == nil { - opCopyObject = &aws.Operation{ - Name: "CopyObject", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", - } + op := &aws.Operation{ + Name: opCopyObject, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}/{Key+}", } if input == nil { input = &CopyObjectInput{} } - req = c.newRequest(opCopyObject, input, output) + req = c.newRequest(op, input, output) output = &CopyObjectOutput{} req.Data = output return @@ -111,26 +95,21 @@ func (c *S3) CopyObject(input *CopyObjectInput) (*CopyObjectOutput, error) { return out, err } -var opCopyObject *aws.Operation +const opCreateBucket = "CreateBucket" // CreateBucketRequest generates a request for the CreateBucket operation. func (c *S3) CreateBucketRequest(input *CreateBucketInput) (req *aws.Request, output *CreateBucketOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opCreateBucket == nil { - opCreateBucket = &aws.Operation{ - Name: "CreateBucket", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}", - } + op := &aws.Operation{ + Name: opCreateBucket, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}", } if input == nil { input = &CreateBucketInput{} } - req = c.newRequest(opCreateBucket, input, output) + req = c.newRequest(op, input, output) output = &CreateBucketOutput{} req.Data = output return @@ -143,26 +122,21 @@ func (c *S3) CreateBucket(input *CreateBucketInput) (*CreateBucketOutput, error) return out, err } -var opCreateBucket *aws.Operation +const opCreateMultipartUpload = "CreateMultipartUpload" // CreateMultipartUploadRequest generates a request for the CreateMultipartUpload operation. func (c *S3) CreateMultipartUploadRequest(input *CreateMultipartUploadInput) (req *aws.Request, output *CreateMultipartUploadOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opCreateMultipartUpload == nil { - opCreateMultipartUpload = &aws.Operation{ - Name: "CreateMultipartUpload", - HTTPMethod: "POST", - HTTPPath: "/{Bucket}/{Key+}?uploads", - } + op := &aws.Operation{ + Name: opCreateMultipartUpload, + HTTPMethod: "POST", + HTTPPath: "/{Bucket}/{Key+}?uploads", } if input == nil { input = &CreateMultipartUploadInput{} } - req = c.newRequest(opCreateMultipartUpload, input, output) + req = c.newRequest(op, input, output) output = &CreateMultipartUploadOutput{} req.Data = output return @@ -181,26 +155,21 @@ func (c *S3) CreateMultipartUpload(input *CreateMultipartUploadInput) (*CreateMu return out, err } -var opCreateMultipartUpload *aws.Operation +const opDeleteBucket = "DeleteBucket" // DeleteBucketRequest generates a request for the DeleteBucket operation. func (c *S3) DeleteBucketRequest(input *DeleteBucketInput) (req *aws.Request, output *DeleteBucketOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucket == nil { - opDeleteBucket = &aws.Operation{ - Name: "DeleteBucket", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}", - } + op := &aws.Operation{ + Name: opDeleteBucket, + HTTPMethod: "DELETE", + HTTPPath: "/{Bucket}", } if input == nil { input = &DeleteBucketInput{} } - req = c.newRequest(opDeleteBucket, input, output) + req = c.newRequest(op, input, output) output = &DeleteBucketOutput{} req.Data = output return @@ -214,26 +183,21 @@ func (c *S3) DeleteBucket(input *DeleteBucketInput) (*DeleteBucketOutput, error) return out, err } -var opDeleteBucket *aws.Operation +const opDeleteBucketCORS = "DeleteBucketCors" // DeleteBucketCORSRequest generates a request for the DeleteBucketCORS operation. func (c *S3) DeleteBucketCORSRequest(input *DeleteBucketCORSInput) (req *aws.Request, output *DeleteBucketCORSOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucketCORS == nil { - opDeleteBucketCORS = &aws.Operation{ - Name: "DeleteBucketCors", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?cors", - } + op := &aws.Operation{ + Name: opDeleteBucketCORS, + HTTPMethod: "DELETE", + HTTPPath: "/{Bucket}?cors", } if input == nil { input = &DeleteBucketCORSInput{} } - req = c.newRequest(opDeleteBucketCORS, input, output) + req = c.newRequest(op, input, output) output = &DeleteBucketCORSOutput{} req.Data = output return @@ -246,26 +210,21 @@ func (c *S3) DeleteBucketCORS(input *DeleteBucketCORSInput) (*DeleteBucketCORSOu return out, err } -var opDeleteBucketCORS *aws.Operation +const opDeleteBucketLifecycle = "DeleteBucketLifecycle" // DeleteBucketLifecycleRequest generates a request for the DeleteBucketLifecycle operation. func (c *S3) DeleteBucketLifecycleRequest(input *DeleteBucketLifecycleInput) (req *aws.Request, output *DeleteBucketLifecycleOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucketLifecycle == nil { - opDeleteBucketLifecycle = &aws.Operation{ - Name: "DeleteBucketLifecycle", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?lifecycle", - } + op := &aws.Operation{ + Name: opDeleteBucketLifecycle, + HTTPMethod: "DELETE", + HTTPPath: "/{Bucket}?lifecycle", } if input == nil { input = &DeleteBucketLifecycleInput{} } - req = c.newRequest(opDeleteBucketLifecycle, input, output) + req = c.newRequest(op, input, output) output = &DeleteBucketLifecycleOutput{} req.Data = output return @@ -278,26 +237,21 @@ func (c *S3) DeleteBucketLifecycle(input *DeleteBucketLifecycleInput) (*DeleteBu return out, err } -var opDeleteBucketLifecycle *aws.Operation +const opDeleteBucketPolicy = "DeleteBucketPolicy" // DeleteBucketPolicyRequest generates a request for the DeleteBucketPolicy operation. func (c *S3) DeleteBucketPolicyRequest(input *DeleteBucketPolicyInput) (req *aws.Request, output *DeleteBucketPolicyOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucketPolicy == nil { - opDeleteBucketPolicy = &aws.Operation{ - Name: "DeleteBucketPolicy", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?policy", - } + op := &aws.Operation{ + Name: opDeleteBucketPolicy, + HTTPMethod: "DELETE", + HTTPPath: "/{Bucket}?policy", } if input == nil { input = &DeleteBucketPolicyInput{} } - req = c.newRequest(opDeleteBucketPolicy, input, output) + req = c.newRequest(op, input, output) output = &DeleteBucketPolicyOutput{} req.Data = output return @@ -310,26 +264,21 @@ func (c *S3) DeleteBucketPolicy(input *DeleteBucketPolicyInput) (*DeleteBucketPo return out, err } -var opDeleteBucketPolicy *aws.Operation +const opDeleteBucketReplication = "DeleteBucketReplication" // DeleteBucketReplicationRequest generates a request for the DeleteBucketReplication operation. func (c *S3) DeleteBucketReplicationRequest(input *DeleteBucketReplicationInput) (req *aws.Request, output *DeleteBucketReplicationOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucketReplication == nil { - opDeleteBucketReplication = &aws.Operation{ - Name: "DeleteBucketReplication", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?replication", - } + op := &aws.Operation{ + Name: opDeleteBucketReplication, + HTTPMethod: "DELETE", + HTTPPath: "/{Bucket}?replication", } if input == nil { input = &DeleteBucketReplicationInput{} } - req = c.newRequest(opDeleteBucketReplication, input, output) + req = c.newRequest(op, input, output) output = &DeleteBucketReplicationOutput{} req.Data = output return @@ -341,26 +290,21 @@ func (c *S3) DeleteBucketReplication(input *DeleteBucketReplicationInput) (*Dele return out, err } -var opDeleteBucketReplication *aws.Operation +const opDeleteBucketTagging = "DeleteBucketTagging" // DeleteBucketTaggingRequest generates a request for the DeleteBucketTagging operation. func (c *S3) DeleteBucketTaggingRequest(input *DeleteBucketTaggingInput) (req *aws.Request, output *DeleteBucketTaggingOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucketTagging == nil { - opDeleteBucketTagging = &aws.Operation{ - Name: "DeleteBucketTagging", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?tagging", - } + op := &aws.Operation{ + Name: opDeleteBucketTagging, + HTTPMethod: "DELETE", + HTTPPath: "/{Bucket}?tagging", } if input == nil { input = &DeleteBucketTaggingInput{} } - req = c.newRequest(opDeleteBucketTagging, input, output) + req = c.newRequest(op, input, output) output = &DeleteBucketTaggingOutput{} req.Data = output return @@ -373,26 +317,21 @@ func (c *S3) DeleteBucketTagging(input *DeleteBucketTaggingInput) (*DeleteBucket return out, err } -var opDeleteBucketTagging *aws.Operation +const opDeleteBucketWebsite = "DeleteBucketWebsite" // DeleteBucketWebsiteRequest generates a request for the DeleteBucketWebsite operation. func (c *S3) DeleteBucketWebsiteRequest(input *DeleteBucketWebsiteInput) (req *aws.Request, output *DeleteBucketWebsiteOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteBucketWebsite == nil { - opDeleteBucketWebsite = &aws.Operation{ - Name: "DeleteBucketWebsite", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}?website", - } + op := &aws.Operation{ + Name: opDeleteBucketWebsite, + HTTPMethod: "DELETE", + HTTPPath: "/{Bucket}?website", } if input == nil { input = &DeleteBucketWebsiteInput{} } - req = c.newRequest(opDeleteBucketWebsite, input, output) + req = c.newRequest(op, input, output) output = &DeleteBucketWebsiteOutput{} req.Data = output return @@ -405,26 +344,21 @@ func (c *S3) DeleteBucketWebsite(input *DeleteBucketWebsiteInput) (*DeleteBucket return out, err } -var opDeleteBucketWebsite *aws.Operation +const opDeleteObject = "DeleteObject" // DeleteObjectRequest generates a request for the DeleteObject operation. func (c *S3) DeleteObjectRequest(input *DeleteObjectInput) (req *aws.Request, output *DeleteObjectOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteObject == nil { - opDeleteObject = &aws.Operation{ - Name: "DeleteObject", - HTTPMethod: "DELETE", - HTTPPath: "/{Bucket}/{Key+}", - } + op := &aws.Operation{ + Name: opDeleteObject, + HTTPMethod: "DELETE", + HTTPPath: "/{Bucket}/{Key+}", } if input == nil { input = &DeleteObjectInput{} } - req = c.newRequest(opDeleteObject, input, output) + req = c.newRequest(op, input, output) output = &DeleteObjectOutput{} req.Data = output return @@ -439,26 +373,21 @@ func (c *S3) DeleteObject(input *DeleteObjectInput) (*DeleteObjectOutput, error) return out, err } -var opDeleteObject *aws.Operation +const opDeleteObjects = "DeleteObjects" // DeleteObjectsRequest generates a request for the DeleteObjects operation. func (c *S3) DeleteObjectsRequest(input *DeleteObjectsInput) (req *aws.Request, output *DeleteObjectsOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opDeleteObjects == nil { - opDeleteObjects = &aws.Operation{ - Name: "DeleteObjects", - HTTPMethod: "POST", - HTTPPath: "/{Bucket}?delete", - } + op := &aws.Operation{ + Name: opDeleteObjects, + HTTPMethod: "POST", + HTTPPath: "/{Bucket}?delete", } if input == nil { input = &DeleteObjectsInput{} } - req = c.newRequest(opDeleteObjects, input, output) + req = c.newRequest(op, input, output) output = &DeleteObjectsOutput{} req.Data = output return @@ -472,26 +401,21 @@ func (c *S3) DeleteObjects(input *DeleteObjectsInput) (*DeleteObjectsOutput, err return out, err } -var opDeleteObjects *aws.Operation +const opGetBucketACL = "GetBucketAcl" // GetBucketACLRequest generates a request for the GetBucketACL operation. func (c *S3) GetBucketACLRequest(input *GetBucketACLInput) (req *aws.Request, output *GetBucketACLOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketACL == nil { - opGetBucketACL = &aws.Operation{ - Name: "GetBucketAcl", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?acl", - } + op := &aws.Operation{ + Name: opGetBucketACL, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?acl", } if input == nil { input = &GetBucketACLInput{} } - req = c.newRequest(opGetBucketACL, input, output) + req = c.newRequest(op, input, output) output = &GetBucketACLOutput{} req.Data = output return @@ -504,26 +428,21 @@ func (c *S3) GetBucketACL(input *GetBucketACLInput) (*GetBucketACLOutput, error) return out, err } -var opGetBucketACL *aws.Operation +const opGetBucketCORS = "GetBucketCors" // GetBucketCORSRequest generates a request for the GetBucketCORS operation. func (c *S3) GetBucketCORSRequest(input *GetBucketCORSInput) (req *aws.Request, output *GetBucketCORSOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketCORS == nil { - opGetBucketCORS = &aws.Operation{ - Name: "GetBucketCors", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?cors", - } + op := &aws.Operation{ + Name: opGetBucketCORS, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?cors", } if input == nil { input = &GetBucketCORSInput{} } - req = c.newRequest(opGetBucketCORS, input, output) + req = c.newRequest(op, input, output) output = &GetBucketCORSOutput{} req.Data = output return @@ -536,26 +455,21 @@ func (c *S3) GetBucketCORS(input *GetBucketCORSInput) (*GetBucketCORSOutput, err return out, err } -var opGetBucketCORS *aws.Operation +const opGetBucketLifecycle = "GetBucketLifecycle" // GetBucketLifecycleRequest generates a request for the GetBucketLifecycle operation. func (c *S3) GetBucketLifecycleRequest(input *GetBucketLifecycleInput) (req *aws.Request, output *GetBucketLifecycleOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketLifecycle == nil { - opGetBucketLifecycle = &aws.Operation{ - Name: "GetBucketLifecycle", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?lifecycle", - } + op := &aws.Operation{ + Name: opGetBucketLifecycle, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?lifecycle", } if input == nil { input = &GetBucketLifecycleInput{} } - req = c.newRequest(opGetBucketLifecycle, input, output) + req = c.newRequest(op, input, output) output = &GetBucketLifecycleOutput{} req.Data = output return @@ -568,26 +482,21 @@ func (c *S3) GetBucketLifecycle(input *GetBucketLifecycleInput) (*GetBucketLifec return out, err } -var opGetBucketLifecycle *aws.Operation +const opGetBucketLocation = "GetBucketLocation" // GetBucketLocationRequest generates a request for the GetBucketLocation operation. func (c *S3) GetBucketLocationRequest(input *GetBucketLocationInput) (req *aws.Request, output *GetBucketLocationOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketLocation == nil { - opGetBucketLocation = &aws.Operation{ - Name: "GetBucketLocation", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?location", - } + op := &aws.Operation{ + Name: opGetBucketLocation, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?location", } if input == nil { input = &GetBucketLocationInput{} } - req = c.newRequest(opGetBucketLocation, input, output) + req = c.newRequest(op, input, output) output = &GetBucketLocationOutput{} req.Data = output return @@ -600,26 +509,21 @@ func (c *S3) GetBucketLocation(input *GetBucketLocationInput) (*GetBucketLocatio return out, err } -var opGetBucketLocation *aws.Operation +const opGetBucketLogging = "GetBucketLogging" // GetBucketLoggingRequest generates a request for the GetBucketLogging operation. func (c *S3) GetBucketLoggingRequest(input *GetBucketLoggingInput) (req *aws.Request, output *GetBucketLoggingOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketLogging == nil { - opGetBucketLogging = &aws.Operation{ - Name: "GetBucketLogging", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?logging", - } + op := &aws.Operation{ + Name: opGetBucketLogging, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?logging", } if input == nil { input = &GetBucketLoggingInput{} } - req = c.newRequest(opGetBucketLogging, input, output) + req = c.newRequest(op, input, output) output = &GetBucketLoggingOutput{} req.Data = output return @@ -633,26 +537,21 @@ func (c *S3) GetBucketLogging(input *GetBucketLoggingInput) (*GetBucketLoggingOu return out, err } -var opGetBucketLogging *aws.Operation +const opGetBucketNotification = "GetBucketNotification" // GetBucketNotificationRequest generates a request for the GetBucketNotification operation. func (c *S3) GetBucketNotificationRequest(input *GetBucketNotificationConfigurationRequest) (req *aws.Request, output *NotificationConfigurationDeprecated) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketNotification == nil { - opGetBucketNotification = &aws.Operation{ - Name: "GetBucketNotification", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?notification", - } + op := &aws.Operation{ + Name: opGetBucketNotification, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?notification", } if input == nil { input = &GetBucketNotificationConfigurationRequest{} } - req = c.newRequest(opGetBucketNotification, input, output) + req = c.newRequest(op, input, output) output = &NotificationConfigurationDeprecated{} req.Data = output return @@ -665,26 +564,21 @@ func (c *S3) GetBucketNotification(input *GetBucketNotificationConfigurationRequ return out, err } -var opGetBucketNotification *aws.Operation +const opGetBucketNotificationConfiguration = "GetBucketNotificationConfiguration" // GetBucketNotificationConfigurationRequest generates a request for the GetBucketNotificationConfiguration operation. func (c *S3) GetBucketNotificationConfigurationRequest(input *GetBucketNotificationConfigurationRequest) (req *aws.Request, output *NotificationConfiguration) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketNotificationConfiguration == nil { - opGetBucketNotificationConfiguration = &aws.Operation{ - Name: "GetBucketNotificationConfiguration", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?notification", - } + op := &aws.Operation{ + Name: opGetBucketNotificationConfiguration, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?notification", } if input == nil { input = &GetBucketNotificationConfigurationRequest{} } - req = c.newRequest(opGetBucketNotificationConfiguration, input, output) + req = c.newRequest(op, input, output) output = &NotificationConfiguration{} req.Data = output return @@ -697,26 +591,21 @@ func (c *S3) GetBucketNotificationConfiguration(input *GetBucketNotificationConf return out, err } -var opGetBucketNotificationConfiguration *aws.Operation +const opGetBucketPolicy = "GetBucketPolicy" // GetBucketPolicyRequest generates a request for the GetBucketPolicy operation. func (c *S3) GetBucketPolicyRequest(input *GetBucketPolicyInput) (req *aws.Request, output *GetBucketPolicyOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketPolicy == nil { - opGetBucketPolicy = &aws.Operation{ - Name: "GetBucketPolicy", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?policy", - } + op := &aws.Operation{ + Name: opGetBucketPolicy, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?policy", } if input == nil { input = &GetBucketPolicyInput{} } - req = c.newRequest(opGetBucketPolicy, input, output) + req = c.newRequest(op, input, output) output = &GetBucketPolicyOutput{} req.Data = output return @@ -729,26 +618,21 @@ func (c *S3) GetBucketPolicy(input *GetBucketPolicyInput) (*GetBucketPolicyOutpu return out, err } -var opGetBucketPolicy *aws.Operation +const opGetBucketReplication = "GetBucketReplication" // GetBucketReplicationRequest generates a request for the GetBucketReplication operation. func (c *S3) GetBucketReplicationRequest(input *GetBucketReplicationInput) (req *aws.Request, output *GetBucketReplicationOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketReplication == nil { - opGetBucketReplication = &aws.Operation{ - Name: "GetBucketReplication", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?replication", - } + op := &aws.Operation{ + Name: opGetBucketReplication, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?replication", } if input == nil { input = &GetBucketReplicationInput{} } - req = c.newRequest(opGetBucketReplication, input, output) + req = c.newRequest(op, input, output) output = &GetBucketReplicationOutput{} req.Data = output return @@ -760,26 +644,21 @@ func (c *S3) GetBucketReplication(input *GetBucketReplicationInput) (*GetBucketR return out, err } -var opGetBucketReplication *aws.Operation +const opGetBucketRequestPayment = "GetBucketRequestPayment" // GetBucketRequestPaymentRequest generates a request for the GetBucketRequestPayment operation. func (c *S3) GetBucketRequestPaymentRequest(input *GetBucketRequestPaymentInput) (req *aws.Request, output *GetBucketRequestPaymentOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketRequestPayment == nil { - opGetBucketRequestPayment = &aws.Operation{ - Name: "GetBucketRequestPayment", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?requestPayment", - } + op := &aws.Operation{ + Name: opGetBucketRequestPayment, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?requestPayment", } if input == nil { input = &GetBucketRequestPaymentInput{} } - req = c.newRequest(opGetBucketRequestPayment, input, output) + req = c.newRequest(op, input, output) output = &GetBucketRequestPaymentOutput{} req.Data = output return @@ -792,26 +671,21 @@ func (c *S3) GetBucketRequestPayment(input *GetBucketRequestPaymentInput) (*GetB return out, err } -var opGetBucketRequestPayment *aws.Operation +const opGetBucketTagging = "GetBucketTagging" // GetBucketTaggingRequest generates a request for the GetBucketTagging operation. func (c *S3) GetBucketTaggingRequest(input *GetBucketTaggingInput) (req *aws.Request, output *GetBucketTaggingOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketTagging == nil { - opGetBucketTagging = &aws.Operation{ - Name: "GetBucketTagging", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?tagging", - } + op := &aws.Operation{ + Name: opGetBucketTagging, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?tagging", } if input == nil { input = &GetBucketTaggingInput{} } - req = c.newRequest(opGetBucketTagging, input, output) + req = c.newRequest(op, input, output) output = &GetBucketTaggingOutput{} req.Data = output return @@ -824,26 +698,21 @@ func (c *S3) GetBucketTagging(input *GetBucketTaggingInput) (*GetBucketTaggingOu return out, err } -var opGetBucketTagging *aws.Operation +const opGetBucketVersioning = "GetBucketVersioning" // GetBucketVersioningRequest generates a request for the GetBucketVersioning operation. func (c *S3) GetBucketVersioningRequest(input *GetBucketVersioningInput) (req *aws.Request, output *GetBucketVersioningOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketVersioning == nil { - opGetBucketVersioning = &aws.Operation{ - Name: "GetBucketVersioning", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?versioning", - } + op := &aws.Operation{ + Name: opGetBucketVersioning, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?versioning", } if input == nil { input = &GetBucketVersioningInput{} } - req = c.newRequest(opGetBucketVersioning, input, output) + req = c.newRequest(op, input, output) output = &GetBucketVersioningOutput{} req.Data = output return @@ -856,26 +725,21 @@ func (c *S3) GetBucketVersioning(input *GetBucketVersioningInput) (*GetBucketVer return out, err } -var opGetBucketVersioning *aws.Operation +const opGetBucketWebsite = "GetBucketWebsite" // GetBucketWebsiteRequest generates a request for the GetBucketWebsite operation. func (c *S3) GetBucketWebsiteRequest(input *GetBucketWebsiteInput) (req *aws.Request, output *GetBucketWebsiteOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetBucketWebsite == nil { - opGetBucketWebsite = &aws.Operation{ - Name: "GetBucketWebsite", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?website", - } + op := &aws.Operation{ + Name: opGetBucketWebsite, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?website", } if input == nil { input = &GetBucketWebsiteInput{} } - req = c.newRequest(opGetBucketWebsite, input, output) + req = c.newRequest(op, input, output) output = &GetBucketWebsiteOutput{} req.Data = output return @@ -888,26 +752,21 @@ func (c *S3) GetBucketWebsite(input *GetBucketWebsiteInput) (*GetBucketWebsiteOu return out, err } -var opGetBucketWebsite *aws.Operation +const opGetObject = "GetObject" // GetObjectRequest generates a request for the GetObject operation. func (c *S3) GetObjectRequest(input *GetObjectInput) (req *aws.Request, output *GetObjectOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetObject == nil { - opGetObject = &aws.Operation{ - Name: "GetObject", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}", - } + op := &aws.Operation{ + Name: opGetObject, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}/{Key+}", } if input == nil { input = &GetObjectInput{} } - req = c.newRequest(opGetObject, input, output) + req = c.newRequest(op, input, output) output = &GetObjectOutput{} req.Data = output return @@ -920,26 +779,21 @@ func (c *S3) GetObject(input *GetObjectInput) (*GetObjectOutput, error) { return out, err } -var opGetObject *aws.Operation +const opGetObjectACL = "GetObjectAcl" // GetObjectACLRequest generates a request for the GetObjectACL operation. func (c *S3) GetObjectACLRequest(input *GetObjectACLInput) (req *aws.Request, output *GetObjectACLOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetObjectACL == nil { - opGetObjectACL = &aws.Operation{ - Name: "GetObjectAcl", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}?acl", - } + op := &aws.Operation{ + Name: opGetObjectACL, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}/{Key+}?acl", } if input == nil { input = &GetObjectACLInput{} } - req = c.newRequest(opGetObjectACL, input, output) + req = c.newRequest(op, input, output) output = &GetObjectACLOutput{} req.Data = output return @@ -952,26 +806,21 @@ func (c *S3) GetObjectACL(input *GetObjectACLInput) (*GetObjectACLOutput, error) return out, err } -var opGetObjectACL *aws.Operation +const opGetObjectTorrent = "GetObjectTorrent" // GetObjectTorrentRequest generates a request for the GetObjectTorrent operation. func (c *S3) GetObjectTorrentRequest(input *GetObjectTorrentInput) (req *aws.Request, output *GetObjectTorrentOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opGetObjectTorrent == nil { - opGetObjectTorrent = &aws.Operation{ - Name: "GetObjectTorrent", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}?torrent", - } + op := &aws.Operation{ + Name: opGetObjectTorrent, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}/{Key+}?torrent", } if input == nil { input = &GetObjectTorrentInput{} } - req = c.newRequest(opGetObjectTorrent, input, output) + req = c.newRequest(op, input, output) output = &GetObjectTorrentOutput{} req.Data = output return @@ -984,26 +833,21 @@ func (c *S3) GetObjectTorrent(input *GetObjectTorrentInput) (*GetObjectTorrentOu return out, err } -var opGetObjectTorrent *aws.Operation +const opHeadBucket = "HeadBucket" // HeadBucketRequest generates a request for the HeadBucket operation. func (c *S3) HeadBucketRequest(input *HeadBucketInput) (req *aws.Request, output *HeadBucketOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opHeadBucket == nil { - opHeadBucket = &aws.Operation{ - Name: "HeadBucket", - HTTPMethod: "HEAD", - HTTPPath: "/{Bucket}", - } + op := &aws.Operation{ + Name: opHeadBucket, + HTTPMethod: "HEAD", + HTTPPath: "/{Bucket}", } if input == nil { input = &HeadBucketInput{} } - req = c.newRequest(opHeadBucket, input, output) + req = c.newRequest(op, input, output) output = &HeadBucketOutput{} req.Data = output return @@ -1017,26 +861,21 @@ func (c *S3) HeadBucket(input *HeadBucketInput) (*HeadBucketOutput, error) { return out, err } -var opHeadBucket *aws.Operation +const opHeadObject = "HeadObject" // HeadObjectRequest generates a request for the HeadObject operation. func (c *S3) HeadObjectRequest(input *HeadObjectInput) (req *aws.Request, output *HeadObjectOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opHeadObject == nil { - opHeadObject = &aws.Operation{ - Name: "HeadObject", - HTTPMethod: "HEAD", - HTTPPath: "/{Bucket}/{Key+}", - } + op := &aws.Operation{ + Name: opHeadObject, + HTTPMethod: "HEAD", + HTTPPath: "/{Bucket}/{Key+}", } if input == nil { input = &HeadObjectInput{} } - req = c.newRequest(opHeadObject, input, output) + req = c.newRequest(op, input, output) output = &HeadObjectOutput{} req.Data = output return @@ -1051,26 +890,21 @@ func (c *S3) HeadObject(input *HeadObjectInput) (*HeadObjectOutput, error) { return out, err } -var opHeadObject *aws.Operation +const opListBuckets = "ListBuckets" // ListBucketsRequest generates a request for the ListBuckets operation. func (c *S3) ListBucketsRequest(input *ListBucketsInput) (req *aws.Request, output *ListBucketsOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opListBuckets == nil { - opListBuckets = &aws.Operation{ - Name: "ListBuckets", - HTTPMethod: "GET", - HTTPPath: "/", - } + op := &aws.Operation{ + Name: opListBuckets, + HTTPMethod: "GET", + HTTPPath: "/", } if input == nil { input = &ListBucketsInput{} } - req = c.newRequest(opListBuckets, input, output) + req = c.newRequest(op, input, output) output = &ListBucketsOutput{} req.Data = output return @@ -1083,32 +917,27 @@ func (c *S3) ListBuckets(input *ListBucketsInput) (*ListBucketsOutput, error) { return out, err } -var opListBuckets *aws.Operation +const opListMultipartUploads = "ListMultipartUploads" // ListMultipartUploadsRequest generates a request for the ListMultipartUploads operation. func (c *S3) ListMultipartUploadsRequest(input *ListMultipartUploadsInput) (req *aws.Request, output *ListMultipartUploadsOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opListMultipartUploads == nil { - opListMultipartUploads = &aws.Operation{ - Name: "ListMultipartUploads", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?uploads", - Paginator: &aws.Paginator{ - InputTokens: []string{"KeyMarker", "UploadIdMarker"}, - OutputTokens: []string{"NextKeyMarker", "NextUploadIdMarker"}, - LimitToken: "MaxUploads", - TruncationToken: "IsTruncated", - }, - } + op := &aws.Operation{ + Name: opListMultipartUploads, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?uploads", + Paginator: &aws.Paginator{ + InputTokens: []string{"KeyMarker", "UploadIdMarker"}, + OutputTokens: []string{"NextKeyMarker", "NextUploadIdMarker"}, + LimitToken: "MaxUploads", + TruncationToken: "IsTruncated", + }, } if input == nil { input = &ListMultipartUploadsInput{} } - req = c.newRequest(opListMultipartUploads, input, output) + req = c.newRequest(op, input, output) output = &ListMultipartUploadsOutput{} req.Data = output return @@ -1128,32 +957,27 @@ func (c *S3) ListMultipartUploadsPages(input *ListMultipartUploadsInput, fn func }) } -var opListMultipartUploads *aws.Operation +const opListObjectVersions = "ListObjectVersions" // ListObjectVersionsRequest generates a request for the ListObjectVersions operation. func (c *S3) ListObjectVersionsRequest(input *ListObjectVersionsInput) (req *aws.Request, output *ListObjectVersionsOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opListObjectVersions == nil { - opListObjectVersions = &aws.Operation{ - Name: "ListObjectVersions", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}?versions", - Paginator: &aws.Paginator{ - InputTokens: []string{"KeyMarker", "VersionIdMarker"}, - OutputTokens: []string{"NextKeyMarker", "NextVersionIdMarker"}, - LimitToken: "MaxKeys", - TruncationToken: "IsTruncated", - }, - } + op := &aws.Operation{ + Name: opListObjectVersions, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}?versions", + Paginator: &aws.Paginator{ + InputTokens: []string{"KeyMarker", "VersionIdMarker"}, + OutputTokens: []string{"NextKeyMarker", "NextVersionIdMarker"}, + LimitToken: "MaxKeys", + TruncationToken: "IsTruncated", + }, } if input == nil { input = &ListObjectVersionsInput{} } - req = c.newRequest(opListObjectVersions, input, output) + req = c.newRequest(op, input, output) output = &ListObjectVersionsOutput{} req.Data = output return @@ -1173,32 +997,27 @@ func (c *S3) ListObjectVersionsPages(input *ListObjectVersionsInput, fn func(p * }) } -var opListObjectVersions *aws.Operation +const opListObjects = "ListObjects" // ListObjectsRequest generates a request for the ListObjects operation. func (c *S3) ListObjectsRequest(input *ListObjectsInput) (req *aws.Request, output *ListObjectsOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opListObjects == nil { - opListObjects = &aws.Operation{ - Name: "ListObjects", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}", - Paginator: &aws.Paginator{ - InputTokens: []string{"Marker"}, - OutputTokens: []string{"NextMarker || Contents[-1].Key"}, - LimitToken: "MaxKeys", - TruncationToken: "IsTruncated", - }, - } + op := &aws.Operation{ + Name: opListObjects, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}", + Paginator: &aws.Paginator{ + InputTokens: []string{"Marker"}, + OutputTokens: []string{"NextMarker || Contents[-1].Key"}, + LimitToken: "MaxKeys", + TruncationToken: "IsTruncated", + }, } if input == nil { input = &ListObjectsInput{} } - req = c.newRequest(opListObjects, input, output) + req = c.newRequest(op, input, output) output = &ListObjectsOutput{} req.Data = output return @@ -1220,32 +1039,27 @@ func (c *S3) ListObjectsPages(input *ListObjectsInput, fn func(p *ListObjectsOut }) } -var opListObjects *aws.Operation +const opListParts = "ListParts" // ListPartsRequest generates a request for the ListParts operation. func (c *S3) ListPartsRequest(input *ListPartsInput) (req *aws.Request, output *ListPartsOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opListParts == nil { - opListParts = &aws.Operation{ - Name: "ListParts", - HTTPMethod: "GET", - HTTPPath: "/{Bucket}/{Key+}", - Paginator: &aws.Paginator{ - InputTokens: []string{"PartNumberMarker"}, - OutputTokens: []string{"NextPartNumberMarker"}, - LimitToken: "MaxParts", - TruncationToken: "IsTruncated", - }, - } + op := &aws.Operation{ + Name: opListParts, + HTTPMethod: "GET", + HTTPPath: "/{Bucket}/{Key+}", + Paginator: &aws.Paginator{ + InputTokens: []string{"PartNumberMarker"}, + OutputTokens: []string{"NextPartNumberMarker"}, + LimitToken: "MaxParts", + TruncationToken: "IsTruncated", + }, } if input == nil { input = &ListPartsInput{} } - req = c.newRequest(opListParts, input, output) + req = c.newRequest(op, input, output) output = &ListPartsOutput{} req.Data = output return @@ -1265,26 +1079,21 @@ func (c *S3) ListPartsPages(input *ListPartsInput, fn func(p *ListPartsOutput, l }) } -var opListParts *aws.Operation +const opPutBucketACL = "PutBucketAcl" // PutBucketACLRequest generates a request for the PutBucketACL operation. func (c *S3) PutBucketACLRequest(input *PutBucketACLInput) (req *aws.Request, output *PutBucketACLOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketACL == nil { - opPutBucketACL = &aws.Operation{ - Name: "PutBucketAcl", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?acl", - } + op := &aws.Operation{ + Name: opPutBucketACL, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?acl", } if input == nil { input = &PutBucketACLInput{} } - req = c.newRequest(opPutBucketACL, input, output) + req = c.newRequest(op, input, output) output = &PutBucketACLOutput{} req.Data = output return @@ -1297,26 +1106,21 @@ func (c *S3) PutBucketACL(input *PutBucketACLInput) (*PutBucketACLOutput, error) return out, err } -var opPutBucketACL *aws.Operation +const opPutBucketCORS = "PutBucketCors" // PutBucketCORSRequest generates a request for the PutBucketCORS operation. func (c *S3) PutBucketCORSRequest(input *PutBucketCORSInput) (req *aws.Request, output *PutBucketCORSOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketCORS == nil { - opPutBucketCORS = &aws.Operation{ - Name: "PutBucketCors", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?cors", - } + op := &aws.Operation{ + Name: opPutBucketCORS, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?cors", } if input == nil { input = &PutBucketCORSInput{} } - req = c.newRequest(opPutBucketCORS, input, output) + req = c.newRequest(op, input, output) output = &PutBucketCORSOutput{} req.Data = output return @@ -1329,26 +1133,21 @@ func (c *S3) PutBucketCORS(input *PutBucketCORSInput) (*PutBucketCORSOutput, err return out, err } -var opPutBucketCORS *aws.Operation +const opPutBucketLifecycle = "PutBucketLifecycle" // PutBucketLifecycleRequest generates a request for the PutBucketLifecycle operation. func (c *S3) PutBucketLifecycleRequest(input *PutBucketLifecycleInput) (req *aws.Request, output *PutBucketLifecycleOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketLifecycle == nil { - opPutBucketLifecycle = &aws.Operation{ - Name: "PutBucketLifecycle", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?lifecycle", - } + op := &aws.Operation{ + Name: opPutBucketLifecycle, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?lifecycle", } if input == nil { input = &PutBucketLifecycleInput{} } - req = c.newRequest(opPutBucketLifecycle, input, output) + req = c.newRequest(op, input, output) output = &PutBucketLifecycleOutput{} req.Data = output return @@ -1362,26 +1161,21 @@ func (c *S3) PutBucketLifecycle(input *PutBucketLifecycleInput) (*PutBucketLifec return out, err } -var opPutBucketLifecycle *aws.Operation +const opPutBucketLogging = "PutBucketLogging" // PutBucketLoggingRequest generates a request for the PutBucketLogging operation. func (c *S3) PutBucketLoggingRequest(input *PutBucketLoggingInput) (req *aws.Request, output *PutBucketLoggingOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketLogging == nil { - opPutBucketLogging = &aws.Operation{ - Name: "PutBucketLogging", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?logging", - } + op := &aws.Operation{ + Name: opPutBucketLogging, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?logging", } if input == nil { input = &PutBucketLoggingInput{} } - req = c.newRequest(opPutBucketLogging, input, output) + req = c.newRequest(op, input, output) output = &PutBucketLoggingOutput{} req.Data = output return @@ -1396,26 +1190,21 @@ func (c *S3) PutBucketLogging(input *PutBucketLoggingInput) (*PutBucketLoggingOu return out, err } -var opPutBucketLogging *aws.Operation +const opPutBucketNotification = "PutBucketNotification" // PutBucketNotificationRequest generates a request for the PutBucketNotification operation. func (c *S3) PutBucketNotificationRequest(input *PutBucketNotificationInput) (req *aws.Request, output *PutBucketNotificationOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketNotification == nil { - opPutBucketNotification = &aws.Operation{ - Name: "PutBucketNotification", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?notification", - } + op := &aws.Operation{ + Name: opPutBucketNotification, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?notification", } if input == nil { input = &PutBucketNotificationInput{} } - req = c.newRequest(opPutBucketNotification, input, output) + req = c.newRequest(op, input, output) output = &PutBucketNotificationOutput{} req.Data = output return @@ -1428,26 +1217,21 @@ func (c *S3) PutBucketNotification(input *PutBucketNotificationInput) (*PutBucke return out, err } -var opPutBucketNotification *aws.Operation +const opPutBucketNotificationConfiguration = "PutBucketNotificationConfiguration" // PutBucketNotificationConfigurationRequest generates a request for the PutBucketNotificationConfiguration operation. func (c *S3) PutBucketNotificationConfigurationRequest(input *PutBucketNotificationConfigurationInput) (req *aws.Request, output *PutBucketNotificationConfigurationOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketNotificationConfiguration == nil { - opPutBucketNotificationConfiguration = &aws.Operation{ - Name: "PutBucketNotificationConfiguration", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?notification", - } + op := &aws.Operation{ + Name: opPutBucketNotificationConfiguration, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?notification", } if input == nil { input = &PutBucketNotificationConfigurationInput{} } - req = c.newRequest(opPutBucketNotificationConfiguration, input, output) + req = c.newRequest(op, input, output) output = &PutBucketNotificationConfigurationOutput{} req.Data = output return @@ -1460,26 +1244,21 @@ func (c *S3) PutBucketNotificationConfiguration(input *PutBucketNotificationConf return out, err } -var opPutBucketNotificationConfiguration *aws.Operation +const opPutBucketPolicy = "PutBucketPolicy" // PutBucketPolicyRequest generates a request for the PutBucketPolicy operation. func (c *S3) PutBucketPolicyRequest(input *PutBucketPolicyInput) (req *aws.Request, output *PutBucketPolicyOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketPolicy == nil { - opPutBucketPolicy = &aws.Operation{ - Name: "PutBucketPolicy", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?policy", - } + op := &aws.Operation{ + Name: opPutBucketPolicy, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?policy", } if input == nil { input = &PutBucketPolicyInput{} } - req = c.newRequest(opPutBucketPolicy, input, output) + req = c.newRequest(op, input, output) output = &PutBucketPolicyOutput{} req.Data = output return @@ -1493,26 +1272,21 @@ func (c *S3) PutBucketPolicy(input *PutBucketPolicyInput) (*PutBucketPolicyOutpu return out, err } -var opPutBucketPolicy *aws.Operation +const opPutBucketReplication = "PutBucketReplication" // PutBucketReplicationRequest generates a request for the PutBucketReplication operation. func (c *S3) PutBucketReplicationRequest(input *PutBucketReplicationInput) (req *aws.Request, output *PutBucketReplicationOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketReplication == nil { - opPutBucketReplication = &aws.Operation{ - Name: "PutBucketReplication", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?replication", - } + op := &aws.Operation{ + Name: opPutBucketReplication, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?replication", } if input == nil { input = &PutBucketReplicationInput{} } - req = c.newRequest(opPutBucketReplication, input, output) + req = c.newRequest(op, input, output) output = &PutBucketReplicationOutput{} req.Data = output return @@ -1526,26 +1300,21 @@ func (c *S3) PutBucketReplication(input *PutBucketReplicationInput) (*PutBucketR return out, err } -var opPutBucketReplication *aws.Operation +const opPutBucketRequestPayment = "PutBucketRequestPayment" // PutBucketRequestPaymentRequest generates a request for the PutBucketRequestPayment operation. func (c *S3) PutBucketRequestPaymentRequest(input *PutBucketRequestPaymentInput) (req *aws.Request, output *PutBucketRequestPaymentOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketRequestPayment == nil { - opPutBucketRequestPayment = &aws.Operation{ - Name: "PutBucketRequestPayment", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?requestPayment", - } + op := &aws.Operation{ + Name: opPutBucketRequestPayment, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?requestPayment", } if input == nil { input = &PutBucketRequestPaymentInput{} } - req = c.newRequest(opPutBucketRequestPayment, input, output) + req = c.newRequest(op, input, output) output = &PutBucketRequestPaymentOutput{} req.Data = output return @@ -1562,26 +1331,21 @@ func (c *S3) PutBucketRequestPayment(input *PutBucketRequestPaymentInput) (*PutB return out, err } -var opPutBucketRequestPayment *aws.Operation +const opPutBucketTagging = "PutBucketTagging" // PutBucketTaggingRequest generates a request for the PutBucketTagging operation. func (c *S3) PutBucketTaggingRequest(input *PutBucketTaggingInput) (req *aws.Request, output *PutBucketTaggingOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketTagging == nil { - opPutBucketTagging = &aws.Operation{ - Name: "PutBucketTagging", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?tagging", - } + op := &aws.Operation{ + Name: opPutBucketTagging, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?tagging", } if input == nil { input = &PutBucketTaggingInput{} } - req = c.newRequest(opPutBucketTagging, input, output) + req = c.newRequest(op, input, output) output = &PutBucketTaggingOutput{} req.Data = output return @@ -1594,26 +1358,21 @@ func (c *S3) PutBucketTagging(input *PutBucketTaggingInput) (*PutBucketTaggingOu return out, err } -var opPutBucketTagging *aws.Operation +const opPutBucketVersioning = "PutBucketVersioning" // PutBucketVersioningRequest generates a request for the PutBucketVersioning operation. func (c *S3) PutBucketVersioningRequest(input *PutBucketVersioningInput) (req *aws.Request, output *PutBucketVersioningOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketVersioning == nil { - opPutBucketVersioning = &aws.Operation{ - Name: "PutBucketVersioning", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?versioning", - } + op := &aws.Operation{ + Name: opPutBucketVersioning, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?versioning", } if input == nil { input = &PutBucketVersioningInput{} } - req = c.newRequest(opPutBucketVersioning, input, output) + req = c.newRequest(op, input, output) output = &PutBucketVersioningOutput{} req.Data = output return @@ -1627,26 +1386,21 @@ func (c *S3) PutBucketVersioning(input *PutBucketVersioningInput) (*PutBucketVer return out, err } -var opPutBucketVersioning *aws.Operation +const opPutBucketWebsite = "PutBucketWebsite" // PutBucketWebsiteRequest generates a request for the PutBucketWebsite operation. func (c *S3) PutBucketWebsiteRequest(input *PutBucketWebsiteInput) (req *aws.Request, output *PutBucketWebsiteOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutBucketWebsite == nil { - opPutBucketWebsite = &aws.Operation{ - Name: "PutBucketWebsite", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}?website", - } + op := &aws.Operation{ + Name: opPutBucketWebsite, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}?website", } if input == nil { input = &PutBucketWebsiteInput{} } - req = c.newRequest(opPutBucketWebsite, input, output) + req = c.newRequest(op, input, output) output = &PutBucketWebsiteOutput{} req.Data = output return @@ -1659,26 +1413,21 @@ func (c *S3) PutBucketWebsite(input *PutBucketWebsiteInput) (*PutBucketWebsiteOu return out, err } -var opPutBucketWebsite *aws.Operation +const opPutObject = "PutObject" // PutObjectRequest generates a request for the PutObject operation. func (c *S3) PutObjectRequest(input *PutObjectInput) (req *aws.Request, output *PutObjectOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutObject == nil { - opPutObject = &aws.Operation{ - Name: "PutObject", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", - } + op := &aws.Operation{ + Name: opPutObject, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}/{Key+}", } if input == nil { input = &PutObjectInput{} } - req = c.newRequest(opPutObject, input, output) + req = c.newRequest(op, input, output) output = &PutObjectOutput{} req.Data = output return @@ -1691,26 +1440,21 @@ func (c *S3) PutObject(input *PutObjectInput) (*PutObjectOutput, error) { return out, err } -var opPutObject *aws.Operation +const opPutObjectACL = "PutObjectAcl" // PutObjectACLRequest generates a request for the PutObjectACL operation. func (c *S3) PutObjectACLRequest(input *PutObjectACLInput) (req *aws.Request, output *PutObjectACLOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opPutObjectACL == nil { - opPutObjectACL = &aws.Operation{ - Name: "PutObjectAcl", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}?acl", - } + op := &aws.Operation{ + Name: opPutObjectACL, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}/{Key+}?acl", } if input == nil { input = &PutObjectACLInput{} } - req = c.newRequest(opPutObjectACL, input, output) + req = c.newRequest(op, input, output) output = &PutObjectACLOutput{} req.Data = output return @@ -1724,26 +1468,21 @@ func (c *S3) PutObjectACL(input *PutObjectACLInput) (*PutObjectACLOutput, error) return out, err } -var opPutObjectACL *aws.Operation +const opRestoreObject = "RestoreObject" // RestoreObjectRequest generates a request for the RestoreObject operation. func (c *S3) RestoreObjectRequest(input *RestoreObjectInput) (req *aws.Request, output *RestoreObjectOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opRestoreObject == nil { - opRestoreObject = &aws.Operation{ - Name: "RestoreObject", - HTTPMethod: "POST", - HTTPPath: "/{Bucket}/{Key+}?restore", - } + op := &aws.Operation{ + Name: opRestoreObject, + HTTPMethod: "POST", + HTTPPath: "/{Bucket}/{Key+}?restore", } if input == nil { input = &RestoreObjectInput{} } - req = c.newRequest(opRestoreObject, input, output) + req = c.newRequest(op, input, output) output = &RestoreObjectOutput{} req.Data = output return @@ -1756,26 +1495,21 @@ func (c *S3) RestoreObject(input *RestoreObjectInput) (*RestoreObjectOutput, err return out, err } -var opRestoreObject *aws.Operation +const opUploadPart = "UploadPart" // UploadPartRequest generates a request for the UploadPart operation. func (c *S3) UploadPartRequest(input *UploadPartInput) (req *aws.Request, output *UploadPartOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opUploadPart == nil { - opUploadPart = &aws.Operation{ - Name: "UploadPart", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", - } + op := &aws.Operation{ + Name: opUploadPart, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}/{Key+}", } if input == nil { input = &UploadPartInput{} } - req = c.newRequest(opUploadPart, input, output) + req = c.newRequest(op, input, output) output = &UploadPartOutput{} req.Data = output return @@ -1794,26 +1528,21 @@ func (c *S3) UploadPart(input *UploadPartInput) (*UploadPartOutput, error) { return out, err } -var opUploadPart *aws.Operation +const opUploadPartCopy = "UploadPartCopy" // UploadPartCopyRequest generates a request for the UploadPartCopy operation. func (c *S3) UploadPartCopyRequest(input *UploadPartCopyInput) (req *aws.Request, output *UploadPartCopyOutput) { - oprw.Lock() - defer oprw.Unlock() - - if opUploadPartCopy == nil { - opUploadPartCopy = &aws.Operation{ - Name: "UploadPartCopy", - HTTPMethod: "PUT", - HTTPPath: "/{Bucket}/{Key+}", - } + op := &aws.Operation{ + Name: opUploadPartCopy, + HTTPMethod: "PUT", + HTTPPath: "/{Bucket}/{Key+}", } if input == nil { input = &UploadPartCopyInput{} } - req = c.newRequest(opUploadPartCopy, input, output) + req = c.newRequest(op, input, output) output = &UploadPartCopyOutput{} req.Data = output return @@ -1826,8 +1555,6 @@ func (c *S3) UploadPartCopy(input *UploadPartCopyInput) (*UploadPartCopyOutput, return out, err } -var opUploadPartCopy *aws.Operation - type AbortMultipartUploadInput struct { Bucket *string `location:"uri" locationName:"Bucket" type:"string" required:"true"` diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/bucket_location.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/bucket_location.go index 8cc0dedea..59eb84524 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/bucket_location.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/bucket_location.go @@ -5,8 +5,8 @@ import ( "regexp" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/internal/apierr" ) var reBucketLocation = regexp.MustCompile(`>([^<>]+)<\/Location`) @@ -16,7 +16,7 @@ func buildGetBucketLocation(r *aws.Request) { out := r.Data.(*GetBucketLocationOutput) b, err := ioutil.ReadAll(r.HTTPResponse.Body) if err != nil { - r.Error = apierr.New("Unmarshal", "failed reading response body", err) + r.Error = awserr.New("SerializationError", "failed reading response body", err) return } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/content_md5.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/content_md5.go index 25e9a8aae..386f09a3f 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/content_md5.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/content_md5.go @@ -6,7 +6,7 @@ import ( "io" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" ) // contentMD5 computes and sets the HTTP Content-MD5 header for requests that @@ -19,12 +19,12 @@ func contentMD5(r *aws.Request) { // body. _, err := io.Copy(h, r.Body) if err != nil { - r.Error = apierr.New("ContentMD5", "failed to read body", err) + r.Error = awserr.New("ContentMD5", "failed to read body", err) return } _, err = r.Body.Seek(0, 0) if err != nil { - r.Error = apierr.New("ContentMD5", "failed to seek body", err) + r.Error = awserr.New("ContentMD5", "failed to seek body", err) return } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations.go index de12c8f00..490ff2d8a 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations.go @@ -17,7 +17,7 @@ func init() { } initRequest = func(r *aws.Request) { - switch r.Operation { + switch r.Operation.Name { case opPutBucketCORS, opPutBucketLifecycle, opPutBucketPolicy, opPutBucketTagging, opDeleteObjects: // These S3 operations require Content-MD5 to be set r.Handlers.Build.PushBack(contentMD5) diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations_test.go index 2096f9104..523b4870e 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/customizations_test.go @@ -30,7 +30,7 @@ func TestMD5InPutBucketCORS(t *testing.T) { Bucket: aws.String("bucketname"), CORSConfiguration: &s3.CORSConfiguration{ CORSRules: []*s3.CORSRule{ - &s3.CORSRule{AllowedMethods: []*string{aws.String("GET")}}, + {AllowedMethods: []*string{aws.String("GET")}}, }, }, }) @@ -43,7 +43,7 @@ func TestMD5InPutBucketLifecycle(t *testing.T) { Bucket: aws.String("bucketname"), LifecycleConfiguration: &s3.LifecycleConfiguration{ Rules: []*s3.LifecycleRule{ - &s3.LifecycleRule{ + { ID: aws.String("ID"), Prefix: aws.String("Prefix"), Status: aws.String("Enabled"), @@ -69,7 +69,7 @@ func TestMD5InPutBucketTagging(t *testing.T) { Bucket: aws.String("bucketname"), Tagging: &s3.Tagging{ TagSet: []*s3.Tag{ - &s3.Tag{Key: aws.String("KEY"), Value: aws.String("VALUE")}, + {Key: aws.String("KEY"), Value: aws.String("VALUE")}, }, }, }) @@ -82,7 +82,7 @@ func TestMD5InDeleteObjects(t *testing.T) { Bucket: aws.String("bucketname"), Delete: &s3.Delete{ Objects: []*s3.ObjectIdentifier{ - &s3.ObjectIdentifier{Key: aws.String("key")}, + {Key: aws.String("key")}, }, }, }) diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/examples_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/examples_test.go index 6ea0e769c..7dde748c8 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/examples_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/examples_test.go @@ -36,7 +36,7 @@ func ExampleS3_AbortMultipartUpload() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -55,7 +55,7 @@ func ExampleS3_CompleteMultipartUpload() { UploadID: aws.String("MultipartUploadId"), // Required MultipartUpload: &s3.CompletedMultipartUpload{ Parts: []*s3.CompletedPart{ - &s3.CompletedPart{ // Required + { // Required ETag: aws.String("ETag"), PartNumber: aws.Long(1), }, @@ -75,7 +75,7 @@ func ExampleS3_CompleteMultipartUpload() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -135,7 +135,7 @@ func ExampleS3_CopyObject() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -171,7 +171,7 @@ func ExampleS3_CreateBucket() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -222,7 +222,7 @@ func ExampleS3_CreateMultipartUpload() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -249,7 +249,7 @@ func ExampleS3_DeleteBucket() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -276,7 +276,7 @@ func ExampleS3_DeleteBucketCORS() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -303,7 +303,7 @@ func ExampleS3_DeleteBucketLifecycle() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -330,7 +330,7 @@ func ExampleS3_DeleteBucketPolicy() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -357,7 +357,7 @@ func ExampleS3_DeleteBucketReplication() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -384,7 +384,7 @@ func ExampleS3_DeleteBucketTagging() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -411,7 +411,7 @@ func ExampleS3_DeleteBucketWebsite() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -442,7 +442,7 @@ func ExampleS3_DeleteObject() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -459,7 +459,7 @@ func ExampleS3_DeleteObjects() { Bucket: aws.String("BucketName"), // Required Delete: &s3.Delete{ // Required Objects: []*s3.ObjectIdentifier{ // Required - &s3.ObjectIdentifier{ // Required + { // Required Key: aws.String("ObjectKey"), // Required VersionID: aws.String("ObjectVersionId"), }, @@ -481,7 +481,7 @@ func ExampleS3_DeleteObjects() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -508,7 +508,7 @@ func ExampleS3_GetBucketACL() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -535,7 +535,7 @@ func ExampleS3_GetBucketCORS() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -562,7 +562,7 @@ func ExampleS3_GetBucketLifecycle() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -589,7 +589,7 @@ func ExampleS3_GetBucketLocation() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -616,7 +616,7 @@ func ExampleS3_GetBucketLogging() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -643,7 +643,7 @@ func ExampleS3_GetBucketNotification() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -670,7 +670,7 @@ func ExampleS3_GetBucketNotificationConfiguration() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -697,7 +697,7 @@ func ExampleS3_GetBucketPolicy() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -724,7 +724,7 @@ func ExampleS3_GetBucketReplication() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -751,7 +751,7 @@ func ExampleS3_GetBucketRequestPayment() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -778,7 +778,7 @@ func ExampleS3_GetBucketTagging() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -805,7 +805,7 @@ func ExampleS3_GetBucketVersioning() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -832,7 +832,7 @@ func ExampleS3_GetBucketWebsite() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -876,7 +876,7 @@ func ExampleS3_GetObject() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -906,7 +906,7 @@ func ExampleS3_GetObjectACL() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -935,7 +935,7 @@ func ExampleS3_GetObjectTorrent() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -962,7 +962,7 @@ func ExampleS3_HeadBucket() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1000,7 +1000,7 @@ func ExampleS3_HeadObject() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1025,7 +1025,7 @@ func ExampleS3_ListBuckets() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1058,7 +1058,7 @@ func ExampleS3_ListMultipartUploads() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1091,7 +1091,7 @@ func ExampleS3_ListObjectVersions() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1123,7 +1123,7 @@ func ExampleS3_ListObjects() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1155,7 +1155,7 @@ func ExampleS3_ListParts() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1173,7 +1173,7 @@ func ExampleS3_PutBucketACL() { ACL: aws.String("BucketCannedACL"), AccessControlPolicy: &s3.AccessControlPolicy{ Grants: []*s3.Grant{ - &s3.Grant{ // Required + { // Required Grantee: &s3.Grantee{ Type: aws.String("Type"), // Required DisplayName: aws.String("DisplayName"), @@ -1207,7 +1207,7 @@ func ExampleS3_PutBucketACL() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1224,7 +1224,7 @@ func ExampleS3_PutBucketCORS() { Bucket: aws.String("BucketName"), // Required CORSConfiguration: &s3.CORSConfiguration{ CORSRules: []*s3.CORSRule{ - &s3.CORSRule{ // Required + { // Required AllowedHeaders: []*string{ aws.String("AllowedHeader"), // Required // More values... @@ -1258,7 +1258,7 @@ func ExampleS3_PutBucketCORS() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1275,7 +1275,7 @@ func ExampleS3_PutBucketLifecycle() { Bucket: aws.String("BucketName"), // Required LifecycleConfiguration: &s3.LifecycleConfiguration{ Rules: []*s3.LifecycleRule{ // Required - &s3.LifecycleRule{ // Required + { // Required Prefix: aws.String("Prefix"), // Required Status: aws.String("ExpirationStatus"), // Required Expiration: &s3.LifecycleExpiration{ @@ -1311,7 +1311,7 @@ func ExampleS3_PutBucketLifecycle() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1330,7 +1330,7 @@ func ExampleS3_PutBucketLogging() { LoggingEnabled: &s3.LoggingEnabled{ TargetBucket: aws.String("TargetBucket"), TargetGrants: []*s3.TargetGrant{ - &s3.TargetGrant{ // Required + { // Required Grantee: &s3.Grantee{ Type: aws.String("Type"), // Required DisplayName: aws.String("DisplayName"), @@ -1357,7 +1357,7 @@ func ExampleS3_PutBucketLogging() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1414,7 +1414,7 @@ func ExampleS3_PutBucketNotification() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1431,7 +1431,7 @@ func ExampleS3_PutBucketNotificationConfiguration() { Bucket: aws.String("BucketName"), // Required NotificationConfiguration: &s3.NotificationConfiguration{ // Required LambdaFunctionConfigurations: []*s3.LambdaFunctionConfiguration{ - &s3.LambdaFunctionConfiguration{ // Required + { // Required Events: []*string{ // Required aws.String("Event"), // Required // More values... @@ -1442,7 +1442,7 @@ func ExampleS3_PutBucketNotificationConfiguration() { // More values... }, QueueConfigurations: []*s3.QueueConfiguration{ - &s3.QueueConfiguration{ // Required + { // Required Events: []*string{ // Required aws.String("Event"), // Required // More values... @@ -1453,7 +1453,7 @@ func ExampleS3_PutBucketNotificationConfiguration() { // More values... }, TopicConfigurations: []*s3.TopicConfiguration{ - &s3.TopicConfiguration{ // Required + { // Required Events: []*string{ // Required aws.String("Event"), // Required // More values... @@ -1476,7 +1476,7 @@ func ExampleS3_PutBucketNotificationConfiguration() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1504,7 +1504,7 @@ func ExampleS3_PutBucketPolicy() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1522,7 +1522,7 @@ func ExampleS3_PutBucketReplication() { ReplicationConfiguration: &s3.ReplicationConfiguration{ // Required Role: aws.String("Role"), // Required Rules: []*s3.ReplicationRule{ // Required - &s3.ReplicationRule{ // Required + { // Required Destination: &s3.Destination{ // Required Bucket: aws.String("BucketName"), // Required }, @@ -1545,7 +1545,7 @@ func ExampleS3_PutBucketReplication() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1575,7 +1575,7 @@ func ExampleS3_PutBucketRequestPayment() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1592,7 +1592,7 @@ func ExampleS3_PutBucketTagging() { Bucket: aws.String("BucketName"), // Required Tagging: &s3.Tagging{ // Required TagSet: []*s3.Tag{ // Required - &s3.Tag{ // Required + { // Required Key: aws.String("ObjectKey"), // Required Value: aws.String("Value"), // Required }, @@ -1611,7 +1611,7 @@ func ExampleS3_PutBucketTagging() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1643,7 +1643,7 @@ func ExampleS3_PutBucketVersioning() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1670,7 +1670,7 @@ func ExampleS3_PutBucketWebsite() { Protocol: aws.String("Protocol"), }, RoutingRules: []*s3.RoutingRule{ - &s3.RoutingRule{ // Required + { // Required Redirect: &s3.Redirect{ // Required HTTPRedirectCode: aws.String("HttpRedirectCode"), HostName: aws.String("HostName"), @@ -1698,7 +1698,7 @@ func ExampleS3_PutBucketWebsite() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1751,7 +1751,7 @@ func ExampleS3_PutObject() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1770,7 +1770,7 @@ func ExampleS3_PutObjectACL() { ACL: aws.String("ObjectCannedACL"), AccessControlPolicy: &s3.AccessControlPolicy{ Grants: []*s3.Grant{ - &s3.Grant{ // Required + { // Required Grantee: &s3.Grantee{ Type: aws.String("Type"), // Required DisplayName: aws.String("DisplayName"), @@ -1805,7 +1805,7 @@ func ExampleS3_PutObjectACL() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1838,7 +1838,7 @@ func ExampleS3_RestoreObject() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1874,7 +1874,7 @@ func ExampleS3_UploadPart() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } @@ -1917,7 +1917,7 @@ func ExampleS3_UploadPartCopy() { fmt.Println(reqErr.Code(), reqErr.Message(), reqErr.StatusCode(), reqErr.RequestID()) } } else { - // This case should never be hit, The SDK should alwsy return an + // This case should never be hit, the SDK should always return an // error which satisfies the awserr.Error interface. fmt.Println(err.Error()) } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/download.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/download.go index 87dbe03a4..d6ebe024e 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/download.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/download.go @@ -129,12 +129,7 @@ func (d *downloader) download() (n int64, err error) { } // Queue the next range of bytes to read. - ch <- dlchunk{ - dlchunkcounter: &dlchunkcounter{}, - w: d.w, - start: d.pos, - size: d.opts.PartSize, - } + ch <- dlchunk{w: d.w, start: d.pos, size: d.opts.PartSize} d.pos += d.opts.PartSize } @@ -175,7 +170,7 @@ func (d *downloader) downloadPart(ch chan dlchunk) { } else { d.setTotalBytes(resp) // Set total if not yet set. - n, err := io.Copy(chunk, resp.Body) + n, err := io.Copy(&chunk, resp.Body) resp.Body.Close() if err != nil { @@ -242,21 +237,15 @@ func (d *downloader) seterr(e error) { // io.WriterAt, effectively making it an io.SectionWriter (which does not // exist). type dlchunk struct { - *dlchunkcounter w io.WriterAt start int64 size int64 -} - -// dlchunkcounter keeps track of the current position the dlchunk struct is -// writing to. -type dlchunkcounter struct { - cur int64 + cur int64 } // Write wraps io.WriterAt for the dlchunk, writing from the dlchunk's start // position to its end (or EOF). -func (c dlchunk) Write(p []byte) (n int, err error) { +func (c *dlchunk) Write(p []byte) (n int, err error) { if c.cur >= c.size { return 0, io.EOF } diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload.go index cdb83e47a..db556805d 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload.go @@ -10,7 +10,6 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/internal/apierr" "github.com/aws/aws-sdk-go/service/s3" ) @@ -60,13 +59,17 @@ type MultiUploadFailure interface { UploadID() string } +// So that the Error interface type can be included as an anonymous field +// in the multiUploadError struct and not conflict with the error.Error() method. +type awsError awserr.Error + // A multiUploadError wraps the upload ID of a failed s3 multipart upload. // Composed of BaseError for code, message, and original error // // Should be used for an error that occurred failing a S3 multipart upload, // and a upload ID is available. If an uploadID is not available a more relevant type multiUploadError struct { - *apierr.BaseError + awsError // ID for multipart upload which failed. uploadID string @@ -77,18 +80,19 @@ type multiUploadError struct { // See apierr.BaseError ErrorWithExtra for output format // // Satisfies the error interface. -func (m *multiUploadError) Error() string { - return m.ErrorWithExtra(fmt.Sprintf("upload id: %s", m.uploadID)) +func (m multiUploadError) Error() string { + extra := fmt.Sprintf("upload id: %s", m.uploadID) + return awserr.SprintError(m.Code(), m.Message(), extra, m.OrigErr()) } // String returns the string representation of the error. // Alias for Error to satisfy the stringer interface. -func (m *multiUploadError) String() string { +func (m multiUploadError) String() string { return m.Error() } // UploadID returns the id of the S3 upload which failed. -func (m *multiUploadError) UploadID() string { +func (m multiUploadError) UploadID() string { return m.uploadID } @@ -258,7 +262,7 @@ func (u *uploader) upload() (*UploadOutput, error) { if u.opts.PartSize < MinUploadPartSize { msg := fmt.Sprintf("part size must be at least %d bytes", MinUploadPartSize) - return nil, apierr.New("ConfigError", msg, nil) + return nil, awserr.New("ConfigError", msg, nil) } // Do one read to determine if we have more than one part @@ -266,7 +270,7 @@ func (u *uploader) upload() (*UploadOutput, error) { if err == io.EOF || err == io.ErrUnexpectedEOF { // single part return u.singlePart(buf) } else if err != nil { - return nil, apierr.New("ReadRequestBody", "read upload data failed", err) + return nil, awserr.New("ReadRequestBody", "read upload data failed", err) } mu := multiuploader{uploader: u} @@ -418,7 +422,7 @@ func (u *multiuploader) upload(firstBuf io.ReadSeeker) (*UploadOutput, error) { if num > int64(MaxUploadParts) { msg := fmt.Sprintf("exceeded total allowed parts (%d). "+ "Adjust PartSize to fit in this limit", MaxUploadParts) - u.seterr(apierr.New("TotalPartsExceeded", msg, nil)) + u.seterr(awserr.New("TotalPartsExceeded", msg, nil)) break } @@ -432,7 +436,10 @@ func (u *multiuploader) upload(firstBuf io.ReadSeeker) (*UploadOutput, error) { ch <- chunk{buf: buf, num: num} if err != nil && err != io.ErrUnexpectedEOF { - u.seterr(apierr.New("ReadRequestBody", "read multipart upload data failed", err)) + u.seterr(awserr.New( + "ReadRequestBody", + "read multipart upload data failed", + err)) break } } @@ -443,16 +450,12 @@ func (u *multiuploader) upload(firstBuf io.ReadSeeker) (*UploadOutput, error) { complete := u.complete() if err := u.geterr(); err != nil { - var berr *apierr.BaseError - switch t := err.(type) { - case *apierr.BaseError: - berr = t - default: - berr = apierr.New("MultipartUpload", "upload multipart failed", err) - } return nil, &multiUploadError{ - BaseError: berr, - uploadID: u.uploadID, + awsError: awserr.New( + "MultipartUpload", + "upload multipart failed", + err), + uploadID: u.uploadID, } } return &UploadOutput{ diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_test.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_test.go index 25639d8ab..901641934 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_test.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/s3manager/upload_test.go @@ -23,11 +23,22 @@ var _ = unit.Imported var buf12MB = make([]byte, 1024*1024*12) var buf2MB = make([]byte, 1024*1024*2) +var emptyList = []string{} + func val(i interface{}, s string) interface{} { return awsutil.ValuesAtPath(i, s)[0] } -func loggingSvc() (*s3.S3, *[]string, *[]interface{}) { +func contains(src []string, s string) bool { + for _, v := range src { + if s == v { + return true + } + } + return false +} + +func loggingSvc(ignoreOps []string) (*s3.S3, *[]string, *[]interface{}) { var m sync.Mutex partNum := 0 names := []string{} @@ -41,8 +52,10 @@ func loggingSvc() (*s3.S3, *[]string, *[]interface{}) { m.Lock() defer m.Unlock() - names = append(names, r.Operation.Name) - params = append(params, r.Params) + if !contains(ignoreOps, r.Operation.Name) { + names = append(names, r.Operation.Name) + params = append(params, r.Params) + } r.HTTPResponse = &http.Response{ StatusCode: 200, @@ -70,7 +83,7 @@ func buflen(i interface{}) int { } func TestUploadOrderMulti(t *testing.T) { - s, ops, args := loggingSvc() + s, ops, args := loggingSvc(emptyList) mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) resp, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), @@ -107,7 +120,7 @@ func TestUploadOrderMulti(t *testing.T) { } func TestUploadOrderMultiDifferentPartSize(t *testing.T) { - s, ops, args := loggingSvc() + s, ops, args := loggingSvc(emptyList) mgr := s3manager.NewUploader(&s3manager.UploadOptions{ S3: s, PartSize: 1024 * 1024 * 7, @@ -131,7 +144,7 @@ func TestUploadIncreasePartSize(t *testing.T) { s3manager.MaxUploadParts = 2 defer func() { s3manager.MaxUploadParts = 10000 }() - s, ops, args := loggingSvc() + s, ops, args := loggingSvc(emptyList) opts := &s3manager.UploadOptions{S3: s, Concurrency: 1} mgr := s3manager.NewUploader(opts) _, err := mgr.Upload(&s3manager.UploadInput{ @@ -167,7 +180,7 @@ func TestUploadFailIfPartSizeTooSmall(t *testing.T) { } func TestUploadOrderSingle(t *testing.T) { - s, ops, args := loggingSvc() + s, ops, args := loggingSvc(emptyList) mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) resp, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), @@ -186,7 +199,7 @@ func TestUploadOrderSingle(t *testing.T) { } func TestUploadOrderSingleFailure(t *testing.T) { - s, ops, _ := loggingSvc() + s, ops, _ := loggingSvc(emptyList) s.Handlers.Send.PushBack(func(r *aws.Request) { r.HTTPResponse.StatusCode = 400 }) @@ -203,7 +216,7 @@ func TestUploadOrderSingleFailure(t *testing.T) { } func TestUploadOrderZero(t *testing.T) { - s, ops, args := loggingSvc() + s, ops, args := loggingSvc(emptyList) mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) resp, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), @@ -219,7 +232,7 @@ func TestUploadOrderZero(t *testing.T) { } func TestUploadOrderMultiFailure(t *testing.T) { - s, ops, _ := loggingSvc() + s, ops, _ := loggingSvc(emptyList) s.Handlers.Send.PushBack(func(r *aws.Request) { switch t := r.Data.(type) { case *s3.UploadPartOutput: @@ -241,7 +254,7 @@ func TestUploadOrderMultiFailure(t *testing.T) { } func TestUploadOrderMultiFailureOnComplete(t *testing.T) { - s, ops, _ := loggingSvc() + s, ops, _ := loggingSvc(emptyList) s.Handlers.Send.PushBack(func(r *aws.Request) { switch r.Data.(type) { case *s3.CompleteMultipartUploadOutput: @@ -249,7 +262,7 @@ func TestUploadOrderMultiFailureOnComplete(t *testing.T) { } }) - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) + mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s, Concurrency: 1}) _, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), Key: aws.String("Key"), @@ -262,7 +275,7 @@ func TestUploadOrderMultiFailureOnComplete(t *testing.T) { } func TestUploadOrderMultiFailureOnCreate(t *testing.T) { - s, ops, _ := loggingSvc() + s, ops, _ := loggingSvc(emptyList) s.Handlers.Send.PushBack(func(r *aws.Request) { switch r.Data.(type) { case *s3.CreateMultipartUploadOutput: @@ -282,7 +295,7 @@ func TestUploadOrderMultiFailureOnCreate(t *testing.T) { } func TestUploadOrderMultiFailureLeaveParts(t *testing.T) { - s, ops, _ := loggingSvc() + s, ops, _ := loggingSvc(emptyList) s.Handlers.Send.PushBack(func(r *aws.Request) { switch data := r.Data.(type) { case *s3.UploadPartOutput: @@ -307,26 +320,26 @@ func TestUploadOrderMultiFailureLeaveParts(t *testing.T) { assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart"}, *ops) } -var failreaderCount = 0 +type failreader struct { + times int + failCount int +} -type failreader struct{ times int } - -func (f failreader) Read(b []byte) (int, error) { - failreaderCount++ - if failreaderCount >= f.times { +func (f *failreader) Read(b []byte) (int, error) { + f.failCount++ + if f.failCount >= f.times { return 0, fmt.Errorf("random failure") } return len(b), nil } func TestUploadOrderReadFail1(t *testing.T) { - failreaderCount = 0 - s, ops, _ := loggingSvc() + s, ops, _ := loggingSvc(emptyList) mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) _, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), Key: aws.String("Key"), - Body: failreader{1}, + Body: &failreader{times: 1}, }) assert.Equal(t, "ReadRequestBody", err.(awserr.Error).Code()) @@ -335,13 +348,12 @@ func TestUploadOrderReadFail1(t *testing.T) { } func TestUploadOrderReadFail2(t *testing.T) { - failreaderCount = 0 - s, ops, _ := loggingSvc() - mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) + s, ops, _ := loggingSvc([]string{"UploadPart"}) + mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s, Concurrency: 1}) _, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), Key: aws.String("Key"), - Body: failreader{2}, + Body: &failreader{times: 2}, }) assert.Equal(t, "ReadRequestBody", err.(awserr.Error).Code()) @@ -349,16 +361,12 @@ func TestUploadOrderReadFail2(t *testing.T) { assert.Equal(t, []string{"CreateMultipartUpload", "AbortMultipartUpload"}, *ops) } -type sizedReaderImpl struct { +type sizedReader struct { size int cur int } -type sizedReader struct { - *sizedReaderImpl -} - -func (s sizedReader) Read(p []byte) (n int, err error) { +func (s *sizedReader) Read(p []byte) (n int, err error) { if s.cur >= s.size { return 0, io.EOF } @@ -373,12 +381,12 @@ func (s sizedReader) Read(p []byte) (n int, err error) { } func TestUploadOrderMultiBufferedReader(t *testing.T) { - s, ops, args := loggingSvc() + s, ops, args := loggingSvc(emptyList) mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) _, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), Key: aws.String("Key"), - Body: sizedReader{&sizedReaderImpl{size: 1024 * 1024 * 12}}, + Body: &sizedReader{size: 1024 * 1024 * 12}, }) assert.NoError(t, err) @@ -397,17 +405,17 @@ func TestUploadOrderMultiBufferedReader(t *testing.T) { func TestUploadOrderMultiBufferedReaderExceedTotalParts(t *testing.T) { s3manager.MaxUploadParts = 2 defer func() { s3manager.MaxUploadParts = 10000 }() - s, ops, _ := loggingSvc() + s, ops, _ := loggingSvc([]string{"UploadPart"}) mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s, Concurrency: 1}) resp, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), Key: aws.String("Key"), - Body: sizedReader{&sizedReaderImpl{size: 1024 * 1024 * 12}}, + Body: &sizedReader{size: 1024 * 1024 * 12}, }) assert.Error(t, err) assert.Nil(t, resp) - assert.Equal(t, []string{"CreateMultipartUpload", "UploadPart", "UploadPart", "AbortMultipartUpload"}, *ops) + assert.Equal(t, []string{"CreateMultipartUpload", "AbortMultipartUpload"}, *ops) aerr := err.(awserr.Error) assert.Equal(t, "TotalPartsExceeded", aerr.Code()) @@ -415,12 +423,12 @@ func TestUploadOrderMultiBufferedReaderExceedTotalParts(t *testing.T) { } func TestUploadOrderSingleBufferedReader(t *testing.T) { - s, ops, _ := loggingSvc() + s, ops, _ := loggingSvc(emptyList) mgr := s3manager.NewUploader(&s3manager.UploadOptions{S3: s}) resp, err := mgr.Upload(&s3manager.UploadInput{ Bucket: aws.String("Bucket"), Key: aws.String("Key"), - Body: sizedReader{&sizedReaderImpl{size: 1024 * 1024 * 2}}, + Body: &sizedReader{size: 1024 * 1024 * 2}, }) assert.NoError(t, err) diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/sse.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/sse.go index dd54163f8..01350f7c1 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/sse.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/sse.go @@ -5,11 +5,11 @@ import ( "encoding/base64" "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/internal/apierr" ) -var errSSERequiresSSL = apierr.New("ConfigError", "cannot send SSE keys over HTTP.", nil) +var errSSERequiresSSL = awserr.New("ConfigError", "cannot send SSE keys over HTTP.", nil) func validateSSERequiresSSL(r *aws.Request) { if r.HTTPRequest.URL.Scheme != "https" { diff --git a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go index e14cd3a7f..c27d4342f 100644 --- a/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go +++ b/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3/unmarshal_error.go @@ -6,7 +6,7 @@ import ( "strings" "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/internal/apierr" + "github.com/aws/aws-sdk-go/aws/awserr" ) type xmlErrorResponse struct { @@ -20,8 +20,8 @@ func unmarshalError(r *aws.Request) { if r.HTTPResponse.ContentLength == int64(0) { // No body, use status code to generate an awserr.Error - r.Error = apierr.NewRequestError( - apierr.New(strings.Replace(r.HTTPResponse.Status, " ", "", -1), r.HTTPResponse.Status, nil), + r.Error = awserr.NewRequestFailure( + awserr.New(strings.Replace(r.HTTPResponse.Status, " ", "", -1), r.HTTPResponse.Status, nil), r.HTTPResponse.StatusCode, "", ) @@ -31,10 +31,10 @@ func unmarshalError(r *aws.Request) { resp := &xmlErrorResponse{} err := xml.NewDecoder(r.HTTPResponse.Body).Decode(resp) if err != nil && err != io.EOF { - r.Error = apierr.New("Unmarshal", "failed to decode S3 XML error response", nil) + r.Error = awserr.New("SerializationError", "failed to decode S3 XML error response", nil) } else { - r.Error = apierr.NewRequestError( - apierr.New(resp.Code, resp.Message, nil), + r.Error = awserr.NewRequestFailure( + awserr.New(resp.Code, resp.Message, nil), r.HTTPResponse.StatusCode, "", ) diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/client.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/client.go index c6cf3341b..a1cbb8bcb 100644 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/client.go +++ b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/client.go @@ -192,7 +192,7 @@ func (c *Client) Close() { // initHTTPClient initializes a HTTP client for etcd client func (c *Client) initHTTPClient() { c.transport = &http.Transport{ - Dial: c.dial, + Dial: c.DefaultDial, TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, }, @@ -218,7 +218,7 @@ func (c *Client) initHTTPSClient(cert, key string) error { tr := &http.Transport{ TLSClientConfig: tlsConfig, - Dial: c.dial, + Dial: c.DefaultDial, } c.httpClient = &http.Client{Transport: tr} @@ -306,12 +306,16 @@ func (c *Client) GetCluster() []string { } // SyncCluster updates the cluster information using the internal machine list. +// If no members are found, the intenral machine list is left untouched. func (c *Client) SyncCluster() bool { return c.internalSyncCluster(c.cluster.Machines) } // internalSyncCluster syncs cluster information using the given machine list. func (c *Client) internalSyncCluster(machines []string) bool { + // comma-separated list of machines in the cluster. + members := "" + for _, machine := range machines { httpPath := c.createHttpPath(machine, path.Join(version, "members")) resp, err := c.httpClient.Get(httpPath) @@ -333,8 +337,7 @@ func (c *Client) internalSyncCluster(machines []string) bool { // try another machine in the cluster continue } - // update Machines List - c.cluster.updateFromStr(string(b)) + members = string(b) } else { b, err := ioutil.ReadAll(resp.Body) resp.Body.Close() @@ -354,10 +357,16 @@ func (c *Client) internalSyncCluster(machines []string) bool { urls = append(urls, m.ClientURLs...) } - // update Machines List - c.cluster.updateFromStr(strings.Join(urls, ",")) + members = strings.Join(urls, ",") } + // We should never do an empty cluster update. + if members == "" { + continue + } + + // update Machines List + c.cluster.updateFromStr(members) logger.Debug("sync.machines ", c.cluster.Machines) c.saveConfig() return true @@ -382,9 +391,9 @@ func (c *Client) createHttpPath(serverName string, _path string) string { return u.String() } -// dial attempts to open a TCP connection to the provided address, explicitly +// DefaultDial attempts to open a TCP connection to the provided address, explicitly // enabling keep-alives with a one-second interval. -func (c *Client) dial(network, addr string) (net.Conn, error) { +func (c *Client) DefaultDial(network, addr string) (net.Conn, error) { conn, err := net.DialTimeout(network, addr, c.config.DialTimeout) if err != nil { return nil, err diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/cluster.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/cluster.go index 1ad3e155b..173a27356 100644 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/cluster.go +++ b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/cluster.go @@ -3,12 +3,14 @@ package etcd import ( "math/rand" "strings" + "sync" ) type Cluster struct { Leader string `json:"leader"` Machines []string `json:"machines"` picked int + mu sync.RWMutex } func NewCluster(machines []string) *Cluster { @@ -25,10 +27,22 @@ func NewCluster(machines []string) *Cluster { } } -func (cl *Cluster) failure() { cl.picked = rand.Intn(len(cl.Machines)) } -func (cl *Cluster) pick() string { return cl.Machines[cl.picked] } +func (cl *Cluster) failure() { + cl.mu.Lock() + defer cl.mu.Unlock() + cl.picked = rand.Intn(len(cl.Machines)) +} + +func (cl *Cluster) pick() string { + cl.mu.Lock() + defer cl.mu.Unlock() + return cl.Machines[cl.picked] +} func (cl *Cluster) updateFromStr(machines string) { + cl.mu.Lock() + defer cl.mu.Unlock() + cl.Machines = strings.Split(machines, ",") for i := range cl.Machines { cl.Machines[i] = strings.TrimSpace(cl.Machines[i]) diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response.generated.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response.generated.go new file mode 100644 index 000000000..eb05e4c89 --- /dev/null +++ b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response.generated.go @@ -0,0 +1,1419 @@ +// ************************************************************ +// DO NOT EDIT. +// THIS FILE IS AUTO-GENERATED BY codecgen. +// ************************************************************ + +package etcd + +import ( + "errors" + "fmt" + codec1978 "github.com/ugorji/go/codec" + "net/http" + "reflect" + "runtime" + "time" +) + +const ( + codecSelferC_UTF84402 = 1 + codecSelferC_RAW4402 = 0 + codecSelverValueTypeArray4402 = 10 + codecSelverValueTypeMap4402 = 9 +) + +var ( + codecSelferBitsize4402 = uint8(reflect.TypeOf(uint(0)).Bits()) + codecSelferOnlyMapOrArrayEncodeToStructErr4402 = errors.New(`only encoded map or array can be decoded into a struct`) +) + +type codecSelfer4402 struct{} + +func init() { + if codec1978.GenVersion != 2 { + _, file, _, _ := runtime.Caller(0) + err := fmt.Errorf("codecgen version mismatch: current: %v, need %v. Re-generate file: %v", + 2, codec1978.GenVersion, file) + panic(err) + } + if false { // reference the types, but skip this branch at build/run time + var v0 http.Header + var v1 time.Time + _, _ = v0, v1 + } +} + +func (x responseType) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeInt(int64(x)) +} + +func (x *responseType) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + *((*int)(x)) = int(r.DecodeInt(codecSelferBitsize4402)) +} + +func (x *RawResponse) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yysep1 := !z.EncBinary() + yy2arr1 := z.EncBasicHandle().StructToArray + var yyfirst1 bool + var yyq1 [3]bool + _, _, _, _ = yysep1, yyfirst1, yyq1, yy2arr1 + const yyr1 bool = false + if yyr1 || yy2arr1 { + r.EncodeArrayStart(3) + } else { + var yynn1 int = 3 + for _, b := range yyq1 { + if b { + yynn1++ + } + } + r.EncodeMapStart(yynn1) + } + if yyr1 || yy2arr1 { + r.EncodeInt(int64(x.StatusCode)) + } else { + yyfirst1 = true + r.EncodeString(codecSelferC_UTF84402, string("StatusCode")) + if yysep1 { + r.EncodeMapKVSeparator() + } + r.EncodeInt(int64(x.StatusCode)) + } + if yyr1 || yy2arr1 { + if yysep1 { + r.EncodeArrayEntrySeparator() + } + if x.Body == nil { + r.EncodeNil() + } else { + r.EncodeStringBytes(codecSelferC_RAW4402, []byte(x.Body)) + } + } else { + if yyfirst1 { + r.EncodeMapEntrySeparator() + } else { + yyfirst1 = true + } + r.EncodeString(codecSelferC_UTF84402, string("Body")) + if yysep1 { + r.EncodeMapKVSeparator() + } + if x.Body == nil { + r.EncodeNil() + } else { + r.EncodeStringBytes(codecSelferC_RAW4402, []byte(x.Body)) + } + } + if yyr1 || yy2arr1 { + if yysep1 { + r.EncodeArrayEntrySeparator() + } + if x.Header == nil { + r.EncodeNil() + } else { + h.enchttp_Header(http.Header(x.Header), e) + } + } else { + if yyfirst1 { + r.EncodeMapEntrySeparator() + } else { + yyfirst1 = true + } + r.EncodeString(codecSelferC_UTF84402, string("Header")) + if yysep1 { + r.EncodeMapKVSeparator() + } + if x.Header == nil { + r.EncodeNil() + } else { + h.enchttp_Header(http.Header(x.Header), e) + } + } + if yysep1 { + if yyr1 || yy2arr1 { + r.EncodeArrayEnd() + } else { + r.EncodeMapEnd() + } + } + } +} + +func (x *RawResponse) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + if r.IsContainerType(codecSelverValueTypeMap4402) { + yyl5 := r.ReadMapStart() + if yyl5 == 0 { + r.ReadMapEnd() + } else { + x.codecDecodeSelfFromMap(yyl5, d) + } + } else if r.IsContainerType(codecSelverValueTypeArray4402) { + yyl5 := r.ReadArrayStart() + if yyl5 == 0 { + r.ReadArrayEnd() + } else { + x.codecDecodeSelfFromArray(yyl5, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr4402) + } +} + +func (x *RawResponse) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys6Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys6Slc + var yyhl6 bool = l >= 0 + for yyj6 := 0; ; yyj6++ { + if yyhl6 { + if yyj6 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + if yyj6 > 0 { + r.ReadMapEntrySeparator() + } + } + yys6Slc = r.DecodeBytes(yys6Slc, true, true) + yys6 := string(yys6Slc) + if !yyhl6 { + r.ReadMapKVSeparator() + } + switch yys6 { + case "StatusCode": + if r.TryDecodeAsNil() { + x.StatusCode = 0 + } else { + x.StatusCode = int(r.DecodeInt(codecSelferBitsize4402)) + } + case "Body": + if r.TryDecodeAsNil() { + x.Body = nil + } else { + yyv8 := &x.Body + *yyv8 = r.DecodeBytes(*(*[]byte)(yyv8), false, false) + } + case "Header": + if r.TryDecodeAsNil() { + x.Header = nil + } else { + yyv9 := &x.Header + h.dechttp_Header((*http.Header)(yyv9), d) + } + default: + z.DecStructFieldNotFound(-1, yys6) + } // end switch yys6 + } // end for yyj6 + if !yyhl6 { + r.ReadMapEnd() + } +} + +func (x *RawResponse) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj10 int + var yyb10 bool + var yyhl10 bool = l >= 0 + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + r.ReadArrayEnd() + return + } + if r.TryDecodeAsNil() { + x.StatusCode = 0 + } else { + x.StatusCode = int(r.DecodeInt(codecSelferBitsize4402)) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + x.Body = nil + } else { + yyv12 := &x.Body + *yyv12 = r.DecodeBytes(*(*[]byte)(yyv12), false, false) + } + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + x.Header = nil + } else { + yyv13 := &x.Header + h.dechttp_Header((*http.Header)(yyv13), d) + } + for { + yyj10++ + if yyhl10 { + yyb10 = yyj10 > l + } else { + yyb10 = r.CheckBreak() + } + if yyb10 { + break + } + if yyj10 > 1 { + r.ReadArrayEntrySeparator() + } + z.DecStructFieldNotFound(yyj10-1, "") + } + r.ReadArrayEnd() +} + +func (x *Response) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yysep14 := !z.EncBinary() + yy2arr14 := z.EncBasicHandle().StructToArray + var yyfirst14 bool + var yyq14 [6]bool + _, _, _, _ = yysep14, yyfirst14, yyq14, yy2arr14 + const yyr14 bool = false + yyq14[2] = x.PrevNode != nil + if yyr14 || yy2arr14 { + r.EncodeArrayStart(6) + } else { + var yynn14 int = 5 + for _, b := range yyq14 { + if b { + yynn14++ + } + } + r.EncodeMapStart(yynn14) + } + if yyr14 || yy2arr14 { + r.EncodeString(codecSelferC_UTF84402, string(x.Action)) + } else { + yyfirst14 = true + r.EncodeString(codecSelferC_UTF84402, string("action")) + if yysep14 { + r.EncodeMapKVSeparator() + } + r.EncodeString(codecSelferC_UTF84402, string(x.Action)) + } + if yyr14 || yy2arr14 { + if yysep14 { + r.EncodeArrayEntrySeparator() + } + if x.Node == nil { + r.EncodeNil() + } else { + x.Node.CodecEncodeSelf(e) + } + } else { + if yyfirst14 { + r.EncodeMapEntrySeparator() + } else { + yyfirst14 = true + } + r.EncodeString(codecSelferC_UTF84402, string("node")) + if yysep14 { + r.EncodeMapKVSeparator() + } + if x.Node == nil { + r.EncodeNil() + } else { + x.Node.CodecEncodeSelf(e) + } + } + if yyr14 || yy2arr14 { + if yysep14 { + r.EncodeArrayEntrySeparator() + } + if yyq14[2] { + if x.PrevNode == nil { + r.EncodeNil() + } else { + x.PrevNode.CodecEncodeSelf(e) + } + } else { + r.EncodeNil() + } + } else { + if yyq14[2] { + if yyfirst14 { + r.EncodeMapEntrySeparator() + } else { + yyfirst14 = true + } + r.EncodeString(codecSelferC_UTF84402, string("prevNode")) + if yysep14 { + r.EncodeMapKVSeparator() + } + if x.PrevNode == nil { + r.EncodeNil() + } else { + x.PrevNode.CodecEncodeSelf(e) + } + } + } + if yyr14 || yy2arr14 { + if yysep14 { + r.EncodeArrayEntrySeparator() + } + r.EncodeUint(uint64(x.EtcdIndex)) + } else { + if yyfirst14 { + r.EncodeMapEntrySeparator() + } else { + yyfirst14 = true + } + r.EncodeString(codecSelferC_UTF84402, string("etcdIndex")) + if yysep14 { + r.EncodeMapKVSeparator() + } + r.EncodeUint(uint64(x.EtcdIndex)) + } + if yyr14 || yy2arr14 { + if yysep14 { + r.EncodeArrayEntrySeparator() + } + r.EncodeUint(uint64(x.RaftIndex)) + } else { + if yyfirst14 { + r.EncodeMapEntrySeparator() + } else { + yyfirst14 = true + } + r.EncodeString(codecSelferC_UTF84402, string("raftIndex")) + if yysep14 { + r.EncodeMapKVSeparator() + } + r.EncodeUint(uint64(x.RaftIndex)) + } + if yyr14 || yy2arr14 { + if yysep14 { + r.EncodeArrayEntrySeparator() + } + r.EncodeUint(uint64(x.RaftTerm)) + } else { + if yyfirst14 { + r.EncodeMapEntrySeparator() + } else { + yyfirst14 = true + } + r.EncodeString(codecSelferC_UTF84402, string("raftTerm")) + if yysep14 { + r.EncodeMapKVSeparator() + } + r.EncodeUint(uint64(x.RaftTerm)) + } + if yysep14 { + if yyr14 || yy2arr14 { + r.EncodeArrayEnd() + } else { + r.EncodeMapEnd() + } + } + } +} + +func (x *Response) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + if r.IsContainerType(codecSelverValueTypeMap4402) { + yyl21 := r.ReadMapStart() + if yyl21 == 0 { + r.ReadMapEnd() + } else { + x.codecDecodeSelfFromMap(yyl21, d) + } + } else if r.IsContainerType(codecSelverValueTypeArray4402) { + yyl21 := r.ReadArrayStart() + if yyl21 == 0 { + r.ReadArrayEnd() + } else { + x.codecDecodeSelfFromArray(yyl21, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr4402) + } +} + +func (x *Response) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys22Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys22Slc + var yyhl22 bool = l >= 0 + for yyj22 := 0; ; yyj22++ { + if yyhl22 { + if yyj22 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + if yyj22 > 0 { + r.ReadMapEntrySeparator() + } + } + yys22Slc = r.DecodeBytes(yys22Slc, true, true) + yys22 := string(yys22Slc) + if !yyhl22 { + r.ReadMapKVSeparator() + } + switch yys22 { + case "action": + if r.TryDecodeAsNil() { + x.Action = "" + } else { + x.Action = string(r.DecodeString()) + } + case "node": + if r.TryDecodeAsNil() { + if x.Node != nil { + x.Node = nil + } + } else { + if x.Node == nil { + x.Node = new(Node) + } + x.Node.CodecDecodeSelf(d) + } + case "prevNode": + if r.TryDecodeAsNil() { + if x.PrevNode != nil { + x.PrevNode = nil + } + } else { + if x.PrevNode == nil { + x.PrevNode = new(Node) + } + x.PrevNode.CodecDecodeSelf(d) + } + case "etcdIndex": + if r.TryDecodeAsNil() { + x.EtcdIndex = 0 + } else { + x.EtcdIndex = uint64(r.DecodeUint(64)) + } + case "raftIndex": + if r.TryDecodeAsNil() { + x.RaftIndex = 0 + } else { + x.RaftIndex = uint64(r.DecodeUint(64)) + } + case "raftTerm": + if r.TryDecodeAsNil() { + x.RaftTerm = 0 + } else { + x.RaftTerm = uint64(r.DecodeUint(64)) + } + default: + z.DecStructFieldNotFound(-1, yys22) + } // end switch yys22 + } // end for yyj22 + if !yyhl22 { + r.ReadMapEnd() + } +} + +func (x *Response) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj29 int + var yyb29 bool + var yyhl29 bool = l >= 0 + yyj29++ + if yyhl29 { + yyb29 = yyj29 > l + } else { + yyb29 = r.CheckBreak() + } + if yyb29 { + r.ReadArrayEnd() + return + } + if r.TryDecodeAsNil() { + x.Action = "" + } else { + x.Action = string(r.DecodeString()) + } + yyj29++ + if yyhl29 { + yyb29 = yyj29 > l + } else { + yyb29 = r.CheckBreak() + } + if yyb29 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + if x.Node != nil { + x.Node = nil + } + } else { + if x.Node == nil { + x.Node = new(Node) + } + x.Node.CodecDecodeSelf(d) + } + yyj29++ + if yyhl29 { + yyb29 = yyj29 > l + } else { + yyb29 = r.CheckBreak() + } + if yyb29 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + if x.PrevNode != nil { + x.PrevNode = nil + } + } else { + if x.PrevNode == nil { + x.PrevNode = new(Node) + } + x.PrevNode.CodecDecodeSelf(d) + } + yyj29++ + if yyhl29 { + yyb29 = yyj29 > l + } else { + yyb29 = r.CheckBreak() + } + if yyb29 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + x.EtcdIndex = 0 + } else { + x.EtcdIndex = uint64(r.DecodeUint(64)) + } + yyj29++ + if yyhl29 { + yyb29 = yyj29 > l + } else { + yyb29 = r.CheckBreak() + } + if yyb29 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + x.RaftIndex = 0 + } else { + x.RaftIndex = uint64(r.DecodeUint(64)) + } + yyj29++ + if yyhl29 { + yyb29 = yyj29 > l + } else { + yyb29 = r.CheckBreak() + } + if yyb29 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + x.RaftTerm = 0 + } else { + x.RaftTerm = uint64(r.DecodeUint(64)) + } + for { + yyj29++ + if yyhl29 { + yyb29 = yyj29 > l + } else { + yyb29 = r.CheckBreak() + } + if yyb29 { + break + } + if yyj29 > 1 { + r.ReadArrayEntrySeparator() + } + z.DecStructFieldNotFound(yyj29-1, "") + } + r.ReadArrayEnd() +} + +func (x *Node) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + yysep36 := !z.EncBinary() + yy2arr36 := z.EncBasicHandle().StructToArray + var yyfirst36 bool + var yyq36 [8]bool + _, _, _, _ = yysep36, yyfirst36, yyq36, yy2arr36 + const yyr36 bool = false + yyq36[1] = x.Value != "" + yyq36[2] = x.Dir != false + yyq36[3] = x.Expiration != nil + yyq36[4] = x.TTL != 0 + yyq36[5] = len(x.Nodes) != 0 + yyq36[6] = x.ModifiedIndex != 0 + yyq36[7] = x.CreatedIndex != 0 + if yyr36 || yy2arr36 { + r.EncodeArrayStart(8) + } else { + var yynn36 int = 1 + for _, b := range yyq36 { + if b { + yynn36++ + } + } + r.EncodeMapStart(yynn36) + } + if yyr36 || yy2arr36 { + r.EncodeString(codecSelferC_UTF84402, string(x.Key)) + } else { + yyfirst36 = true + r.EncodeString(codecSelferC_UTF84402, string("key")) + if yysep36 { + r.EncodeMapKVSeparator() + } + r.EncodeString(codecSelferC_UTF84402, string(x.Key)) + } + if yyr36 || yy2arr36 { + if yysep36 { + r.EncodeArrayEntrySeparator() + } + if yyq36[1] { + r.EncodeString(codecSelferC_UTF84402, string(x.Value)) + } else { + r.EncodeString(codecSelferC_UTF84402, "") + } + } else { + if yyq36[1] { + if yyfirst36 { + r.EncodeMapEntrySeparator() + } else { + yyfirst36 = true + } + r.EncodeString(codecSelferC_UTF84402, string("value")) + if yysep36 { + r.EncodeMapKVSeparator() + } + r.EncodeString(codecSelferC_UTF84402, string(x.Value)) + } + } + if yyr36 || yy2arr36 { + if yysep36 { + r.EncodeArrayEntrySeparator() + } + if yyq36[2] { + r.EncodeBool(bool(x.Dir)) + } else { + r.EncodeBool(false) + } + } else { + if yyq36[2] { + if yyfirst36 { + r.EncodeMapEntrySeparator() + } else { + yyfirst36 = true + } + r.EncodeString(codecSelferC_UTF84402, string("dir")) + if yysep36 { + r.EncodeMapKVSeparator() + } + r.EncodeBool(bool(x.Dir)) + } + } + if yyr36 || yy2arr36 { + if yysep36 { + r.EncodeArrayEntrySeparator() + } + if yyq36[3] { + if x.Expiration == nil { + r.EncodeNil() + } else { + z.EncFallback(x.Expiration) + } + } else { + r.EncodeNil() + } + } else { + if yyq36[3] { + if yyfirst36 { + r.EncodeMapEntrySeparator() + } else { + yyfirst36 = true + } + r.EncodeString(codecSelferC_UTF84402, string("expiration")) + if yysep36 { + r.EncodeMapKVSeparator() + } + if x.Expiration == nil { + r.EncodeNil() + } else { + z.EncFallback(x.Expiration) + } + } + } + if yyr36 || yy2arr36 { + if yysep36 { + r.EncodeArrayEntrySeparator() + } + if yyq36[4] { + r.EncodeInt(int64(x.TTL)) + } else { + r.EncodeInt(0) + } + } else { + if yyq36[4] { + if yyfirst36 { + r.EncodeMapEntrySeparator() + } else { + yyfirst36 = true + } + r.EncodeString(codecSelferC_UTF84402, string("ttl")) + if yysep36 { + r.EncodeMapKVSeparator() + } + r.EncodeInt(int64(x.TTL)) + } + } + if yyr36 || yy2arr36 { + if yysep36 { + r.EncodeArrayEntrySeparator() + } + if yyq36[5] { + if x.Nodes == nil { + r.EncodeNil() + } else { + x.Nodes.CodecEncodeSelf(e) + } + } else { + r.EncodeNil() + } + } else { + if yyq36[5] { + if yyfirst36 { + r.EncodeMapEntrySeparator() + } else { + yyfirst36 = true + } + r.EncodeString(codecSelferC_UTF84402, string("nodes")) + if yysep36 { + r.EncodeMapKVSeparator() + } + if x.Nodes == nil { + r.EncodeNil() + } else { + x.Nodes.CodecEncodeSelf(e) + } + } + } + if yyr36 || yy2arr36 { + if yysep36 { + r.EncodeArrayEntrySeparator() + } + if yyq36[6] { + r.EncodeUint(uint64(x.ModifiedIndex)) + } else { + r.EncodeUint(0) + } + } else { + if yyq36[6] { + if yyfirst36 { + r.EncodeMapEntrySeparator() + } else { + yyfirst36 = true + } + r.EncodeString(codecSelferC_UTF84402, string("modifiedIndex")) + if yysep36 { + r.EncodeMapKVSeparator() + } + r.EncodeUint(uint64(x.ModifiedIndex)) + } + } + if yyr36 || yy2arr36 { + if yysep36 { + r.EncodeArrayEntrySeparator() + } + if yyq36[7] { + r.EncodeUint(uint64(x.CreatedIndex)) + } else { + r.EncodeUint(0) + } + } else { + if yyq36[7] { + if yyfirst36 { + r.EncodeMapEntrySeparator() + } else { + yyfirst36 = true + } + r.EncodeString(codecSelferC_UTF84402, string("createdIndex")) + if yysep36 { + r.EncodeMapKVSeparator() + } + r.EncodeUint(uint64(x.CreatedIndex)) + } + } + if yysep36 { + if yyr36 || yy2arr36 { + r.EncodeArrayEnd() + } else { + r.EncodeMapEnd() + } + } + } +} + +func (x *Node) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + if r.IsContainerType(codecSelverValueTypeMap4402) { + yyl45 := r.ReadMapStart() + if yyl45 == 0 { + r.ReadMapEnd() + } else { + x.codecDecodeSelfFromMap(yyl45, d) + } + } else if r.IsContainerType(codecSelverValueTypeArray4402) { + yyl45 := r.ReadArrayStart() + if yyl45 == 0 { + r.ReadArrayEnd() + } else { + x.codecDecodeSelfFromArray(yyl45, d) + } + } else { + panic(codecSelferOnlyMapOrArrayEncodeToStructErr4402) + } +} + +func (x *Node) codecDecodeSelfFromMap(l int, d *codec1978.Decoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yys46Slc = z.DecScratchBuffer() // default slice to decode into + _ = yys46Slc + var yyhl46 bool = l >= 0 + for yyj46 := 0; ; yyj46++ { + if yyhl46 { + if yyj46 >= l { + break + } + } else { + if r.CheckBreak() { + break + } + if yyj46 > 0 { + r.ReadMapEntrySeparator() + } + } + yys46Slc = r.DecodeBytes(yys46Slc, true, true) + yys46 := string(yys46Slc) + if !yyhl46 { + r.ReadMapKVSeparator() + } + switch yys46 { + case "key": + if r.TryDecodeAsNil() { + x.Key = "" + } else { + x.Key = string(r.DecodeString()) + } + case "value": + if r.TryDecodeAsNil() { + x.Value = "" + } else { + x.Value = string(r.DecodeString()) + } + case "dir": + if r.TryDecodeAsNil() { + x.Dir = false + } else { + x.Dir = bool(r.DecodeBool()) + } + case "expiration": + if r.TryDecodeAsNil() { + if x.Expiration != nil { + x.Expiration = nil + } + } else { + if x.Expiration == nil { + x.Expiration = new(time.Time) + } + z.DecFallback(x.Expiration, false) + } + case "ttl": + if r.TryDecodeAsNil() { + x.TTL = 0 + } else { + x.TTL = int64(r.DecodeInt(64)) + } + case "nodes": + if r.TryDecodeAsNil() { + x.Nodes = nil + } else { + yyv52 := &x.Nodes + yyv52.CodecDecodeSelf(d) + } + case "modifiedIndex": + if r.TryDecodeAsNil() { + x.ModifiedIndex = 0 + } else { + x.ModifiedIndex = uint64(r.DecodeUint(64)) + } + case "createdIndex": + if r.TryDecodeAsNil() { + x.CreatedIndex = 0 + } else { + x.CreatedIndex = uint64(r.DecodeUint(64)) + } + default: + z.DecStructFieldNotFound(-1, yys46) + } // end switch yys46 + } // end for yyj46 + if !yyhl46 { + r.ReadMapEnd() + } +} + +func (x *Node) codecDecodeSelfFromArray(l int, d *codec1978.Decoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + var yyj55 int + var yyb55 bool + var yyhl55 bool = l >= 0 + yyj55++ + if yyhl55 { + yyb55 = yyj55 > l + } else { + yyb55 = r.CheckBreak() + } + if yyb55 { + r.ReadArrayEnd() + return + } + if r.TryDecodeAsNil() { + x.Key = "" + } else { + x.Key = string(r.DecodeString()) + } + yyj55++ + if yyhl55 { + yyb55 = yyj55 > l + } else { + yyb55 = r.CheckBreak() + } + if yyb55 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + x.Value = "" + } else { + x.Value = string(r.DecodeString()) + } + yyj55++ + if yyhl55 { + yyb55 = yyj55 > l + } else { + yyb55 = r.CheckBreak() + } + if yyb55 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + x.Dir = false + } else { + x.Dir = bool(r.DecodeBool()) + } + yyj55++ + if yyhl55 { + yyb55 = yyj55 > l + } else { + yyb55 = r.CheckBreak() + } + if yyb55 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + if x.Expiration != nil { + x.Expiration = nil + } + } else { + if x.Expiration == nil { + x.Expiration = new(time.Time) + } + z.DecFallback(x.Expiration, false) + } + yyj55++ + if yyhl55 { + yyb55 = yyj55 > l + } else { + yyb55 = r.CheckBreak() + } + if yyb55 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + x.TTL = 0 + } else { + x.TTL = int64(r.DecodeInt(64)) + } + yyj55++ + if yyhl55 { + yyb55 = yyj55 > l + } else { + yyb55 = r.CheckBreak() + } + if yyb55 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + x.Nodes = nil + } else { + yyv61 := &x.Nodes + yyv61.CodecDecodeSelf(d) + } + yyj55++ + if yyhl55 { + yyb55 = yyj55 > l + } else { + yyb55 = r.CheckBreak() + } + if yyb55 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + x.ModifiedIndex = 0 + } else { + x.ModifiedIndex = uint64(r.DecodeUint(64)) + } + yyj55++ + if yyhl55 { + yyb55 = yyj55 > l + } else { + yyb55 = r.CheckBreak() + } + if yyb55 { + r.ReadArrayEnd() + return + } + r.ReadArrayEntrySeparator() + if r.TryDecodeAsNil() { + x.CreatedIndex = 0 + } else { + x.CreatedIndex = uint64(r.DecodeUint(64)) + } + for { + yyj55++ + if yyhl55 { + yyb55 = yyj55 > l + } else { + yyb55 = r.CheckBreak() + } + if yyb55 { + break + } + if yyj55 > 1 { + r.ReadArrayEntrySeparator() + } + z.DecStructFieldNotFound(yyj55-1, "") + } + r.ReadArrayEnd() +} + +func (x Nodes) CodecEncodeSelf(e *codec1978.Encoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + if x == nil { + r.EncodeNil() + } else { + h.encNodes(Nodes(x), e) + } +} + +func (x *Nodes) CodecDecodeSelf(d *codec1978.Decoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + h.decNodes((*Nodes)(x), d) +} + +func (x codecSelfer4402) enchttp_Header(v http.Header, e *codec1978.Encoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeMapStart(len(v)) + yys64 := !z.EncBinary() + yyj64 := 0 + if yys64 { + for yyk64, yyv64 := range v { + if yyj64 > 0 { + r.EncodeMapEntrySeparator() + } + r.EncodeString(codecSelferC_UTF84402, string(yyk64)) + r.EncodeMapKVSeparator() + if yyv64 == nil { + r.EncodeNil() + } else { + z.F.EncSliceStringV(yyv64, false, e) + } + yyj64++ + } + r.EncodeMapEnd() + } else { + for yyk64, yyv64 := range v { + r.EncodeString(codecSelferC_UTF84402, string(yyk64)) + if yyv64 == nil { + r.EncodeNil() + } else { + z.F.EncSliceStringV(yyv64, false, e) + } + } + } +} + +func (x codecSelfer4402) dechttp_Header(v *http.Header, d *codec1978.Decoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv65 := *v + yyl65 := r.ReadMapStart() + if yyv65 == nil { + if yyl65 > 0 { + yyv65 = make(map[string][]string, yyl65) + } else { + yyv65 = make(map[string][]string) // supports indefinite-length, etc + } + *v = yyv65 + } + if yyl65 > 0 { + for yyj65 := 0; yyj65 < yyl65; yyj65++ { + var yymk65 string + if r.TryDecodeAsNil() { + yymk65 = "" + } else { + yymk65 = string(r.DecodeString()) + } + + yymv65 := yyv65[yymk65] + if r.TryDecodeAsNil() { + yymv65 = nil + } else { + yyv67 := &yymv65 + z.F.DecSliceStringX(yyv67, false, d) + } + + if yyv65 != nil { + yyv65[yymk65] = yymv65 + } + } + } else if yyl65 < 0 { + for yyj65 := 0; !r.CheckBreak(); yyj65++ { + if yyj65 > 0 { + r.ReadMapEntrySeparator() + } + var yymk65 string + if r.TryDecodeAsNil() { + yymk65 = "" + } else { + yymk65 = string(r.DecodeString()) + } + + r.ReadMapKVSeparator() + yymv65 := yyv65[yymk65] + if r.TryDecodeAsNil() { + yymv65 = nil + } else { + yyv69 := &yymv65 + z.F.DecSliceStringX(yyv69, false, d) + } + + if yyv65 != nil { + yyv65[yymk65] = yymv65 + } + } + r.ReadMapEnd() + } // else len==0: TODO: Should we clear map entries? +} + +func (x codecSelfer4402) encNodes(v Nodes, e *codec1978.Encoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperEncoder(e) + _, _, _ = h, z, r + r.EncodeArrayStart(len(v)) + yys70 := !z.EncBinary() + if yys70 { + for yyi70, yyv70 := range v { + if yyi70 > 0 { + r.EncodeArrayEntrySeparator() + } + if yyv70 == nil { + r.EncodeNil() + } else { + yyv70.CodecEncodeSelf(e) + } + } + r.EncodeArrayEnd() + } else { + for _, yyv70 := range v { + if yyv70 == nil { + r.EncodeNil() + } else { + yyv70.CodecEncodeSelf(e) + } + } + } +} + +func (x codecSelfer4402) decNodes(v *Nodes, d *codec1978.Decoder) { + var h codecSelfer4402 + z, r := codec1978.GenHelperDecoder(d) + _, _, _ = h, z, r + + yyv71 := *v + yyh71, yyl71 := z.DecSliceHelperStart() + + var yyc71 bool + if yyv71 == nil { + if yyl71 <= 0 { + yyv71 = make(Nodes, 0) + } else { + yyv71 = make(Nodes, yyl71) + } + yyc71 = true + } + + if yyl71 == 0 { + if len(yyv71) != 0 { + yyv71 = yyv71[:0] + yyc71 = true + } + } else if yyl71 > 0 { + + yyn71 := yyl71 + if yyl71 > cap(yyv71) { + yyv71 = make([]*Node, yyl71, yyl71) + yyc71 = true + + } else if yyl71 != len(yyv71) { + yyv71 = yyv71[:yyl71] + yyc71 = true + } + yyj71 := 0 + for ; yyj71 < yyn71; yyj71++ { + if r.TryDecodeAsNil() { + if yyv71[yyj71] != nil { + *yyv71[yyj71] = Node{} + } + } else { + if yyv71[yyj71] == nil { + yyv71[yyj71] = new(Node) + } + yyw72 := yyv71[yyj71] + yyw72.CodecDecodeSelf(d) + } + + } + + } else { + for yyj71 := 0; !r.CheckBreak(); yyj71++ { + if yyj71 >= len(yyv71) { + yyv71 = append(yyv71, nil) // var yyz71 *Node + yyc71 = true + } + if yyj71 > 0 { + yyh71.Sep(yyj71) + } + + if yyj71 < len(yyv71) { + if r.TryDecodeAsNil() { + if yyv71[yyj71] != nil { + *yyv71[yyj71] = Node{} + } + } else { + if yyv71[yyj71] == nil { + yyv71[yyj71] = new(Node) + } + yyw73 := yyv71[yyj71] + yyw73.CodecDecodeSelf(d) + } + + } else { + z.DecSwallow() + } + + } + yyh71.End() + } + if yyc71 { + *v = yyv71 + } +} diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response.go index 1fe9b4e87..dff20c356 100644 --- a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response.go +++ b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response.go @@ -1,10 +1,13 @@ package etcd +//go:generate codecgen -o response.generated.go response.go + import ( - "encoding/json" "net/http" "strconv" "time" + + "github.com/ugorji/go/codec" ) const ( @@ -28,6 +31,7 @@ var ( http.StatusNotFound: true, http.StatusPreconditionFailed: true, http.StatusForbidden: true, + http.StatusUnauthorized: true, } ) @@ -39,7 +43,7 @@ func (rr *RawResponse) Unmarshal() (*Response, error) { resp := new(Response) - err := json.Unmarshal(rr.Body, resp) + err := codec.NewDecoderBytes(rr.Body, new(codec.JsonHandle)).Decode(resp) if err != nil { return nil, err diff --git a/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response_test.go b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response_test.go new file mode 100644 index 000000000..23e0c56eb --- /dev/null +++ b/Godeps/_workspace/src/github.com/coreos/go-etcd/etcd/response_test.go @@ -0,0 +1,75 @@ +package etcd + +import ( + "net/http" + "reflect" + "strings" + "testing" + + "github.com/ugorji/go/codec" +) + +func createTestNode(size int) *Node { + return &Node{ + Key: strings.Repeat("a", 30), + Value: strings.Repeat("a", size), + TTL: 123456789, + ModifiedIndex: 123456, + CreatedIndex: 123456, + } +} + +func createTestNodeWithChildren(children, size int) *Node { + node := createTestNode(size) + for i := 0; i < children; i++ { + node.Nodes = append(node.Nodes, createTestNode(size)) + } + return node +} + +func createTestResponse(children, size int) *Response { + return &Response{ + Action: "aaaaa", + Node: createTestNodeWithChildren(children, size), + PrevNode: nil, + EtcdIndex: 123456, + RaftIndex: 123456, + RaftTerm: 123456, + } +} + +func benchmarkResponseUnmarshalling(b *testing.B, children, size int) { + response := createTestResponse(children, size) + + rr := RawResponse{http.StatusOK, make([]byte, 0), http.Header{}} + codec.NewEncoderBytes(&rr.Body, new(codec.JsonHandle)).Encode(response) + + b.ResetTimer() + newResponse := new(Response) + var err error + for i := 0; i < b.N; i++ { + if newResponse, err = rr.Unmarshal(); err != nil { + b.Errorf("Error: %v", err) + } + + } + if !reflect.DeepEqual(response.Node, newResponse.Node) { + b.Errorf("Unexpected difference in a parsed response: \n%+v\n%+v", response, newResponse) + } +} + +func BenchmarkSmallResponseUnmarshal(b *testing.B) { + benchmarkResponseUnmarshalling(b, 30, 20) +} + +func BenchmarkManySmallResponseUnmarshal(b *testing.B) { + benchmarkResponseUnmarshalling(b, 3000, 20) +} + +func BenchmarkMediumResponseUnmarshal(b *testing.B) { + benchmarkResponseUnmarshalling(b, 300, 200) +} + +func BenchmarkLargeResponseUnmarshal(b *testing.B) { + benchmarkResponseUnmarshalling(b, 3000, 2000) +} diff --git a/Godeps/_workspace/src/github.com/go-ldap/ldap/compare.go b/Godeps/_workspace/src/github.com/go-ldap/ldap/compare.go new file mode 100644 index 000000000..802e9cc93 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-ldap/ldap/compare.go @@ -0,0 +1,85 @@ +// 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. +// +// File contains Compare functionality +// +// https://tools.ietf.org/html/rfc4511 +// +// CompareRequest ::= [APPLICATION 14] SEQUENCE { +// entry LDAPDN, +// ava AttributeValueAssertion } +// +// AttributeValueAssertion ::= SEQUENCE { +// attributeDesc AttributeDescription, +// assertionValue AssertionValue } +// +// AttributeDescription ::= LDAPString +// -- Constrained to +// -- [RFC4512] +// +// AttributeValue ::= OCTET STRING +// + +package ldap + +import ( + "errors" + "fmt" + + "gopkg.in/asn1-ber.v1" +) + +// Compare checks to see if the attribute of the dn matches value. Returns true if it does otherwise +// false with any error that occurs if any. +func (l *Conn) Compare(dn, attribute, value string) (bool, error) { + messageID := l.nextMessageID() + packet := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "LDAP Request") + packet.AppendChild(ber.NewInteger(ber.ClassUniversal, ber.TypePrimitive, ber.TagInteger, messageID, "MessageID")) + + request := ber.Encode(ber.ClassApplication, ber.TypeConstructed, ApplicationCompareRequest, nil, "Compare Request") + request.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, dn, "DN")) + + ava := ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagSequence, nil, "AttributeValueAssertion") + ava.AppendChild(ber.NewString(ber.ClassUniversal, ber.TypePrimitive, ber.TagOctetString, attribute, "AttributeDesc")) + ava.AppendChild(ber.Encode(ber.ClassUniversal, ber.TypeConstructed, ber.TagOctetString, value, "AssertionValue")) + request.AppendChild(ava) + packet.AppendChild(request) + + l.Debug.PrintPacket(packet) + + channel, err := l.sendMessage(packet) + if err != nil { + return false, err + } + if channel == nil { + return false, NewError(ErrorNetwork, errors.New("ldap: could not send message")) + } + defer l.finishMessage(messageID) + + l.Debug.Printf("%d: waiting for response", messageID) + packet = <-channel + l.Debug.Printf("%d: got response %p", messageID, packet) + if packet == nil { + return false, NewError(ErrorNetwork, errors.New("ldap: could not retrieve message")) + } + + if l.Debug { + if err := addLDAPDescriptions(packet); err != nil { + return false, err + } + ber.PrintPacket(packet) + } + + if packet.Children[1].Tag == ApplicationCompareResponse { + resultCode, resultDescription := getLDAPResultCode(packet) + if resultCode == LDAPResultCompareTrue { + return true, nil + } else if resultCode == LDAPResultCompareFalse { + return false, nil + } else { + return false, NewError(resultCode, errors.New(resultDescription)) + } + } + return false, fmt.Errorf("Unexpected Response: %d", packet.Children[1].Tag) +} diff --git a/Godeps/_workspace/src/github.com/go-ldap/ldap/conn.go b/Godeps/_workspace/src/github.com/go-ldap/ldap/conn.go index d4b1027be..a3b0fa4e2 100644 --- a/Godeps/_workspace/src/github.com/go-ldap/ldap/conn.go +++ b/Godeps/_workspace/src/github.com/go-ldap/ldap/conn.go @@ -7,7 +7,6 @@ package ldap import ( "crypto/tls" "errors" - "flag" "fmt" "gopkg.in/asn1-ber.v1" "log" @@ -54,25 +53,17 @@ type Conn struct { messageMutex sync.Mutex } -var ldapTimeout time.Duration - -func init() { - var timeoutVar string - flag.StringVar(&timeoutVar, "ldapConnectionTimeout", "60s", "Default connection timeout for ldap") - flag.Parse() - timeout, err := time.ParseDuration(timeoutVar) - if err != nil { - ldapTimeout = 60 * time.Second - return - } - ldapTimeout = timeout - return -} +// DefaultTimeout is a package-level variable that sets the timeout value +// used for the Dial and DialTLS methods. +// +// WARNING: since this is a package-level variable, setting this value from +// multiple places will probably result in undesired behaviour. +var DefaultTimeout = 60 * time.Second // Dial connects to the given address on the given network using net.Dial // and then returns a new Conn for the connection. func Dial(network, addr string) (*Conn, error) { - c, err := net.DialTimeout(network, addr, ldapTimeout) + c, err := net.DialTimeout(network, addr, DefaultTimeout) if err != nil { return nil, NewError(ErrorNetwork, err) } @@ -84,7 +75,7 @@ func Dial(network, addr string) (*Conn, error) { // DialTLS connects to the given address on the given network using tls.Dial // and then returns a new Conn for the connection. func DialTLS(network, addr string, config *tls.Config) (*Conn, error) { - dc, err := net.DialTimeout(network, addr, ldapTimeout) + dc, err := net.DialTimeout(network, addr, DefaultTimeout) if err != nil { return nil, NewError(ErrorNetwork, err) } diff --git a/Godeps/_workspace/src/github.com/go-ldap/ldap/examples/compare/compare.go b/Godeps/_workspace/src/github.com/go-ldap/ldap/examples/compare/compare.go new file mode 100644 index 000000000..97e0a2d51 --- /dev/null +++ b/Godeps/_workspace/src/github.com/go-ldap/ldap/examples/compare/compare.go @@ -0,0 +1,39 @@ +// 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 main + +import ( + "fmt" + "log" + + "github.com/go-ldap/ldap" +) + +var ( + ldapServer string = "localhost" + ldapPort uint16 = 389 + user string = "*" + passwd string = "*" + dn string = "uid=*,cn=*,dc=*,dc=*" + attribute string = "uid" + value string = "username" +) + +func main() { + l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ldapServer, ldapPort)) + if err != nil { + log.Fatalf("ERROR: %s\n", err.Error()) + } + defer l.Close() + // l.Debug = true + + err = l.Bind(user, passwd) + if err != nil { + log.Printf("ERROR: Cannot bind: %s\n", err.Error()) + return + } + + fmt.Println(l.Compare(dn, attribute, value)) +} diff --git a/Godeps/_workspace/src/github.com/go-ldap/ldap/ldap_test.go b/Godeps/_workspace/src/github.com/go-ldap/ldap/ldap_test.go index d6211bdc3..e9933f99a 100644 --- a/Godeps/_workspace/src/github.com/go-ldap/ldap/ldap_test.go +++ b/Godeps/_workspace/src/github.com/go-ldap/ldap/ldap_test.go @@ -224,3 +224,24 @@ func TestEscapeFilter(t *testing.T) { t.Errorf("Got %s, expected %s", want, got) } } + +func TestCompare(t *testing.T) { + fmt.Printf("TestCompare: starting...\n") + l, err := Dial("tcp", fmt.Sprintf("%s:%d", ldapServer, ldapPort)) + if err != nil { + t.Fatal(err.Error()) + } + defer l.Close() + + dn := "cn=math mich,ou=User Groups,ou=Groups,dc=umich,dc=edu" + attribute := "cn" + value := "math mich" + + sr, err := l.Compare(dn, attribute, value) + if err != nil { + t.Errorf(err.Error()) + return + } + + fmt.Printf("TestCompare: -> num of entries = %d\n", sr) +} diff --git a/Godeps/_workspace/src/github.com/go-ldap/ldap/todo b/Godeps/_workspace/src/github.com/go-ldap/ldap/todo deleted file mode 100644 index 4a7be3d26..000000000 --- a/Godeps/_workspace/src/github.com/go-ldap/ldap/todo +++ /dev/null @@ -1,19 +0,0 @@ -"" => [] -sep is always , -multivalue is + - -type=value - -type is numericoid or keystring: - keystring = leadkeychar *keychar - leadkeychar = ALPHA - keychar = ALPHA / DIGIT / HYPHEN - numericoid = number 1*( DOT number ) - -example oid: -givenname = 2.5.4.42 - - If the AttributeType is of the dotted-decimal form, the - AttributeValue is represented by an number sign ('#' U+0023) - character followed by the hexadecimal encoding of each of the octets - of the BER encoding of the X.500 AttributeValue. diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/AUTHORS b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/AUTHORS index 2a7db63ee..6fc4c6f7b 100644 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/AUTHORS +++ b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/AUTHORS @@ -23,6 +23,7 @@ Henri Yandell INADA Naoki James Harr Jian Zhen +Joshua Prunier Julien Schmidt Kamil Dziedzic Leonardo YongUk Kim @@ -31,6 +32,8 @@ Luke Scott Michael Woolnough Nicola Peduzzi Runrioter Wung +Soroush Pour +Stan Putrya Xiaobing Jiang Xiuming Chen diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md index 8c76711cd..6a2bb2ca3 100644 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md +++ b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/README.md @@ -123,6 +123,16 @@ Default: false `allowAllFiles=true` disables the file Whitelist for `LOAD DATA LOCAL INFILE` and allows *all* files. [*Might be insecure!*](http://dev.mysql.com/doc/refman/5.7/en/load-data-local.html) +##### `allowCleartextPasswords` + +``` +Type: bool +Valid Values: true, false +Default: false +``` + +`allowCleartextPasswords=true` allows using the [cleartext client side plugin](http://dev.mysql.com/doc/en/cleartext-authentication-plugin.html) if required by an account, such as one defined with the [PAM authentication plugin](http://dev.mysql.com/doc/en/pam-authentication-plugin.html). Sending passwords in clear text may be a security problem in some configurations. To avoid problems if there is any possibility that the password would be intercepted, clients should connect to MySQL Server using a method that protects the password. Possibilities include [TLS / SSL](#tls), IPsec, or a private network. + ##### `allowOldPasswords` ``` @@ -205,6 +215,8 @@ Default: UTC Sets the location for time.Time values (when using `parseTime=true`). *"Local"* sets the system's location. See [time.LoadLocation](http://golang.org/pkg/time/#LoadLocation) for details. +Note that this sets the location for time.Time values but does not change MySQL's [time_zone setting](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html). For that see the [time_zone system variable](#system-variables), which can also be set as a DSN parameter. + Please keep in mind, that param values must be [url.QueryEscape](http://golang.org/pkg/net/url/#QueryEscape)'ed. Alternatively you can manually replace the `/` with `%2F`. For example `US/Pacific` would be `loc=US%2FPacific`. @@ -257,7 +269,7 @@ Default: false All other parameters are interpreted as system variables: * `autocommit`: `"SET autocommit="` - * `time_zone`: `"SET time_zone="` + * [`time_zone`](https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html): `"SET time_zone="` * [`tx_isolation`](https://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_tx_isolation): `"SET tx_isolation="` * `param`: `"SET ="` diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/connection.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/connection.go index a6d39bec9..caaae013f 100644 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/connection.go +++ b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/connection.go @@ -34,21 +34,22 @@ type mysqlConn struct { } type config struct { - user string - passwd string - net string - addr string - dbname string - params map[string]string - loc *time.Location - tls *tls.Config - timeout time.Duration - collation uint8 - allowAllFiles bool - allowOldPasswords bool - clientFoundRows bool - columnsWithAlias bool - interpolateParams bool + user string + passwd string + net string + addr string + dbname string + params map[string]string + loc *time.Location + tls *tls.Config + timeout time.Duration + collation uint8 + allowAllFiles bool + allowOldPasswords bool + allowCleartextPasswords bool + clientFoundRows bool + columnsWithAlias bool + interpolateParams bool } // Handles parameters set in DSN after the connection is established diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/const.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/const.go index baa81f022..dddc12908 100644 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/const.go +++ b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/const.go @@ -24,6 +24,7 @@ const ( iERR byte = 0xff ) +// https://dev.mysql.com/doc/internals/en/capability-flags.html#packet-Protocol::CapabilityFlags type clientFlag uint32 const ( @@ -45,6 +46,13 @@ const ( clientSecureConn clientMultiStatements clientMultiResults + clientPSMultiResults + clientPluginAuth + clientConnectAttrs + clientPluginAuthLenEncClientData + clientCanHandleExpiredPasswords + clientSessionTrack + clientDeprecateEOF ) const ( @@ -78,6 +86,7 @@ const ( comStmtFetch ) +// https://dev.mysql.com/doc/internals/en/com-query-response.html#packet-Protocol::ColumnType const ( fieldTypeDecimal byte = iota fieldTypeTiny @@ -132,7 +141,6 @@ const ( ) // http://dev.mysql.com/doc/internals/en/status-flags.html - type statusFlag uint16 const ( diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver.go index 3cbbe6031..d310624ad 100644 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver.go +++ b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver.go @@ -107,6 +107,15 @@ func (d MySQLDriver) Open(dsn string) (driver.Conn, error) { mc.Close() return nil, err } + } else if mc.cfg != nil && mc.cfg.allowCleartextPasswords && err == ErrCleartextPassword { + if err = mc.writeClearAuthPacket(); err != nil { + mc.Close() + return nil, err + } + if err = mc.readResultOK(); err != nil { + mc.Close() + return nil, err + } } else { mc.Close() return nil, err diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go index bda62eebc..cb0d5f5ec 100644 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go +++ b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/driver_test.go @@ -780,6 +780,49 @@ func TestNULL(t *testing.T) { }) } +func TestUint64(t *testing.T) { + const ( + u0 = uint64(0) + uall = ^u0 + uhigh = uall >> 1 + utop = ^uhigh + s0 = int64(0) + sall = ^s0 + shigh = int64(uhigh) + stop = ^shigh + ) + runTests(t, dsn, func(dbt *DBTest) { + stmt, err := dbt.db.Prepare(`SELECT ?, ?, ? ,?, ?, ?, ?, ?`) + if err != nil { + dbt.Fatal(err) + } + defer stmt.Close() + row := stmt.QueryRow( + u0, uhigh, utop, uall, + s0, shigh, stop, sall, + ) + + var ua, ub, uc, ud uint64 + var sa, sb, sc, sd int64 + + err = row.Scan(&ua, &ub, &uc, &ud, &sa, &sb, &sc, &sd) + if err != nil { + dbt.Fatal(err) + } + switch { + case ua != u0, + ub != uhigh, + uc != utop, + ud != uall, + sa != s0, + sb != shigh, + sc != stop, + sd != sall: + dbt.Fatal("Unexpected result value") + } + }) +} + func TestLongData(t *testing.T) { runTests(t, dsn, func(dbt *DBTest) { var maxAllowedPacketSize int diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors.go index 97d7b3996..44cf30db6 100644 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors.go +++ b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/errors.go @@ -19,15 +19,17 @@ import ( // Various errors the driver might return. Can change between driver versions. var ( - ErrInvalidConn = errors.New("Invalid Connection") - ErrMalformPkt = errors.New("Malformed Packet") - ErrNoTLS = errors.New("TLS encryption requested but server does not support TLS") - ErrOldPassword = errors.New("This server only supports the insecure old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords") - ErrOldProtocol = errors.New("MySQL-Server does not support required Protocol 41+") - ErrPktSync = errors.New("Commands out of sync. You can't run this command now") - ErrPktSyncMul = errors.New("Commands out of sync. Did you run multiple statements at once?") - ErrPktTooLarge = errors.New("Packet for query is too large. You can change this value on the server by adjusting the 'max_allowed_packet' variable.") - ErrBusyBuffer = errors.New("Busy buffer") + ErrInvalidConn = errors.New("Invalid Connection") + ErrMalformPkt = errors.New("Malformed Packet") + ErrNoTLS = errors.New("TLS encryption requested but server does not support TLS") + ErrOldPassword = errors.New("This user requires old password authentication. If you still want to use it, please add 'allowOldPasswords=1' to your DSN. See also https://github.com/go-sql-driver/mysql/wiki/old_passwords") + ErrCleartextPassword = errors.New("This user requires clear text authentication. If you still want to use it, please add 'allowCleartextPasswords=1' to your DSN.") + ErrUnknownPlugin = errors.New("The authentication plugin is not supported.") + ErrOldProtocol = errors.New("MySQL-Server does not support required Protocol 41+") + ErrPktSync = errors.New("Commands out of sync. You can't run this command now") + ErrPktSyncMul = errors.New("Commands out of sync. Did you run multiple statements at once?") + ErrPktTooLarge = errors.New("Packet for query is too large. You can change this value on the server by adjusting the 'max_allowed_packet' variable.") + ErrBusyBuffer = errors.New("Busy buffer") ) var errLog Logger = log.New(os.Stderr, "[MySQL] ", log.Ldate|log.Ltime|log.Lshortfile) diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/packets.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/packets.go index 290a3887a..14395bf9a 100644 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/packets.go +++ b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/packets.go @@ -196,7 +196,11 @@ func (mc *mysqlConn) readInitPacket() ([]byte, error) { // return //} //return ErrMalformPkt - return cipher, nil + + // make a memory safe copy of the cipher slice + var b [20]byte + copy(b[:], cipher) + return b[:], nil } // make a memory safe copy of the cipher slice @@ -214,6 +218,7 @@ func (mc *mysqlConn) writeAuthPacket(cipher []byte) error { clientLongPassword | clientTransactions | clientLocalFiles | + clientPluginAuth | mc.flags&clientLongFlag if mc.cfg.clientFoundRows { @@ -228,7 +233,7 @@ func (mc *mysqlConn) writeAuthPacket(cipher []byte) error { // User Password scrambleBuff := scramblePassword(cipher, []byte(mc.cfg.passwd)) - pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.user) + 1 + 1 + len(scrambleBuff) + pktLen := 4 + 4 + 1 + 23 + len(mc.cfg.user) + 1 + 1 + len(scrambleBuff) + 21 + 1 // To specify a db name if n := len(mc.cfg.dbname); n > 0 { @@ -294,8 +299,13 @@ func (mc *mysqlConn) writeAuthPacket(cipher []byte) error { if len(mc.cfg.dbname) > 0 { pos += copy(data[pos:], mc.cfg.dbname) data[pos] = 0x00 + pos++ } + // Assume native client during response + pos += copy(data[pos:], "mysql_native_password") + data[pos] = 0x00 + // Send Auth packet return mc.writePacket(data) } @@ -306,7 +316,7 @@ func (mc *mysqlConn) writeOldAuthPacket(cipher []byte) error { // User password scrambleBuff := scrambleOldPassword(cipher, []byte(mc.cfg.passwd)) - // Calculate the packet lenght and add a tailing 0 + // Calculate the packet length and add a tailing 0 pktLen := len(scrambleBuff) + 1 data := mc.buf.takeSmallBuffer(4 + pktLen) if data == nil { @@ -322,6 +332,25 @@ func (mc *mysqlConn) writeOldAuthPacket(cipher []byte) error { return mc.writePacket(data) } +// Client clear text authentication packet +// http://dev.mysql.com/doc/internals/en/connection-phase-packets.html#packet-Protocol::AuthSwitchResponse +func (mc *mysqlConn) writeClearAuthPacket() error { + // Calculate the packet length and add a tailing 0 + pktLen := len(mc.cfg.passwd) + 1 + data := mc.buf.takeSmallBuffer(4 + pktLen) + if data == nil { + // can not take the buffer. Something must be wrong with the connection + errLog.Print(ErrBusyBuffer) + return driver.ErrBadConn + } + + // Add the clear password [null terminated string] + copy(data[4:], mc.cfg.passwd) + data[4+pktLen-1] = 0x00 + + return mc.writePacket(data) +} + /****************************************************************************** * Command Packets * ******************************************************************************/ @@ -405,8 +434,20 @@ func (mc *mysqlConn) readResultOK() error { return mc.handleOkPacket(data) case iEOF: - // someone is using old_passwords - return ErrOldPassword + if len(data) > 1 { + plugin := string(data[1:bytes.IndexByte(data, 0x00)]) + if plugin == "mysql_old_password" { + // using old_passwords + return ErrOldPassword + } else if plugin == "mysql_clear_password" { + // using clear text password + return ErrCleartextPassword + } else { + return ErrUnknownPlugin + } + } else { + return ErrOldPassword + } default: // Error otherwise return mc.handleErrorPacket(data) diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/statement.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/statement.go index 142ef5416..6e869b340 100644 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/statement.go +++ b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/statement.go @@ -10,6 +10,9 @@ package mysql import ( "database/sql/driver" + "fmt" + "reflect" + "strconv" ) type mysqlStmt struct { @@ -34,6 +37,10 @@ func (stmt *mysqlStmt) NumInput() int { return stmt.paramCount } +func (stmt *mysqlStmt) ColumnConverter(idx int) driver.ValueConverter { + return converter{} +} + func (stmt *mysqlStmt) Exec(args []driver.Value) (driver.Result, error) { if stmt.mc.netConn == nil { errLog.Print(ErrInvalidConn) @@ -110,3 +117,34 @@ func (stmt *mysqlStmt) Query(args []driver.Value) (driver.Rows, error) { return rows, err } + +type converter struct{} + +func (c converter) ConvertValue(v interface{}) (driver.Value, error) { + if driver.IsValue(v) { + return v, nil + } + + rv := reflect.ValueOf(v) + switch rv.Kind() { + case reflect.Ptr: + // indirect pointers + if rv.IsNil() { + return nil, nil + } + return c.ConvertValue(rv.Elem().Interface()) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return rv.Int(), nil + case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32: + return int64(rv.Uint()), nil + case reflect.Uint64: + u64 := rv.Uint() + if u64 >= 1<<63 { + return strconv.FormatUint(u64, 10), nil + } + return int64(u64), nil + case reflect.Float32, reflect.Float64: + return rv.Float(), nil + } + return nil, fmt.Errorf("unsupported type %T, a %s", v, rv.Kind()) +} diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils.go index 6693d2970..6a26ad129 100644 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils.go +++ b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils.go @@ -80,8 +80,6 @@ func parseDSN(dsn string) (cfg *config, err error) { collation: defaultCollation, } - // TODO: use strings.IndexByte when we can depend on Go 1.2 - // [user[:password]@][net[(addr)]]/dbname[?param1=value1¶mN=valueN] // Find the last '/' (since the password or the net addr might contain a '/') foundSlash := false @@ -201,6 +199,14 @@ func parseDSNParams(cfg *config, params string) (err error) { return fmt.Errorf("Invalid Bool value: %s", value) } + // Use cleartext authentication mode (MySQL 5.5.10+) + case "allowCleartextPasswords": + var isBool bool + cfg.allowCleartextPasswords, isBool = readBool(value) + if !isBool { + return fmt.Errorf("Invalid Bool value: %s", value) + } + // Use old authentication mode (pre MySQL 4.1) case "allowOldPasswords": var isBool bool @@ -771,6 +777,10 @@ func skipLengthEncodedString(b []byte) (int, error) { // returns the number read, whether the value is NULL and the number of bytes read func readLengthEncodedInteger(b []byte) (uint64, bool, int) { + // See issue #349 + if len(b) == 0 { + return 0, true, 1 + } switch b[0] { // 251: NULL diff --git a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go index adb8dcbd1..79fbdd1eb 100644 --- a/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go +++ b/Godeps/_workspace/src/github.com/go-sql-driver/mysql/utils_test.go @@ -22,19 +22,19 @@ var testDSNs = []struct { out string loc *time.Location }{ - {"username:password@protocol(address)/dbname?param=value", "&{user:username passwd:password net:protocol addr:address dbname:dbname params:map[param:value] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"username:password@protocol(address)/dbname?param=value&columnsWithAlias=true", "&{user:username passwd:password net:protocol addr:address dbname:dbname params:map[param:value] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:true interpolateParams:false}", time.UTC}, - {"user@unix(/path/to/socket)/dbname?charset=utf8", "&{user:user passwd: net:unix addr:/path/to/socket dbname:dbname params:map[charset:utf8] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"user:password@tcp(localhost:5555)/dbname?charset=utf8&tls=true", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"user:password@tcp(localhost:5555)/dbname?charset=utf8mb4,utf8&tls=skip-verify", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8mb4,utf8] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"user:password@/dbname?loc=UTC&timeout=30s&allowAllFiles=1&clientFoundRows=true&allowOldPasswords=TRUE&collation=utf8mb4_unicode_ci", "&{user:user passwd:password net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls: timeout:30000000000 collation:224 allowAllFiles:true allowOldPasswords:true clientFoundRows:true columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"user:p@ss(word)@tcp([de:ad:be:ef::ca:fe]:80)/dbname?loc=Local", "&{user:user passwd:p@ss(word) net:tcp addr:[de:ad:be:ef::ca:fe]:80 dbname:dbname params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.Local}, - {"/dbname", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"@/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"user:p@/ssword@/", "&{user:user passwd:p@/ssword net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, - {"unix/?arg=%2Fsome%2Fpath.ext", "&{user: passwd: net:unix addr:/tmp/mysql.sock dbname: params:map[arg:/some/path.ext] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, + {"username:password@protocol(address)/dbname?param=value", "&{user:username passwd:password net:protocol addr:address dbname:dbname params:map[param:value] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, + {"username:password@protocol(address)/dbname?param=value&columnsWithAlias=true", "&{user:username passwd:password net:protocol addr:address dbname:dbname params:map[param:value] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:true interpolateParams:false}", time.UTC}, + {"user@unix(/path/to/socket)/dbname?charset=utf8", "&{user:user passwd: net:unix addr:/path/to/socket dbname:dbname params:map[charset:utf8] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, + {"user:password@tcp(localhost:5555)/dbname?charset=utf8&tls=true", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, + {"user:password@tcp(localhost:5555)/dbname?charset=utf8mb4,utf8&tls=skip-verify", "&{user:user passwd:password net:tcp addr:localhost:5555 dbname:dbname params:map[charset:utf8mb4,utf8] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, + {"user:password@/dbname?loc=UTC&timeout=30s&allowAllFiles=1&clientFoundRows=true&allowOldPasswords=TRUE&collation=utf8mb4_unicode_ci", "&{user:user passwd:password net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls: timeout:30000000000 collation:224 allowAllFiles:true allowOldPasswords:true allowCleartextPasswords:false clientFoundRows:true columnsWithAlias:false interpolateParams:false}", time.UTC}, + {"user:p@ss(word)@tcp([de:ad:be:ef::ca:fe]:80)/dbname?loc=Local", "&{user:user passwd:p@ss(word) net:tcp addr:[de:ad:be:ef::ca:fe]:80 dbname:dbname params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.Local}, + {"/dbname", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname:dbname params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, + {"@/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, + {"/", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, + {"", "&{user: passwd: net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, + {"user:p@/ssword@/", "&{user:user passwd:p@/ssword net:tcp addr:127.0.0.1:3306 dbname: params:map[] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, + {"unix/?arg=%2Fsome%2Fpath.ext", "&{user: passwd: net:unix addr:/tmp/mysql.sock dbname: params:map[arg:/some/path.ext] loc:%p tls: timeout:0 collation:33 allowAllFiles:false allowOldPasswords:false allowCleartextPasswords:false clientFoundRows:false columnsWithAlias:false interpolateParams:false}", time.UTC}, } func TestDSNParser(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/activity_star.go b/Godeps/_workspace/src/github.com/google/go-github/github/activity_star.go index 982f24d71..fac4f41d2 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/activity_star.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/activity_star.go @@ -7,6 +7,12 @@ package github import "fmt" +// StarredRepository is returned by ListStarred. +type StarredRepository struct { + StarredAt *Timestamp `json:"starred_at,omitempty"` + Repository *Repository `json:"repo,omitempty"` +} + // ListStargazers lists people who have starred the specified repo. // // GitHub API Docs: https://developer.github.com/v3/activity/starring/#list-stargazers @@ -49,7 +55,7 @@ type ActivityListStarredOptions struct { // will list the starred repositories for the authenticated user. // // GitHub API docs: http://developer.github.com/v3/activity/starring/#list-repositories-being-starred -func (s *ActivityService) ListStarred(user string, opt *ActivityListStarredOptions) ([]Repository, *Response, error) { +func (s *ActivityService) ListStarred(user string, opt *ActivityListStarredOptions) ([]StarredRepository, *Response, error) { var u string if user != "" { u = fmt.Sprintf("users/%v/starred", user) @@ -66,7 +72,10 @@ func (s *ActivityService) ListStarred(user string, opt *ActivityListStarredOptio return nil, nil, err } - repos := new([]Repository) + // TODO: remove custom Accept header when this API fully launches + req.Header.Set("Accept", mediaTypeStarringPreview) + + repos := new([]StarredRepository) resp, err := s.client.Do(req, repos) if err != nil { return nil, resp, err diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/activity_star_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/activity_star_test.go index ae33b93cf..eb2c4055e 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/activity_star_test.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/activity_star_test.go @@ -10,6 +10,7 @@ import ( "net/http" "reflect" "testing" + "time" ) func TestActivityService_ListStargazers(t *testing.T) { @@ -42,7 +43,8 @@ func TestActivityService_ListStarred_authenticatedUser(t *testing.T) { mux.HandleFunc("/user/starred", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") - fmt.Fprint(w, `[{"id":1}]`) + testHeader(t, r, "Accept", mediaTypeStarringPreview) + fmt.Fprint(w, `[{"starred_at":"2002-02-10T15:30:00Z","repo":{"id":1}}]`) }) repos, _, err := client.Activity.ListStarred("", nil) @@ -50,7 +52,7 @@ func TestActivityService_ListStarred_authenticatedUser(t *testing.T) { t.Errorf("Activity.ListStarred returned error: %v", err) } - want := []Repository{{ID: Int(1)}} + want := []StarredRepository{{StarredAt: &Timestamp{time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC)}, Repository: &Repository{ID: Int(1)}}} if !reflect.DeepEqual(repos, want) { t.Errorf("Activity.ListStarred returned %+v, want %+v", repos, want) } @@ -62,12 +64,13 @@ func TestActivityService_ListStarred_specifiedUser(t *testing.T) { mux.HandleFunc("/users/u/starred", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") + testHeader(t, r, "Accept", mediaTypeStarringPreview) testFormValues(t, r, values{ "sort": "created", "direction": "asc", "page": "2", }) - fmt.Fprint(w, `[{"id":2}]`) + fmt.Fprint(w, `[{"starred_at":"2002-02-10T15:30:00Z","repo":{"id":2}}]`) }) opt := &ActivityListStarredOptions{"created", "asc", ListOptions{Page: 2}} @@ -76,7 +79,7 @@ func TestActivityService_ListStarred_specifiedUser(t *testing.T) { t.Errorf("Activity.ListStarred returned error: %v", err) } - want := []Repository{{ID: Int(2)}} + want := []StarredRepository{{StarredAt: &Timestamp{time.Date(2002, time.February, 10, 15, 30, 0, 0, time.UTC)}, Repository: &Repository{ID: Int(2)}}} if !reflect.DeepEqual(repos, want) { t.Errorf("Activity.ListStarred returned %+v, want %+v", repos, want) } diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/doc.go b/Godeps/_workspace/src/github.com/google/go-github/github/doc.go index 9e48242d2..b4ac8e640 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/doc.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/doc.go @@ -35,21 +35,10 @@ use it with the oauth2 library using: import "golang.org/x/oauth2" - // tokenSource is an oauth2.TokenSource which returns a static access token - type tokenSource struct { - token *oauth2.Token - } - - // Token implements the oauth2.TokenSource interface - func (t *tokenSource) Token() (*oauth2.Token, error){ - return t.token, nil - } - func main() { - ts := &tokenSource{ + ts := oauth2.StaticTokenSource( &oauth2.Token{AccessToken: "... your access token ..."}, - } - + ) tc := oauth2.NewClient(oauth2.NoContext, ts) client := github.NewClient(tc) diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/gists.go b/Godeps/_workspace/src/github.com/google/go-github/github/gists.go index 20c3536c1..14bf5dc50 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/gists.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/gists.go @@ -157,6 +157,24 @@ func (s *GistsService) Get(id string) (*Gist, *Response, error) { return gist, resp, err } +// Get a specific revision of a gist. +// +// GitHub API docs: https://developer.github.com/v3/gists/#get-a-specific-revision-of-a-gist +func (s *GistsService) GetRevision(id, sha string) (*Gist, *Response, error) { + u := fmt.Sprintf("gists/%v/%v", id, sha) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + gist := new(Gist) + resp, err := s.client.Do(req, gist) + if err != nil { + return nil, resp, err + } + + return gist, resp, err +} + // Create a gist for authenticated user. // // GitHub API docs: http://developer.github.com/v3/gists/#create-a-gist diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/gists_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/gists_test.go index bd755da0d..573120129 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/gists_test.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/gists_test.go @@ -146,6 +146,32 @@ func TestGistsService_Get_invalidID(t *testing.T) { testURLParseError(t, err) } +func TestGistsService_GetRevision(t *testing.T) { + setup() + defer teardown() + + mux.HandleFunc("/gists/1/s", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + fmt.Fprint(w, `{"id": "1"}`) + }) + + gist, _, err := client.Gists.GetRevision("1", "s") + + if err != nil { + t.Errorf("Gists.Get returned error: %v", err) + } + + want := &Gist{ID: String("1")} + if !reflect.DeepEqual(gist, want) { + t.Errorf("Gists.Get returned %+v, want %+v", gist, want) + } +} + +func TestGistsService_GetRevision_invalidID(t *testing.T) { + _, _, err := client.Gists.GetRevision("%", "%") + testURLParseError(t, err) +} + func TestGistsService_Create(t *testing.T) { setup() defer teardown() diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/github.go b/Godeps/_workspace/src/github.com/google/go-github/github/github.go index 52699eb8c..3aa643cb6 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/github.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/github.go @@ -37,11 +37,14 @@ const ( // Media Type values to access preview APIs - // https://developer.github.com/changes/2014-08-05-team-memberships-api/ - mediaTypeMembershipPreview = "application/vnd.github.the-wasp-preview+json" + // https://developer.github.com/changes/2015-03-09-licenses-api/ + mediaTypeLicensesPreview = "application/vnd.github.drax-preview+json" - // https://developer.github.com/changes/2014-01-09-preview-the-new-deployments-api/ - mediaTypeDeploymentPreview = "application/vnd.github.cannonball-preview+json" + // https://developer.github.com/changes/2014-12-09-new-attributes-for-stars-api/ + mediaTypeStarringPreview = "application/vnd.github.v3.star+json" + + // https://developer.github.com/changes/2014-12-08-organization-permissions-api-preview/ + mediaTypeOrganizationsPreview = "application/vnd.github.moondragon+json" ) // A Client manages communication with the GitHub API. @@ -77,6 +80,7 @@ type Client struct { Repositories *RepositoriesService Search *SearchService Users *UsersService + Licenses *LicensesService } // ListOptions specifies the optional parameters to various List methods that @@ -138,6 +142,7 @@ func NewClient(httpClient *http.Client) *Client { c.Repositories = &RepositoriesService{client: c} c.Search = &SearchService{client: c} c.Users = &UsersService{client: c} + c.Licenses = &LicensesService{client: c} return c } @@ -219,7 +224,7 @@ type Response struct { Rate } -// newResponse creats a new Response for the provided http.Response. +// newResponse creates a new Response for the provided http.Response. func newResponse(r *http.Response) *Response { response := &Response{Response: r} response.populatePageValues() @@ -333,10 +338,24 @@ type ErrorResponse struct { func (r *ErrorResponse) Error() string { return fmt.Sprintf("%v %v: %d %v %+v", - r.Response.Request.Method, r.Response.Request.URL, + r.Response.Request.Method, sanitizeURL(r.Response.Request.URL), r.Response.StatusCode, r.Message, r.Errors) } +// sanitizeURL redacts the client_id and client_secret tokens from the URL which +// may be exposed to the user, specifically in the ErrorResponse error message. +func sanitizeURL(uri *url.URL) *url.URL { + if uri == nil { + return nil + } + params := uri.Query() + if len(params.Get("client_secret")) > 0 { + params.Set("client_secret", "REDACTED") + uri.RawQuery = params.Encode() + } + return uri +} + /* An Error reports more details on an individual error in an ErrorResponse. These are the possible validation error codes: diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/github_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/github_test.go index 0fb2c18a1..05c817b65 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/github_test.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/github_test.go @@ -430,6 +430,25 @@ func TestDo_rateLimit_errorResponse(t *testing.T) { } } +func TestSanitizeURL(t *testing.T) { + tests := []struct { + in, want string + }{ + {"/?a=b", "/?a=b"}, + {"/?a=b&client_secret=secret", "/?a=b&client_secret=REDACTED"}, + {"/?a=b&client_id=id&client_secret=secret", "/?a=b&client_id=id&client_secret=REDACTED"}, + } + + for _, tt := range tests { + inURL, _ := url.Parse(tt.in) + want, _ := url.Parse(tt.want) + + if got := sanitizeURL(inURL); !reflect.DeepEqual(got, want) { + t.Errorf("sanitizeURL(%v) returned %v, want %v", tt.in, got, want) + } + } +} + func TestCheckResponse(t *testing.T) { res := &http.Response{ Request: &http.Request{}, diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/issues.go b/Godeps/_workspace/src/github.com/google/go-github/github/issues.go index f92df6b56..05f5477f9 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/issues.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/issues.go @@ -49,12 +49,12 @@ func (i Issue) String() string { // It is separate from Issue above because otherwise Labels // and Assignee fail to serialize to the correct JSON. type IssueRequest struct { - Title *string `json:"title,omitempty"` - Body *string `json:"body,omitempty"` - Labels []string `json:"labels,omitempty"` - Assignee *string `json:"assignee,omitempty"` - State *string `json:"state,omitempty"` - Milestone *int `json:"milestone,omitempty"` + Title *string `json:"title,omitempty"` + Body *string `json:"body,omitempty"` + Labels *[]string `json:"labels,omitempty"` + Assignee *string `json:"assignee,omitempty"` + State *string `json:"state,omitempty"` + Milestone *int `json:"milestone,omitempty"` } // IssueListOptions specifies the optional parameters to the IssuesService.List @@ -72,7 +72,7 @@ type IssueListOptions struct { Labels []string `url:"labels,comma,omitempty"` // Sort specifies how to sort issues. Possible values are: created, updated, - // and comments. Default value is "assigned". + // and comments. Default value is "created". Sort string `url:"sort,omitempty"` // Direction in which to sort issues. Possible values are: asc, desc. @@ -166,7 +166,7 @@ type IssueListByRepoOptions struct { Labels []string `url:"labels,omitempty,comma"` // Sort specifies how to sort issues. Possible values are: created, updated, - // and comments. Default value is "assigned". + // and comments. Default value is "created". Sort string `url:"sort,omitempty"` // Direction in which to sort issues. Possible values are: asc, desc. diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/issues_labels.go b/Godeps/_workspace/src/github.com/google/go-github/github/issues_labels.go index 5ad25c1bb..88f9f3ff9 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/issues_labels.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/issues_labels.go @@ -7,7 +7,7 @@ package github import "fmt" -// Label represents a GitHib label on an Issue +// Label represents a GitHub label on an Issue type Label struct { URL *string `json:"url,omitempty"` Name *string `json:"name,omitempty"` diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/issues_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/issues_test.go index 090cf1b1a..f69efd399 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/issues_test.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/issues_test.go @@ -176,7 +176,7 @@ func TestIssuesService_Create(t *testing.T) { Title: String("t"), Body: String("b"), Assignee: String("a"), - Labels: []string{"l1", "l2"}, + Labels: &[]string{"l1", "l2"}, } mux.HandleFunc("/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) { diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/licenses.go b/Godeps/_workspace/src/github.com/google/go-github/github/licenses.go new file mode 100644 index 000000000..d2a5a5066 --- /dev/null +++ b/Godeps/_workspace/src/github.com/google/go-github/github/licenses.go @@ -0,0 +1,81 @@ +// Copyright 2013 The go-github 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 github + +import "fmt" + +// LicensesService handles communication with the license related +// methods of the GitHub API. +// +// GitHub API docs: http://developer.github.com/v3/pulls/ +type LicensesService struct { + client *Client +} + +// License represents an open source license. +type License struct { + Key *string `json:"key,omitempty"` + Name *string `json:"name,omitempty"` + URL *string `json:"url,omitempty"` + + HTMLURL *string `json:"html_url",omitempty` + Featured *bool `json:"featured,omitempty"` + Description *string `json:"description,omitempty"` + Category *string `json:"category,omitempty"` + Implementation *string `json:"implementation,omitempty"` + Required *[]string `json:"required,omitempty"` + Permitted *[]string `json:"permitted,omitempty"` + Forbidden *[]string `json:"forbidden,omitempty"` + Body *string `json:"body,omitempty"` +} + +func (l License) String() string { + return Stringify(l) +} + +// List popular open source licenses. +// +// GitHub API docs: https://developer.github.com/v3/licenses/#list-all-licenses +func (s *LicensesService) List() ([]License, *Response, error) { + req, err := s.client.NewRequest("GET", "licenses", nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches + req.Header.Set("Accept", mediaTypeLicensesPreview) + + licenses := new([]License) + resp, err := s.client.Do(req, licenses) + if err != nil { + return nil, resp, err + } + + return *licenses, resp, err +} + +// Fetch extended metadata for one license. +// +// GitHub API docs: https://developer.github.com/v3/licenses/#get-an-individual-license +func (s *LicensesService) Get(licenseName string) (*License, *Response, error) { + u := fmt.Sprintf("licenses/%s", licenseName) + + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches + req.Header.Set("Accept", mediaTypeLicensesPreview) + + license := new(License) + resp, err := s.client.Do(req, license) + if err != nil { + return nil, resp, err + } + + return license, resp, err +} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/licenses_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/licenses_test.go new file mode 100644 index 000000000..72f6633b2 --- /dev/null +++ b/Godeps/_workspace/src/github.com/google/go-github/github/licenses_test.go @@ -0,0 +1,64 @@ +// Copyright 2013 The go-github 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 github + +import ( + "fmt" + "net/http" + "reflect" + "testing" +) + +func TestLicensesService_List(t *testing.T) { + setup() + defer teardown() + + mux.HandleFunc("/licenses", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + testHeader(t, r, "Accept", mediaTypeLicensesPreview) + fmt.Fprint(w, `[{"key":"mit","name":"MIT","url":"https://api.github.com/licenses/mit"}]`) + }) + + licenses, _, err := client.Licenses.List() + if err != nil { + t.Errorf("Licenses.List returned error: %v", err) + } + + want := []License{License{ + Key: String("mit"), + Name: String("MIT"), + URL: String("https://api.github.com/licenses/mit"), + }} + if !reflect.DeepEqual(licenses, want) { + t.Errorf("Licenses.List returned %+v, want %+v", licenses, want) + } +} + +func TestLicensesService_Get(t *testing.T) { + setup() + defer teardown() + + mux.HandleFunc("/licenses/mit", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + testHeader(t, r, "Accept", mediaTypeLicensesPreview) + fmt.Fprint(w, `{"key":"mit","name":"MIT"}`) + }) + + license, _, err := client.Licenses.Get("mit") + if err != nil { + t.Errorf("Licenses.Get returned error: %v", err) + } + + want := &License{Key: String("mit"), Name: String("MIT")} + if !reflect.DeepEqual(license, want) { + t.Errorf("Licenses.Get returned %+v, want %+v", license, want) + } +} + +func TestLicensesService_Get_invalidTemplate(t *testing.T) { + _, _, err := client.Licenses.Get("%") + testURLParseError(t, err) +} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/misc.go b/Godeps/_workspace/src/github.com/google/go-github/github/misc.go index 4a9bb99ef..66e7f5239 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/misc.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/misc.go @@ -98,6 +98,10 @@ type APIMeta struct { // username and password, sudo mode, and two-factor authentication are // not supported on these servers.) VerifiablePasswordAuthentication *bool `json:"verifiable_password_authentication,omitempty"` + + // An array of IP addresses in CIDR format specifying the addresses + // which serve GitHub Pages websites. + Pages []string `json:"pages,omitempty"` } // APIMeta returns information about GitHub.com, the service. Or, if you access @@ -159,3 +163,35 @@ func (c *Client) Zen() (string, *Response, error) { return buf.String(), resp, nil } + +// ServiceHook represents a hook that has configuration settings, a list of +// available events, and default events. +type ServiceHook struct { + Name *string `json:"name,omitempty"` + Events []string `json:"events,omitempty"` + SupportedEvents []string `json:"supported_events,omitempty"` + Schema [][]string `json:"schema,omitempty"` +} + +func (s *ServiceHook) String() string { + return Stringify(s) +} + +// ListServiceHooks lists all of the available service hooks. +// +// GitHub API docs: https://developer.github.com/webhooks/#services +func (c *Client) ListServiceHooks() ([]ServiceHook, *Response, error) { + u := "hooks" + req, err := c.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + hooks := new([]ServiceHook) + resp, err := c.Do(req, hooks) + if err != nil { + return nil, resp, err + } + + return *hooks, resp, err +} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/misc_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/misc_test.go index 33c3db63d..8ca58d251 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/misc_test.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/misc_test.go @@ -72,7 +72,7 @@ func TestAPIMeta(t *testing.T) { mux.HandleFunc("/meta", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") - fmt.Fprint(w, `{"hooks":["h"], "git":["g"], "verifiable_password_authentication": true}`) + fmt.Fprint(w, `{"hooks":["h"], "git":["g"], "pages":["p"], "verifiable_password_authentication": true}`) }) meta, _, err := client.APIMeta() @@ -83,6 +83,7 @@ func TestAPIMeta(t *testing.T) { want := &APIMeta{ Hooks: []string{"h"}, Git: []string{"g"}, + Pages: []string{"p"}, VerifiablePasswordAuthentication: Bool(true), } if !reflect.DeepEqual(want, meta) { @@ -135,3 +136,35 @@ func TestZen(t *testing.T) { t.Errorf("Zen returned %+v, want %+v", got, want) } } + +func TestRepositoriesService_ListServiceHooks(t *testing.T) { + setup() + defer teardown() + + mux.HandleFunc("/hooks", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + fmt.Fprint(w, `[{ + "name":"n", + "events":["e"], + "supported_events":["s"], + "schema":[ + ["a", "b"] + ] + }]`) + }) + + hooks, _, err := client.Repositories.ListServiceHooks() + if err != nil { + t.Errorf("Repositories.ListHooks returned error: %v", err) + } + + want := []ServiceHook{{ + Name: String("n"), + Events: []string{"e"}, + SupportedEvents: []string{"s"}, + Schema: [][]string{{"a", "b"}}, + }} + if !reflect.DeepEqual(hooks, want) { + t.Errorf("Repositories.ListServiceHooks returned %+v, want %+v", hooks, want) + } +} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_hooks.go b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_hooks.go new file mode 100644 index 000000000..3e7ad40ff --- /dev/null +++ b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_hooks.go @@ -0,0 +1,104 @@ +// Copyright 2015 The go-github 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 github + +import "fmt" + +// ListHooks lists all Hooks for the specified organization. +// +// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#list-hooks +func (s *OrganizationsService) ListHooks(org string, opt *ListOptions) ([]Hook, *Response, error) { + u := fmt.Sprintf("orgs/%v/hooks", org) + u, err := addOptions(u, opt) + if err != nil { + return nil, nil, err + } + + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + hooks := new([]Hook) + resp, err := s.client.Do(req, hooks) + if err != nil { + return nil, resp, err + } + + return *hooks, resp, err +} + +// GetHook returns a single specified Hook. +// +// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#get-single-hook +func (s *OrganizationsService) GetHook(org string, id int) (*Hook, *Response, error) { + u := fmt.Sprintf("orgs/%v/hooks/%d", org, id) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + hook := new(Hook) + resp, err := s.client.Do(req, hook) + return hook, resp, err +} + +// CreateHook creates a Hook for the specified org. +// Name and Config are required fields. +// +// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#create-a-hook +func (s *OrganizationsService) CreateHook(org string, hook *Hook) (*Hook, *Response, error) { + u := fmt.Sprintf("orgs/%v/hooks", org) + req, err := s.client.NewRequest("POST", u, hook) + if err != nil { + return nil, nil, err + } + + h := new(Hook) + resp, err := s.client.Do(req, h) + if err != nil { + return nil, resp, err + } + + return h, resp, err +} + +// EditHook updates a specified Hook. +// +// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#edit-a-hook +func (s *OrganizationsService) EditHook(org string, id int, hook *Hook) (*Hook, *Response, error) { + u := fmt.Sprintf("orgs/%v/hooks/%d", org, id) + req, err := s.client.NewRequest("PATCH", u, hook) + if err != nil { + return nil, nil, err + } + h := new(Hook) + resp, err := s.client.Do(req, h) + return h, resp, err +} + +// PingHook triggers a 'ping' event to be sent to the Hook. +// +// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#ping-a-hook +func (s *OrganizationsService) PingHook(org string, id int) (*Response, error) { + u := fmt.Sprintf("orgs/%v/hooks/%d/pings", org, id) + req, err := s.client.NewRequest("POST", u, nil) + if err != nil { + return nil, err + } + return s.client.Do(req, nil) +} + +// DeleteHook deletes a specified Hook. +// +// GitHub API docs: https://developer.github.com/v3/orgs/hooks/#delete-a-hook +func (s *OrganizationsService) DeleteHook(org string, id int) (*Response, error) { + u := fmt.Sprintf("orgs/%v/hooks/%d", org, id) + req, err := s.client.NewRequest("DELETE", u, nil) + if err != nil { + return nil, err + } + return s.client.Do(req, nil) +} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_hooks_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_hooks_test.go new file mode 100644 index 000000000..1ebc07d5a --- /dev/null +++ b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_hooks_test.go @@ -0,0 +1,134 @@ +// Copyright 2015 The go-github 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 github + +import ( + "encoding/json" + "fmt" + "net/http" + "reflect" + "testing" +) + +func TestOrganizationsService_ListHooks(t *testing.T) { + setup() + defer teardown() + + mux.HandleFunc("/orgs/o/hooks", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + testFormValues(t, r, values{"page": "2"}) + fmt.Fprint(w, `[{"id":1}, {"id":2}]`) + }) + + opt := &ListOptions{Page: 2} + + hooks, _, err := client.Organizations.ListHooks("o", opt) + if err != nil { + t.Errorf("Organizations.ListHooks returned error: %v", err) + } + + want := []Hook{{ID: Int(1)}, {ID: Int(2)}} + if !reflect.DeepEqual(hooks, want) { + t.Errorf("Organizations.ListHooks returned %+v, want %+v", hooks, want) + } +} + +func TestOrganizationsService_ListHooks_invalidOrg(t *testing.T) { + _, _, err := client.Organizations.ListHooks("%", nil) + testURLParseError(t, err) +} + +func TestOrganizationsService_GetHook(t *testing.T) { + setup() + defer teardown() + + mux.HandleFunc("/orgs/o/hooks/1", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + fmt.Fprint(w, `{"id":1}`) + }) + + hook, _, err := client.Organizations.GetHook("o", 1) + if err != nil { + t.Errorf("Organizations.GetHook returned error: %v", err) + } + + want := &Hook{ID: Int(1)} + if !reflect.DeepEqual(hook, want) { + t.Errorf("Organizations.GetHook returned %+v, want %+v", hook, want) + } +} + +func TestOrganizationsService_GetHook_invalidOrg(t *testing.T) { + _, _, err := client.Organizations.GetHook("%", 1) + testURLParseError(t, err) +} + +func TestOrganizationsService_EditHook(t *testing.T) { + setup() + defer teardown() + + input := &Hook{Name: String("t")} + + mux.HandleFunc("/orgs/o/hooks/1", func(w http.ResponseWriter, r *http.Request) { + v := new(Hook) + json.NewDecoder(r.Body).Decode(v) + + testMethod(t, r, "PATCH") + if !reflect.DeepEqual(v, input) { + t.Errorf("Request body = %+v, want %+v", v, input) + } + + fmt.Fprint(w, `{"id":1}`) + }) + + hook, _, err := client.Organizations.EditHook("o", 1, input) + if err != nil { + t.Errorf("Organizations.EditHook returned error: %v", err) + } + + want := &Hook{ID: Int(1)} + if !reflect.DeepEqual(hook, want) { + t.Errorf("Organizations.EditHook returned %+v, want %+v", hook, want) + } +} + +func TestOrganizationsService_EditHook_invalidOrg(t *testing.T) { + _, _, err := client.Organizations.EditHook("%", 1, nil) + testURLParseError(t, err) +} + +func TestOrganizationsService_PingHook(t *testing.T) { + setup() + defer teardown() + + mux.HandleFunc("/orgs/o/hooks/1/pings", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "POST") + }) + + _, err := client.Organizations.PingHook("o", 1) + if err != nil { + t.Errorf("Organizations.PingHook returned error: %v", err) + } +} + +func TestOrganizationsService_DeleteHook(t *testing.T) { + setup() + defer teardown() + + mux.HandleFunc("/orgs/o/hooks/1", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "DELETE") + }) + + _, err := client.Organizations.DeleteHook("o", 1) + if err != nil { + t.Errorf("Organizations.DeleteHook returned error: %v", err) + } +} + +func TestOrganizationsService_DeleteHook_invalidOrg(t *testing.T) { + _, err := client.Organizations.DeleteHook("%", 1) + testURLParseError(t, err) +} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_members.go b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_members.go index ae6f57943..64dcfcc3d 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_members.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_members.go @@ -171,9 +171,6 @@ func (s *OrganizationsService) ListOrgMemberships(opt *ListOrgMembershipsOptions return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeMembershipPreview) - var memberships []Membership resp, err := s.client.Do(req, &memberships) if err != nil { @@ -194,9 +191,6 @@ func (s *OrganizationsService) GetOrgMembership(org string) (*Membership, *Respo return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeMembershipPreview) - membership := new(Membership) resp, err := s.client.Do(req, membership) if err != nil { @@ -217,9 +211,6 @@ func (s *OrganizationsService) EditOrgMembership(org string, membership *Members return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeMembershipPreview) - m := new(Membership) resp, err := s.client.Do(req, m) if err != nil { diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_members_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_members_test.go index 85cb98718..493488aa6 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_members_test.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_members_test.go @@ -217,7 +217,6 @@ func TestOrganizationsService_ListOrgMemberships(t *testing.T) { mux.HandleFunc("/user/memberships/orgs", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeMembershipPreview) testFormValues(t, r, values{ "state": "active", "page": "2", @@ -246,7 +245,6 @@ func TestOrganizationsService_GetOrgMembership(t *testing.T) { mux.HandleFunc("/user/memberships/orgs/o", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeMembershipPreview) fmt.Fprint(w, `{"url":"u"}`) }) @@ -272,7 +270,6 @@ func TestOrganizationsService_EditOrgMembership(t *testing.T) { json.NewDecoder(r.Body).Decode(v) testMethod(t, r, "PATCH") - testHeader(t, r, "Accept", mediaTypeMembershipPreview) if !reflect.DeepEqual(v, input) { t.Errorf("Request body = %+v, want %+v", v, input) } diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_teams.go b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_teams.go index 0c0f7dbd9..dd01a7b22 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_teams.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_teams.go @@ -158,32 +158,6 @@ func (s *OrganizationsService) IsTeamMember(team int, user string) (bool, *Respo return member, resp, err } -// AddTeamMember adds a user to a team. -// -// GitHub API docs: http://developer.github.com/v3/orgs/teams/#add-team-member -func (s *OrganizationsService) AddTeamMember(team int, user string) (*Response, error) { - u := fmt.Sprintf("teams/%v/members/%v", team, user) - req, err := s.client.NewRequest("PUT", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(req, nil) -} - -// RemoveTeamMember removes a user from a team. -// -// GitHub API docs: http://developer.github.com/v3/orgs/teams/#remove-team-member -func (s *OrganizationsService) RemoveTeamMember(team int, user string) (*Response, error) { - u := fmt.Sprintf("teams/%v/members/%v", team, user) - req, err := s.client.NewRequest("DELETE", u, nil) - if err != nil { - return nil, err - } - - return s.client.Do(req, nil) -} - // ListTeamRepos lists the repositories that the specified team has access to. // // GitHub API docs: http://developer.github.com/v3/orgs/teams/#list-team-repos @@ -286,9 +260,6 @@ func (s *OrganizationsService) GetTeamMembership(team int, user string) (*Member return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeMembershipPreview) - t := new(Membership) resp, err := s.client.Do(req, t) if err != nil { @@ -323,9 +294,6 @@ func (s *OrganizationsService) AddTeamMembership(team int, user string) (*Member return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeMembershipPreview) - t := new(Membership) resp, err := s.client.Do(req, t) if err != nil { @@ -345,8 +313,5 @@ func (s *OrganizationsService) RemoveTeamMembership(team int, user string) (*Res return nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeMembershipPreview) - return s.client.Do(req, nil) } diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_teams_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_teams_test.go index 1f45e8c1b..1b18b623f 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/orgs_teams_test.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/orgs_teams_test.go @@ -220,46 +220,6 @@ func TestOrganizationsService_IsTeamMember_invalidUser(t *testing.T) { testURLParseError(t, err) } -func TestOrganizationsService_AddTeamMember(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "PUT") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.AddTeamMember(1, "u") - if err != nil { - t.Errorf("Organizations.AddTeamMember returned error: %v", err) - } -} - -func TestOrganizationsService_AddTeamMember_invalidUser(t *testing.T) { - _, err := client.Organizations.AddTeamMember(1, "%") - testURLParseError(t, err) -} - -func TestOrganizationsService_RemoveTeamMember(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/teams/1/members/u", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "DELETE") - w.WriteHeader(http.StatusNoContent) - }) - - _, err := client.Organizations.RemoveTeamMember(1, "u") - if err != nil { - t.Errorf("Organizations.RemoveTeamMember returned error: %v", err) - } -} - -func TestOrganizationsService_RemoveTeamMember_invalidUser(t *testing.T) { - _, err := client.Organizations.RemoveTeamMember(1, "%") - testURLParseError(t, err) -} - func TestOrganizationsService_PublicizeMembership(t *testing.T) { setup() defer teardown() @@ -442,7 +402,6 @@ func TestOrganizationsService_GetTeamMembership(t *testing.T) { mux.HandleFunc("/teams/1/memberships/u", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") - testHeader(t, r, "Accept", mediaTypeMembershipPreview) fmt.Fprint(w, `{"url":"u", "state":"active"}`) }) @@ -463,7 +422,6 @@ func TestOrganizationsService_AddTeamMembership(t *testing.T) { mux.HandleFunc("/teams/1/memberships/u", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "PUT") - testHeader(t, r, "Accept", mediaTypeMembershipPreview) fmt.Fprint(w, `{"url":"u", "state":"pending"}`) }) @@ -484,7 +442,6 @@ func TestOrganizationsService_RemoveTeamMembership(t *testing.T) { mux.HandleFunc("/teams/1/memberships/u", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "DELETE") - testHeader(t, r, "Accept", mediaTypeMembershipPreview) w.WriteHeader(http.StatusNoContent) }) diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/pulls.go b/Godeps/_workspace/src/github.com/google/go-github/github/pulls.go index 307562d70..71cf2e248 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/pulls.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/pulls.go @@ -41,6 +41,8 @@ type PullRequest struct { HTMLURL *string `json:"html_url,omitempty"` IssueURL *string `json:"issue_url,omitempty"` StatusesURL *string `json:"statuses_url,omitempty"` + DiffURL *string `json:"diff_url,omitempty"` + PatchURL *string `json:"patch_url,omitempty"` Head *PullRequestBranch `json:"head,omitempty"` Base *PullRequestBranch `json:"base,omitempty"` @@ -73,6 +75,15 @@ type PullRequestListOptions struct { // Base filters pull requests by base branch name. Base string `url:"base,omitempty"` + // Sort specifies how to sort pull requests. Possible values are: created, + // updated, popularity, long-running. Default is "created". + Sort string `url:"sort,omitempty"` + + // Direction in which to sort pull requests. Possible values are: asc, desc. + // If Sort is "created" or not specified, Default is "desc", otherwise Default + // is "asc" + Direction string `url:"direction,omitempty"` + ListOptions } diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/pulls_comments.go b/Godeps/_workspace/src/github.com/google/go-github/github/pulls_comments.go index bfbad9af2..35c7241b9 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/pulls_comments.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/pulls_comments.go @@ -93,7 +93,7 @@ func (s *PullRequestsService) GetComment(owner string, repo string, number int) // CreateComment creates a new comment on the specified pull request. // -// GitHub API docs: https://developer.github.com/v3/pulls/comments/#get-a-single-comment +// GitHub API docs: https://developer.github.com/v3/pulls/comments/#create-a-comment func (s *PullRequestsService) CreateComment(owner string, repo string, number int, comment *PullRequestComment) (*PullRequestComment, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pulls/%d/comments", owner, repo, number) req, err := s.client.NewRequest("POST", u, comment) diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/pulls_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/pulls_test.go index d0e976bc3..6ac0ddb17 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/pulls_test.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/pulls_test.go @@ -20,15 +20,17 @@ func TestPullRequestsService_List(t *testing.T) { mux.HandleFunc("/repos/o/r/pulls", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") testFormValues(t, r, values{ - "state": "closed", - "head": "h", - "base": "b", - "page": "2", + "state": "closed", + "head": "h", + "base": "b", + "sort": "created", + "direction": "desc", + "page": "2", }) fmt.Fprint(w, `[{"number":1}]`) }) - opt := &PullRequestListOptions{"closed", "h", "b", ListOptions{Page: 2}} + opt := &PullRequestListOptions{"closed", "h", "b", "created", "desc", ListOptions{Page: 2}} pulls, _, err := client.PullRequests.List("o", "r", opt) if err != nil { @@ -98,6 +100,29 @@ func TestPullRequestsService_Get_headAndBase(t *testing.T) { } } +func TestPullRequestService_Get_DiffURLAndPatchURL(t *testing.T) { + setup() + defer teardown() + + mux.HandleFunc("/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + fmt.Fprint(w, `{"number":1, + "diff_url": "https://github.com/octocat/Hello-World/pull/1347.diff", + "patch_url": "https://github.com/octocat/Hello-World/pull/1347.patch"}`) + }) + + pull, _, err := client.PullRequests.Get("o", "r", 1) + + if err != nil { + t.Errorf("PullRequests.Get returned error: %v", err) + } + + want := &PullRequest{Number: Int(1), DiffURL: String("https://github.com/octocat/Hello-World/pull/1347.diff"), PatchURL: String("https://github.com/octocat/Hello-World/pull/1347.patch")} + if !reflect.DeepEqual(pull, want) { + t.Errorf("PullRequests.Get returned %+v, want %+v", pull, want) + } +} + func TestPullRequestsService_Get_invalidOwner(t *testing.T) { _, _, err := client.PullRequests.Get("%", "r", 1) testURLParseError(t, err) diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos.go index 8d8d40fc1..86d9ad0d0 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/repos.go @@ -49,6 +49,9 @@ type Repository struct { Organization *Organization `json:"organization,omitempty"` Permissions *map[string]bool `json:"permissions,omitempty"` + // Only provided when using RepositoriesService.Get while in preview + License *License `json:"license,omitempty"` + // Additional mutable fields when creating and editing a repository Private *bool `json:"private"` HasIssues *bool `json:"has_issues"` @@ -119,6 +122,11 @@ type RepositoryListOptions struct { // Default is "asc" when sort is "full_name", otherwise default is "desc". Direction string `url:"direction,omitempty"` + // Include orginization repositories the user has access to. + // This will become the default behavior in the future, but is opt-in for now. + // See https://developer.github.com/changes/2015-01-07-prepare-for-organization-permissions-changes/ + IncludeOrg bool `url:"-"` + ListOptions } @@ -143,6 +151,10 @@ func (s *RepositoriesService) List(user string, opt *RepositoryListOptions) ([]R return nil, nil, err } + if opt != nil && opt.IncludeOrg { + req.Header.Set("Accept", mediaTypeOrganizationsPreview) + } + repos := new([]Repository) resp, err := s.client.Do(req, repos) if err != nil { @@ -255,6 +267,10 @@ func (s *RepositoriesService) Get(owner, repo string) (*Repository, *Response, e return nil, nil, err } + // TODO: remove custom Accept header when the license support fully launches + // https://developer.github.com/v3/licenses/#get-a-repositorys-license + req.Header.Set("Accept", mediaTypeLicensesPreview) + repository := new(Repository) resp, err := s.client.Do(req, repository) if err != nil { diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_commits.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_commits.go index 5a5914690..6401cb4ab 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_commits.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/repos_commits.go @@ -61,7 +61,8 @@ func (c CommitFile) String() string { // CommitsComparison is the result of comparing two commits. // See CompareCommits() for details. type CommitsComparison struct { - BaseCommit *RepositoryCommit `json:"base_commit,omitempty"` + BaseCommit *RepositoryCommit `json:"base_commit,omitempty"` + MergeBaseCommit *RepositoryCommit `json:"merge_base_commit,omitempty"` // Head can be 'behind' or 'ahead' Status *string `json:"status,omitempty"` diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_contents.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_contents.go index d17c63e8c..80776f2da 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_contents.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/repos_contents.go @@ -13,22 +13,25 @@ import ( "encoding/json" "errors" "fmt" + "io" "net/http" "net/url" + "path" ) // RepositoryContent represents a file or directory in a github repository. type RepositoryContent struct { - Type *string `json:"type,omitempty"` - Encoding *string `json:"encoding,omitempty"` - Size *int `json:"size,omitempty"` - Name *string `json:"name,omitempty"` - Path *string `json:"path,omitempty"` - Content *string `json:"content,omitempty"` - SHA *string `json:"sha,omitempty"` - URL *string `json:"url,omitempty"` - GitURL *string `json:"giturl,omitempty"` - HTMLURL *string `json:"htmlurl,omitempty"` + Type *string `json:"type,omitempty"` + Encoding *string `json:"encoding,omitempty"` + Size *int `json:"size,omitempty"` + Name *string `json:"name,omitempty"` + Path *string `json:"path,omitempty"` + Content *string `json:"content,omitempty"` + SHA *string `json:"sha,omitempty"` + URL *string `json:"url,omitempty"` + GitURL *string `json:"git_url,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + DownloadURL *string `json:"download_url,omitempty"` } // RepositoryContentResponse holds the parsed response from CreateFile, UpdateFile, and DeleteFile. @@ -90,6 +93,32 @@ func (s *RepositoriesService) GetReadme(owner, repo string, opt *RepositoryConte return readme, resp, err } +// DownloadContents returns an io.ReadCloser that reads the contents of the +// specified file. This function will work with files of any size, as opposed +// to GetContents which is limited to 1 Mb files. It is the caller's +// responsibility to close the ReadCloser. +func (s *RepositoriesService) DownloadContents(owner, repo, filepath string, opt *RepositoryContentGetOptions) (io.ReadCloser, error) { + dir := path.Dir(filepath) + filename := path.Base(filepath) + _, dirContents, _, err := s.GetContents(owner, repo, dir, opt) + if err != nil { + return nil, err + } + for _, contents := range dirContents { + if *contents.Name == filename { + if contents.DownloadURL == nil || *contents.DownloadURL == "" { + return nil, fmt.Errorf("No download link found for %s", filepath) + } + resp, err := s.client.client.Get(*contents.DownloadURL) + if err != nil { + return nil, err + } + return resp.Body, nil + } + } + return nil, fmt.Errorf("No file named %s found in %s", filename, dir) +} + // GetContents can return either the metadata and content of a single file // (when path references a file) or the metadata of all the files and/or // subdirectories of a directory (when path references a directory). To make it diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_contents_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_contents_test.go index 7376aea57..8ab3ecdae 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_contents_test.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/repos_contents_test.go @@ -2,6 +2,7 @@ package github import ( "fmt" + "io/ioutil" "net/http" "reflect" "testing" @@ -54,7 +55,70 @@ func TestRepositoriesService_GetReadme(t *testing.T) { } } -func TestRepositoriesService_GetContent_File(t *testing.T) { +func TestRepositoriesService_DownloadContents_Success(t *testing.T) { + setup() + defer teardown() + mux.HandleFunc("/repos/o/r/contents/d", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + fmt.Fprint(w, `[{ + "type": "file", + "name": "f", + "download_url": "`+server.URL+`/download/f" + }]`) + }) + mux.HandleFunc("/download/f", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + fmt.Fprint(w, "foo") + }) + + r, err := client.Repositories.DownloadContents("o", "r", "d/f", nil) + if err != nil { + t.Errorf("Repositories.DownloadContents returned error: %v", err) + } + + bytes, err := ioutil.ReadAll(r) + if err != nil { + t.Errorf("Error reading response body: %v", err) + } + r.Close() + + if got, want := string(bytes), "foo"; got != want { + t.Errorf("Repositories.DownloadContents returned %v, want %v", got, want) + } +} + +func TestRepositoriesService_DownloadContents_NoDownloadURL(t *testing.T) { + setup() + defer teardown() + mux.HandleFunc("/repos/o/r/contents/d", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + fmt.Fprint(w, `[{ + "type": "file", + "name": "f", + }]`) + }) + + _, err := client.Repositories.DownloadContents("o", "r", "d/f", nil) + if err == nil { + t.Errorf("Repositories.DownloadContents did not return expected error") + } +} + +func TestRepositoriesService_DownloadContents_NoFile(t *testing.T) { + setup() + defer teardown() + mux.HandleFunc("/repos/o/r/contents/d", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + fmt.Fprint(w, `[]`) + }) + + _, err := client.Repositories.DownloadContents("o", "r", "d/f", nil) + if err == nil { + t.Errorf("Repositories.DownloadContents did not return expected error") + } +} + +func TestRepositoriesService_GetContents_File(t *testing.T) { setup() defer teardown() mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) { @@ -69,7 +133,7 @@ func TestRepositoriesService_GetContent_File(t *testing.T) { }) fileContents, _, _, err := client.Repositories.GetContents("o", "r", "p", &RepositoryContentGetOptions{}) if err != nil { - t.Errorf("Repositories.GetContents_File returned error: %v", err) + t.Errorf("Repositories.GetContents returned error: %v", err) } want := &RepositoryContent{Type: String("file"), Name: String("LICENSE"), Size: Int(20678), Encoding: String("base64"), Path: String("LICENSE")} if !reflect.DeepEqual(fileContents, want) { @@ -77,7 +141,7 @@ func TestRepositoriesService_GetContent_File(t *testing.T) { } } -func TestRepositoriesService_GetContent_Directory(t *testing.T) { +func TestRepositoriesService_GetContents_Directory(t *testing.T) { setup() defer teardown() mux.HandleFunc("/repos/o/r/contents/p", func(w http.ResponseWriter, r *http.Request) { @@ -88,7 +152,7 @@ func TestRepositoriesService_GetContent_Directory(t *testing.T) { "path": "lib" }, { - "type": "file", + "type": "file", "size": 20678, "name": "LICENSE", "path": "LICENSE" @@ -96,7 +160,7 @@ func TestRepositoriesService_GetContent_Directory(t *testing.T) { }) _, directoryContents, _, err := client.Repositories.GetContents("o", "r", "p", &RepositoryContentGetOptions{}) if err != nil { - t.Errorf("Repositories.GetContents_Directory returned error: %v", err) + t.Errorf("Repositories.GetContents returned error: %v", err) } want := []*RepositoryContent{{Type: String("dir"), Name: String("lib"), Path: String("lib")}, {Type: String("file"), Name: String("LICENSE"), Size: Int(20678), Path: String("LICENSE")}} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_deployments.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_deployments.go index 2fdf15a76..77c79491d 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_deployments.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/repos_deployments.go @@ -27,13 +27,13 @@ type Deployment struct { // DeploymentRequest represents a deployment request type DeploymentRequest struct { - Ref *string `json:"ref,omitempty"` - Task *string `json:"task,omitempty"` - AutoMerge *bool `json:"auto_merge,omitempty"` - RequiredContexts []string `json:"required_contexts,omitempty"` - Payload *string `json:"payload,omitempty"` - Environment *string `json:"environment,omitempty"` - Description *string `json:"description,omitempty"` + Ref *string `json:"ref,omitempty"` + Task *string `json:"task,omitempty"` + AutoMerge *bool `json:"auto_merge,omitempty"` + RequiredContexts *[]string `json:"required_contexts,omitempty"` + Payload *string `json:"payload,omitempty"` + Environment *string `json:"environment,omitempty"` + Description *string `json:"description,omitempty"` } // DeploymentsListOptions specifies the optional parameters to the @@ -69,9 +69,6 @@ func (s *RepositoriesService) ListDeployments(owner, repo string, opt *Deploymen return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeDeploymentPreview) - deployments := new([]Deployment) resp, err := s.client.Do(req, deployments) if err != nil { @@ -92,9 +89,6 @@ func (s *RepositoriesService) CreateDeployment(owner, repo string, request *Depl return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeDeploymentPreview) - d := new(Deployment) resp, err := s.client.Do(req, d) if err != nil { @@ -138,9 +132,6 @@ func (s *RepositoriesService) ListDeploymentStatuses(owner, repo string, deploym return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeDeploymentPreview) - statuses := new([]DeploymentStatus) resp, err := s.client.Do(req, statuses) if err != nil { @@ -161,9 +152,6 @@ func (s *RepositoriesService) CreateDeploymentStatus(owner, repo string, deploym return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeDeploymentPreview) - d := new(DeploymentStatus) resp, err := s.client.Do(req, d) if err != nil { diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_hooks.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_hooks.go index 846867285..bc4c8c5dd 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_hooks.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/repos_hooks.go @@ -164,6 +164,18 @@ func (s *RepositoriesService) DeleteHook(owner, repo string, id int) (*Response, return s.client.Do(req, nil) } +// PingHook triggers a 'ping' event to be sent to the Hook. +// +// GitHub API docs: https://developer.github.com/v3/repos/hooks/#ping-a-hook +func (s *RepositoriesService) PingHook(owner, repo string, id int) (*Response, error) { + u := fmt.Sprintf("repos/%v/%v/hooks/%d/pings", owner, repo, id) + req, err := s.client.NewRequest("POST", u, nil) + if err != nil { + return nil, err + } + return s.client.Do(req, nil) +} + // TestHook triggers a test Hook by github. // // GitHub API docs: http://developer.github.com/v3/repos/hooks/#test-a-push-hook @@ -176,34 +188,7 @@ func (s *RepositoriesService) TestHook(owner, repo string, id int) (*Response, e return s.client.Do(req, nil) } -// ServiceHook represents a hook that has configuration settings, a list of -// available events, and default events. -type ServiceHook struct { - Name *string `json:"name,omitempty"` - Events []string `json:"events,omitempty"` - SupportedEvents []string `json:"supported_events,omitempty"` - Schema [][]string `json:"schema,omitempty"` -} - -func (s *ServiceHook) String() string { - return Stringify(s) -} - -// ListServiceHooks lists all of the available service hooks. -// -// GitHub API docs: https://developer.github.com/webhooks/#services +// ListServiceHooks is deprecated. Use Client.ListServiceHooks instead. func (s *RepositoriesService) ListServiceHooks() ([]ServiceHook, *Response, error) { - u := "hooks" - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, nil, err - } - - hooks := new([]ServiceHook) - resp, err := s.client.Do(req, hooks) - if err != nil { - return nil, resp, err - } - - return *hooks, resp, err + return s.client.ListServiceHooks() } diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_hooks_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_hooks_test.go index b322e17ea..c163a26b2 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_hooks_test.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/repos_hooks_test.go @@ -153,6 +153,20 @@ func TestRepositoriesService_DeleteHook_invalidOwner(t *testing.T) { testURLParseError(t, err) } +func TestRepositoriesService_PingHook(t *testing.T) { + setup() + defer teardown() + + mux.HandleFunc("/repos/o/r/hooks/1/pings", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "POST") + }) + + _, err := client.Repositories.PingHook("o", "r", 1) + if err != nil { + t.Errorf("Repositories.PingHook returned error: %v", err) + } +} + func TestRepositoriesService_TestHook(t *testing.T) { setup() defer teardown() @@ -171,35 +185,3 @@ func TestRepositoriesService_TestHook_invalidOwner(t *testing.T) { _, err := client.Repositories.TestHook("%", "%", 1) testURLParseError(t, err) } - -func TestRepositoriesService_ListServiceHooks(t *testing.T) { - setup() - defer teardown() - - mux.HandleFunc("/hooks", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - fmt.Fprint(w, `[{ - "name":"n", - "events":["e"], - "supported_events":["s"], - "schema":[ - ["a", "b"] - ] - }]`) - }) - - hooks, _, err := client.Repositories.ListServiceHooks() - if err != nil { - t.Errorf("Repositories.ListHooks returned error: %v", err) - } - - want := []ServiceHook{{ - Name: String("n"), - Events: []string{"e"}, - SupportedEvents: []string{"s"}, - Schema: [][]string{{"a", "b"}}, - }} - if !reflect.DeepEqual(hooks, want) { - t.Errorf("Repositories.ListServiceHooks returned %+v, want %+v", hooks, want) - } -} diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_releases.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_releases.go index 140011441..d0e041b81 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_releases.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/repos_releases.go @@ -85,8 +85,27 @@ func (s *RepositoriesService) ListReleases(owner, repo string, opt *ListOptions) // GitHub API docs: http://developer.github.com/v3/repos/releases/#get-a-single-release func (s *RepositoriesService) GetRelease(owner, repo string, id int) (*RepositoryRelease, *Response, error) { u := fmt.Sprintf("repos/%s/%s/releases/%d", owner, repo, id) + return s.getSingleRelease(u) +} - req, err := s.client.NewRequest("GET", u, nil) +// GetLatestRelease fetches the latest published release for the repository. +// +// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-the-latest-release +func (s *RepositoriesService) GetLatestRelease(owner, repo string) (*RepositoryRelease, *Response, error) { + u := fmt.Sprintf("repos/%s/%s/releases/latest", owner, repo) + return s.getSingleRelease(u) +} + +// GetLatestReleaseByTag fetches a release with the specified tag. +// +// GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-release-by-tag-name +func (s *RepositoriesService) GetReleaseByTag(owner, repo, tag string) (*RepositoryRelease, *Response, error) { + u := fmt.Sprintf("repos/%s/%s/releases/tags/%s", owner, repo, tag) + return s.getSingleRelease(u) +} + +func (s *RepositoriesService) getSingleRelease(url string) (*RepositoryRelease, *Response, error) { + req, err := s.client.NewRequest("GET", url, nil) if err != nil { return nil, nil, err } diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_releases_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_releases_test.go index 17c670235..21808b7e6 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_releases_test.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/repos_releases_test.go @@ -55,6 +55,46 @@ func TestRepositoriesService_GetRelease(t *testing.T) { } } +func TestRepositoriesService_GetLatestRelease(t *testing.T) { + setup() + defer teardown() + + mux.HandleFunc("/repos/o/r/releases/latest", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + fmt.Fprint(w, `{"id":3}`) + }) + + release, resp, err := client.Repositories.GetLatestRelease("o", "r") + if err != nil { + t.Errorf("Repositories.GetLatestRelease returned error: %v\n%v", err, resp.Body) + } + + want := &RepositoryRelease{ID: Int(3)} + if !reflect.DeepEqual(release, want) { + t.Errorf("Repositories.GetLatestRelease returned %+v, want %+v", release, want) + } +} + +func TestRepositoriesService_GetReleaseByTag(t *testing.T) { + setup() + defer teardown() + + mux.HandleFunc("/repos/o/r/releases/tags/foo", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + fmt.Fprint(w, `{"id":13}`) + }) + + release, resp, err := client.Repositories.GetReleaseByTag("o", "r", "foo") + if err != nil { + t.Errorf("Repositories.GetReleaseByTag returned error: %v\n%v", err, resp.Body) + } + + want := &RepositoryRelease{ID: Int(13)} + if !reflect.DeepEqual(release, want) { + t.Errorf("Repositories.GetReleaseByTag returned %+v, want %+v", release, want) + } +} + func TestRepositoriesService_CreateRelease(t *testing.T) { setup() defer teardown() diff --git a/Godeps/_workspace/src/github.com/google/go-github/github/repos_test.go b/Godeps/_workspace/src/github.com/google/go-github/github/repos_test.go index def211975..2480b88b1 100644 --- a/Godeps/_workspace/src/github.com/google/go-github/github/repos_test.go +++ b/Godeps/_workspace/src/github.com/google/go-github/github/repos_test.go @@ -45,11 +45,11 @@ func TestRepositoriesService_List_specifiedUser(t *testing.T) { "direction": "asc", "page": "2", }) - + testHeader(t, r, "Accept", mediaTypeOrganizationsPreview) fmt.Fprint(w, `[{"id":1}]`) }) - opt := &RepositoryListOptions{"owner", "created", "asc", ListOptions{Page: 2}} + opt := &RepositoryListOptions{"owner", "created", "asc", true, ListOptions{Page: 2}} repos, _, err := client.Repositories.List("u", opt) if err != nil { t.Errorf("Repositories.List returned error: %v", err) @@ -191,7 +191,8 @@ func TestRepositoriesService_Get(t *testing.T) { mux.HandleFunc("/repos/o/r", func(w http.ResponseWriter, r *http.Request) { testMethod(t, r, "GET") - fmt.Fprint(w, `{"id":1,"name":"n","description":"d","owner":{"login":"l"}}`) + testHeader(t, r, "Accept", mediaTypeLicensesPreview) + fmt.Fprint(w, `{"id":1,"name":"n","description":"d","owner":{"login":"l"},"license":{"key":"mit"}}`) }) repo, _, err := client.Repositories.Get("o", "r") @@ -199,7 +200,7 @@ func TestRepositoriesService_Get(t *testing.T) { t.Errorf("Repositories.Get returned error: %v", err) } - want := &Repository{ID: Int(1), Name: String("n"), Description: String("d"), Owner: &User{Login: String("l")}} + want := &Repository{ID: Int(1), Name: String("n"), Description: String("d"), Owner: &User{Login: String("l")}, License: &License{Key: String("mit")}} if !reflect.DeepEqual(repo, want) { t.Errorf("Repositories.Get returned %+v, want %+v", repo, want) } diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go index 1e9641795..2a5207a6e 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go @@ -1,25 +1,14 @@ package api import ( - "os" "testing" ) -// ROOT is a management token for the tests -var CONSUL_ROOT string - -func init() { - CONSUL_ROOT = os.Getenv("CONSUL_ROOT") -} - func TestACL_CreateDestroy(t *testing.T) { - if CONSUL_ROOT == "" { - t.SkipNow() - } - c, s := makeClient(t) + t.Parallel() + c, s := makeACLClient(t) defer s.Stop() - c.config.Token = CONSUL_ROOT acl := c.ACL() ae := ACLEntry{ @@ -61,16 +50,13 @@ func TestACL_CreateDestroy(t *testing.T) { } func TestACL_CloneDestroy(t *testing.T) { - if CONSUL_ROOT == "" { - t.SkipNow() - } - c, s := makeClient(t) + t.Parallel() + c, s := makeACLClient(t) defer s.Stop() - c.config.Token = CONSUL_ROOT acl := c.ACL() - id, wm, err := acl.Clone(CONSUL_ROOT, nil) + id, wm, err := acl.Clone(c.config.Token, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -94,16 +80,13 @@ func TestACL_CloneDestroy(t *testing.T) { } func TestACL_Info(t *testing.T) { - if CONSUL_ROOT == "" { - t.SkipNow() - } - c, s := makeClient(t) + t.Parallel() + c, s := makeACLClient(t) defer s.Stop() - c.config.Token = CONSUL_ROOT acl := c.ACL() - ae, qm, err := acl.Info(CONSUL_ROOT, nil) + ae, qm, err := acl.Info(c.config.Token, nil) if err != nil { t.Fatalf("err: %v", err) } @@ -115,19 +98,16 @@ func TestACL_Info(t *testing.T) { t.Fatalf("bad: %v", qm) } - if ae == nil || ae.ID != CONSUL_ROOT || ae.Type != ACLManagementType { + if ae == nil || ae.ID != c.config.Token || ae.Type != ACLManagementType { t.Fatalf("bad: %#v", ae) } } func TestACL_List(t *testing.T) { - if CONSUL_ROOT == "" { - t.SkipNow() - } - c, s := makeClient(t) + t.Parallel() + c, s := makeACLClient(t) defer s.Stop() - c.config.Token = CONSUL_ROOT acl := c.ACL() acls, qm, err := acl.List(nil) diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent.go index 4b144fe18..e56a18dcd 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent.go @@ -68,6 +68,7 @@ type AgentServiceCheck struct { Timeout string `json:",omitempty"` TTL string `json:",omitempty"` HTTP string `json:",omitempty"` + Status string `json:",omitempty"` } type AgentServiceChecks []*AgentServiceCheck diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go index 549842092..358c12a6c 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go @@ -6,6 +6,7 @@ import ( ) func TestAgent_Self(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -23,6 +24,7 @@ func TestAgent_Self(t *testing.T) { } func TestAgent_Members(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -39,6 +41,7 @@ func TestAgent_Members(t *testing.T) { } func TestAgent_Services(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -63,21 +66,91 @@ func TestAgent_Services(t *testing.T) { if _, ok := services["foo"]; !ok { t.Fatalf("missing service: %v", services) } - checks, err := agent.Checks() if err != nil { t.Fatalf("err: %v", err) } - if _, ok := checks["service:foo"]; !ok { + chk, ok := checks["service:foo"] + if !ok { t.Fatalf("missing check: %v", checks) } + // Checks should default to critical + if chk.Status != "critical" { + t.Fatalf("Bad: %#v", chk) + } + if err := agent.ServiceDeregister("foo"); err != nil { t.Fatalf("err: %v", err) } } +func TestAgent_Services_CheckPassing(t *testing.T) { + t.Parallel() + c, s := makeClient(t) + defer s.Stop() + + agent := c.Agent() + reg := &AgentServiceRegistration{ + Name: "foo", + Tags: []string{"bar", "baz"}, + Port: 8000, + Check: &AgentServiceCheck{ + TTL: "15s", + Status: "passing", + }, + } + if err := agent.ServiceRegister(reg); err != nil { + t.Fatalf("err: %v", err) + } + + services, err := agent.Services() + if err != nil { + t.Fatalf("err: %v", err) + } + if _, ok := services["foo"]; !ok { + t.Fatalf("missing service: %v", services) + } + + checks, err := agent.Checks() + if err != nil { + t.Fatalf("err: %v", err) + } + chk, ok := checks["service:foo"] + if !ok { + t.Fatalf("missing check: %v", checks) + } + + if chk.Status != "passing" { + t.Fatalf("Bad: %#v", chk) + } + if err := agent.ServiceDeregister("foo"); err != nil { + t.Fatalf("err: %v", err) + } +} + +func TestAgent_Services_CheckBadStatus(t *testing.T) { + t.Parallel() + c, s := makeClient(t) + defer s.Stop() + + agent := c.Agent() + reg := &AgentServiceRegistration{ + Name: "foo", + Tags: []string{"bar", "baz"}, + Port: 8000, + Check: &AgentServiceCheck{ + TTL: "15s", + Status: "fluffy", + }, + } + if err := agent.ServiceRegister(reg); err == nil { + t.Fatalf("bad status accepted") + } +} + func TestAgent_ServiceAddress(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -124,6 +197,7 @@ func TestAgent_ServiceAddress(t *testing.T) { } func TestAgent_Services_MultipleChecks(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -167,6 +241,7 @@ func TestAgent_Services_MultipleChecks(t *testing.T) { } func TestAgent_SetTTLStatus(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -207,6 +282,7 @@ func TestAgent_SetTTLStatus(t *testing.T) { } func TestAgent_Checks(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -224,9 +300,48 @@ func TestAgent_Checks(t *testing.T) { if err != nil { t.Fatalf("err: %v", err) } - if _, ok := checks["foo"]; !ok { + chk, ok := checks["foo"] + if !ok { t.Fatalf("missing check: %v", checks) } + if chk.Status != "critical" { + t.Fatalf("check not critical: %v", chk) + } + + if err := agent.CheckDeregister("foo"); err != nil { + t.Fatalf("err: %v", err) + } +} + +func TestAgent_CheckStartPassing(t *testing.T) { + t.Parallel() + c, s := makeClient(t) + defer s.Stop() + + agent := c.Agent() + + reg := &AgentCheckRegistration{ + Name: "foo", + AgentServiceCheck: AgentServiceCheck{ + Status: "passing", + }, + } + reg.TTL = "15s" + if err := agent.CheckRegister(reg); err != nil { + t.Fatalf("err: %v", err) + } + + checks, err := agent.Checks() + if err != nil { + t.Fatalf("err: %v", err) + } + chk, ok := checks["foo"] + if !ok { + t.Fatalf("missing check: %v", checks) + } + if chk.Status != "passing" { + t.Fatalf("check not passing: %v", chk) + } if err := agent.CheckDeregister("foo"); err != nil { t.Fatalf("err: %v", err) @@ -234,6 +349,7 @@ func TestAgent_Checks(t *testing.T) { } func TestAgent_Checks_serviceBound(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -272,6 +388,7 @@ func TestAgent_Checks_serviceBound(t *testing.T) { } func TestAgent_Join(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -291,6 +408,7 @@ func TestAgent_Join(t *testing.T) { } func TestAgent_ForceLeave(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -304,6 +422,7 @@ func TestAgent_ForceLeave(t *testing.T) { } func TestServiceMaintenance(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -358,6 +477,7 @@ func TestServiceMaintenance(t *testing.T) { } func TestNodeMaintenance(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go index 9c86e17ae..56f9494f8 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go @@ -20,6 +20,16 @@ func makeClient(t *testing.T) (*Client, *testutil.TestServer) { return makeClientWithConfig(t, nil, nil) } +func makeACLClient(t *testing.T) (*Client, *testutil.TestServer) { + return makeClientWithConfig(t, func(clientConfig *Config) { + clientConfig.Token = "root" + }, func(serverConfig *testutil.TestServerConfig) { + serverConfig.ACLMasterToken = "root" + serverConfig.ACLDatacenter = "dc1" + serverConfig.ACLDefaultPolicy = "deny" + }) +} + func makeClientWithConfig( t *testing.T, cb1 configCallback, @@ -59,6 +69,7 @@ func testKey() string { } func TestDefaultConfig_env(t *testing.T) { + t.Parallel() addr := "1.2.3.4:5678" token := "abcd1234" auth := "username:password" @@ -104,6 +115,7 @@ func TestDefaultConfig_env(t *testing.T) { } func TestSetQueryOptions(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -139,6 +151,7 @@ func TestSetQueryOptions(t *testing.T) { } func TestSetWriteOptions(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -158,6 +171,7 @@ func TestSetWriteOptions(t *testing.T) { } func TestRequestToHTTP(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -180,6 +194,7 @@ func TestRequestToHTTP(t *testing.T) { } func TestParseQueryMeta(t *testing.T) { + t.Parallel() resp := &http.Response{ Header: make(map[string][]string), } @@ -204,6 +219,7 @@ func TestParseQueryMeta(t *testing.T) { } func TestAPI_UnixSocket(t *testing.T) { + t.Parallel() if runtime.GOOS == "windows" { t.SkipNow() } diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go index a0b950e5f..bb8be25b0 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go @@ -8,6 +8,7 @@ import ( ) func TestCatalog_Datacenters(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -30,6 +31,7 @@ func TestCatalog_Datacenters(t *testing.T) { } func TestCatalog_Nodes(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -56,6 +58,7 @@ func TestCatalog_Nodes(t *testing.T) { } func TestCatalog_Services(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -82,6 +85,7 @@ func TestCatalog_Services(t *testing.T) { } func TestCatalog_Service(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -108,6 +112,7 @@ func TestCatalog_Service(t *testing.T) { } func TestCatalog_Node(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -134,6 +139,7 @@ func TestCatalog_Node(t *testing.T) { } func TestCatalog_Registration(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go index 9ebcb5397..1ca92e233 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go @@ -2,9 +2,12 @@ package api import ( "testing" + + "github.com/hashicorp/consul/testutil" ) func TestEvent_FireList(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -24,16 +27,23 @@ func TestEvent_FireList(t *testing.T) { t.Fatalf("invalid: %v", id) } - events, qm, err := event.List("", nil) - if err != nil { - t.Fatalf("err: %v", err) + var events []*UserEvent + var qm *QueryMeta + testutil.WaitForResult(func() (bool, error) { + events, qm, err = event.List("", nil) + if err != nil { + t.Fatalf("err: %v", err) + } + return len(events) > 0, err + }, func(err error) { + t.Fatalf("err: %#v", err) + }) + + if events[len(events)-1].ID != id { + t.Fatalf("bad: %#v", events) } if qm.LastIndex != event.IDToIndex(id) { t.Fatalf("Bad: %#v", qm) } - - if events[len(events)-1].ID != id { - t.Fatalf("bad: %#v", events) - } } diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go index df6eb0f66..d80a4693a 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go @@ -8,6 +8,7 @@ import ( ) func TestHealth_Node(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -38,6 +39,7 @@ func TestHealth_Node(t *testing.T) { } func TestHealth_Checks(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -74,6 +76,7 @@ func TestHealth_Checks(t *testing.T) { } func TestHealth_Service(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -98,6 +101,7 @@ func TestHealth_Service(t *testing.T) { } func TestHealth_State(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv.go index ba74057fc..c1a8923be 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv.go @@ -168,6 +168,10 @@ func (k *KV) Release(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) { } func (k *KV) put(key string, params map[string]string, body []byte, q *WriteOptions) (bool, *WriteMeta, error) { + if len(key) > 0 && key[0] == '/' { + return false, nil, fmt.Errorf("Invalid key. Key must not begin with a '/': %s", key) + } + r := k.c.newRequest("PUT", "/v1/kv/"+key) r.setWriteOptions(q) for param, val := range params { diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go index a5a0b54e2..758595d89 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go @@ -8,6 +8,7 @@ import ( ) func TestClientPutGetDelete(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -23,9 +24,17 @@ func TestClientPutGetDelete(t *testing.T) { t.Fatalf("unexpected value: %#v", pair) } - // Put the key value := []byte("test") - p := &KVPair{Key: key, Flags: 42, Value: value} + + // Put a key that begins with a '/', this should fail + invalidKey := "/test" + p := &KVPair{Key: invalidKey, Flags: 42, Value: value} + if _, err := kv.Put(p, nil); err == nil { + t.Fatalf("Invalid key not detected: %s", invalidKey) + } + + // Put the key + p = &KVPair{Key: key, Flags: 42, Value: value} if _, err := kv.Put(p, nil); err != nil { t.Fatalf("err: %v", err) } @@ -64,6 +73,7 @@ func TestClientPutGetDelete(t *testing.T) { } func TestClient_List_DeleteRecurse(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -118,6 +128,7 @@ func TestClient_List_DeleteRecurse(t *testing.T) { } func TestClient_DeleteCAS(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -163,6 +174,7 @@ func TestClient_DeleteCAS(t *testing.T) { } func TestClient_CAS(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -210,6 +222,7 @@ func TestClient_CAS(t *testing.T) { } func TestClient_WatchGet(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -261,6 +274,7 @@ func TestClient_WatchGet(t *testing.T) { } func TestClient_WatchList(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -314,6 +328,7 @@ func TestClient_WatchList(t *testing.T) { } func TestClient_Keys_DeleteRecurse(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -363,6 +378,7 @@ func TestClient_Keys_DeleteRecurse(t *testing.T) { } func TestClient_AcquireRelease(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock.go index 4b694789c..a76685f04 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock.go @@ -183,11 +183,23 @@ WAIT: // Handle the case of not getting the lock if !locked { - select { - case <-time.After(DefaultLockRetryTime): + // Determine why the lock failed + qOpts.WaitIndex = 0 + pair, meta, err = kv.Get(l.opts.Key, qOpts) + if pair != nil && pair.Session != "" { + //If the session is not null, this means that a wait can safely happen + //using a long poll + qOpts.WaitIndex = meta.LastIndex goto WAIT - case <-stopCh: - return nil, nil + } else { + // If the session is empty and the lock failed to acquire, then it means + // a lock-delay is in effect and a timed wait must be used + select { + case <-time.After(DefaultLockRetryTime): + goto WAIT + case <-stopCh: + return nil, nil + } } } diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go index 163372fe4..0a8fa5172 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go @@ -8,6 +8,7 @@ import ( ) func TestLock_LockUnlock(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -65,6 +66,7 @@ func TestLock_LockUnlock(t *testing.T) { } func TestLock_ForceInvalidate(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -99,6 +101,7 @@ func TestLock_ForceInvalidate(t *testing.T) { } func TestLock_DeleteKey(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -132,6 +135,7 @@ func TestLock_DeleteKey(t *testing.T) { } func TestLock_Contend(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -184,6 +188,7 @@ func TestLock_Contend(t *testing.T) { } func TestLock_Destroy(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -252,6 +257,7 @@ func TestLock_Destroy(t *testing.T) { } func TestLock_Conflict(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -289,6 +295,7 @@ func TestLock_Conflict(t *testing.T) { } func TestLock_ReclaimLock(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore.go index 957f884a4..ff4c2058c 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore.go @@ -22,11 +22,6 @@ const ( // a Semaphore acquisition. DefaultSemaphoreWaitTime = 15 * time.Second - // DefaultSemaphoreRetryTime is how long we wait after a failed lock acquisition - // before attempting to do the lock again. This is so that once a lock-delay - // is in affect, we do not hot loop retrying the acquisition. - DefaultSemaphoreRetryTime = 5 * time.Second - // DefaultSemaphoreKey is the key used within the prefix to // use for coordination between all the contenders. DefaultSemaphoreKey = ".lock" diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go index cb5057df9..5e5e53588 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go @@ -8,6 +8,7 @@ import ( ) func TestSemaphore_AcquireRelease(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -65,6 +66,7 @@ func TestSemaphore_AcquireRelease(t *testing.T) { } func TestSemaphore_ForceInvalidate(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -99,6 +101,7 @@ func TestSemaphore_ForceInvalidate(t *testing.T) { } func TestSemaphore_DeleteKey(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -132,6 +135,7 @@ func TestSemaphore_DeleteKey(t *testing.T) { } func TestSemaphore_Contend(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -184,6 +188,7 @@ func TestSemaphore_Contend(t *testing.T) { } func TestSemaphore_BadLimit(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -214,6 +219,7 @@ func TestSemaphore_BadLimit(t *testing.T) { } func TestSemaphore_Destroy(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -269,6 +275,7 @@ func TestSemaphore_Destroy(t *testing.T) { } func TestSemaphore_Conflict(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/session.go index 63baa90e9..a99da511d 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/session.go @@ -1,6 +1,7 @@ package api import ( + "fmt" "time" ) @@ -131,19 +132,32 @@ func (s *Session) RenewPeriodic(initialTTL string, id string, q *WriteOptions, d if err != nil { return err } + + waitDur := ttl / 2 + lastRenewTime := time.Now() + var lastErr error for { + if time.Since(lastRenewTime) > ttl { + return lastErr + } select { - case <-time.After(ttl / 2): + case <-time.After(waitDur): entry, _, err := s.Renew(id, q) if err != nil { - return err + waitDur = time.Second + lastErr = err + continue } if entry == nil { - return nil + waitDur = time.Second + lastErr = fmt.Errorf("No SessionEntry returned") + continue } // Handle the server updating the TTL ttl, _ = time.ParseDuration(entry.TTL) + waitDur = ttl / 2 + lastRenewTime = time.Now() case <-doneCh: // Attempt a session destroy diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go index 194c45fb7..c503c21a0 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go @@ -5,6 +5,7 @@ import ( ) func TestSession_CreateDestroy(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -34,6 +35,7 @@ func TestSession_CreateDestroy(t *testing.T) { } func TestSession_CreateRenewDestroy(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -84,6 +86,7 @@ func TestSession_CreateRenewDestroy(t *testing.T) { } func TestSession_Info(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -137,6 +140,7 @@ func TestSession_Info(t *testing.T) { } func TestSession_Node(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -171,6 +175,7 @@ func TestSession_Node(t *testing.T) { } func TestSession_List(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go index cb0cca672..62dc1550f 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go +++ b/Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go @@ -5,6 +5,7 @@ import ( ) func TestStatusLeader(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() @@ -20,6 +21,7 @@ func TestStatusLeader(t *testing.T) { } func TestStatusPeers(t *testing.T) { + t.Parallel() c, s := makeClient(t) defer s.Stop() diff --git a/Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten.go b/Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten.go new file mode 100644 index 000000000..aab8e9abe --- /dev/null +++ b/Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten.go @@ -0,0 +1,26 @@ +package multierror + +// Flatten flattens the given error, merging any *Errors together into +// a single *Error. +func Flatten(err error) error { + // If it isn't an *Error, just return the error as-is + if _, ok := err.(*Error); !ok { + return err + } + + // Otherwise, make the result and flatten away! + flatErr := new(Error) + flatten(err, flatErr) + return flatErr +} + +func flatten(err error, flatErr *Error) { + switch err := err.(type) { + case *Error: + for _, e := range err.Errors { + flatten(e, flatErr) + } + default: + flatErr.Errors = append(flatErr.Errors, err) + } +} diff --git a/Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten_test.go b/Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten_test.go new file mode 100644 index 000000000..75218f103 --- /dev/null +++ b/Godeps/_workspace/src/github.com/hashicorp/go-multierror/flatten_test.go @@ -0,0 +1,48 @@ +package multierror + +import ( + "errors" + "fmt" + "reflect" + "strings" + "testing" +) + +func TestFlatten(t *testing.T) { + original := &Error{ + Errors: []error{ + errors.New("one"), + &Error{ + Errors: []error{ + errors.New("two"), + &Error{ + Errors: []error{ + errors.New("three"), + }, + }, + }, + }, + }, + } + + expected := strings.TrimSpace(` +3 error(s) occurred: + +* one +* two +* three + `) + actual := fmt.Sprintf("%s", Flatten(original)) + + if expected != actual { + t.Fatalf("expected: %s, got: %s", expected, actual) + } +} + +func TestFlatten_nonError(t *testing.T) { + err := errors.New("foo") + actual := Flatten(err) + if !reflect.DeepEqual(actual, err) { + t.Fatalf("bad: %#v", actual) + } +} diff --git a/Godeps/_workspace/src/github.com/hashicorp/golang-lru/lru.go b/Godeps/_workspace/src/github.com/hashicorp/golang-lru/lru.go index b97933da5..5f1e8a1af 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/golang-lru/lru.go +++ b/Godeps/_workspace/src/github.com/hashicorp/golang-lru/lru.go @@ -49,7 +49,7 @@ func (c *Cache) Purge() { if c.onEvicted != nil { for k, v := range c.items { - c.onEvicted(k, v.Value) + c.onEvicted(k, v.Value.(*entry).value) } } @@ -94,6 +94,27 @@ func (c *Cache) Get(key interface{}) (value interface{}, ok bool) { return } +// Check if a key is in the cache, without updating the recent-ness or deleting it for being stale. +func (c *Cache) Contains(key interface{}) (ok bool) { + c.lock.RLock() + defer c.lock.RUnlock() + + _, ok = c.items[key] + return ok +} + +// Returns the key value (or undefined if not found) without updating the "recently used"-ness of the key. +// (If you find yourself using this a lot, you might be using the wrong sort of data structure, but there are some use cases where it's handy.) +func (c *Cache) Peek(key interface{}) (value interface{}, ok bool) { + c.lock.RLock() + defer c.lock.RUnlock() + + if ent, ok := c.items[key]; ok { + return ent.Value.(*entry).value, true + } + return nil, ok +} + // Remove removes the provided key from the cache. func (c *Cache) Remove(key interface{}) { c.lock.Lock() diff --git a/Godeps/_workspace/src/github.com/hashicorp/golang-lru/lru_test.go b/Godeps/_workspace/src/github.com/hashicorp/golang-lru/lru_test.go index cd0cd55d6..b676cfd9d 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/golang-lru/lru_test.go +++ b/Godeps/_workspace/src/github.com/hashicorp/golang-lru/lru_test.go @@ -5,6 +5,9 @@ import "testing" func TestLRU(t *testing.T) { evictCounter := 0 onEvicted := func(k interface{}, v interface{}) { + if k != v { + t.Fatalf("Evict values not equal (%v!=%v)", k, v) + } evictCounter += 1 } l, err := NewWithEvict(128, onEvicted) @@ -65,7 +68,7 @@ func TestLRU(t *testing.T) { } } -// test that Add return true/false if an eviction occured +// test that Add returns true/false if an eviction occured func TestLRUAdd(t *testing.T) { evictCounter := 0 onEvicted := func(k interface{}, v interface{}) { @@ -84,3 +87,41 @@ func TestLRUAdd(t *testing.T) { t.Errorf("should have an eviction") } } + +// test that Contains doesn't update recent-ness +func TestLRUContains(t *testing.T) { + l, err := New(2) + if err != nil { + t.Fatalf("err: %v", err) + } + + l.Add(1, 1) + l.Add(2, 2) + if !l.Contains(1) { + t.Errorf("1 should be contained") + } + + l.Add(3, 3) + if l.Contains(1) { + t.Errorf("Contains should not have updated recent-ness of 1") + } +} + +// test that Peek doesn't update recent-ness +func TestLRUPeek(t *testing.T) { + l, err := New(2) + if err != nil { + t.Fatalf("err: %v", err) + } + + l.Add(1, 1) + l.Add(2, 2) + if v, ok := l.Peek(1); !ok || v != 1 { + t.Errorf("1 should be set to 1: %v, %v", v, ok) + } + + l.Add(3, 3) + if l.Contains(1) { + t.Errorf("should not have updated recent-ness of 1") + } +} diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/README.md b/Godeps/_workspace/src/github.com/hashicorp/hcl/README.md index 55c43bd3e..c69d17e9b 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/README.md +++ b/Godeps/_workspace/src/github.com/hashicorp/hcl/README.md @@ -53,7 +53,9 @@ of the syntax and grammar are listed here. * Single line comments start with `#` or `//` - * Multi-line comments are wrapped in `/*` and `*/` + * Multi-line comments are wrapped in `/*` and `*/`. Nested block comments + are not allowed. A multi-line comment (also known as a block comment) + terminates at the first `*/` found. * Values are assigned with the syntax `key = value` (whitespace doesn't matter). The value can be any primitive: a string, number, boolean, diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/decoder_test.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/decoder_test.go index f4936ac7c..a71163b19 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/decoder_test.go +++ b/Godeps/_workspace/src/github.com/hashicorp/hcl/decoder_test.go @@ -188,6 +188,20 @@ func TestDecode_interface(t *testing.T) { }, }, }, + + { + "nested_block_comment.hcl", + false, + map[string]interface{}{ + "bar": "value", + }, + }, + + { + "unterminated_block_comment.hcl", + true, + nil, + }, } for _, tc := range cases { diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/lex.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/lex.go index 825b7da61..c14165956 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/lex.go +++ b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/lex.go @@ -125,7 +125,14 @@ func (x *hclLex) consumeComment(c rune) bool { c = x.next() if c == lexEOF { x.backup() - return true + if single { + // Single line comments can end with an EOF + return true + } + + // Multi-line comments must end with a */ + x.createErr(fmt.Sprintf("end of multi-line comment expected, got EOF")) + return false } // Single line comments continue until a '\n' @@ -149,18 +156,13 @@ func (x *hclLex) consumeComment(c rune) bool { case '*': c = x.next() if c == '/' { - nested-- + return true } else { x.backup() } default: // Continue } - - // If we're done with the comment, return! - if nested == 0 { - return true - } } } diff --git a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/valuetype_string.go b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/valuetype_string.go index efe119a03..83b39048a 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/valuetype_string.go +++ b/Godeps/_workspace/src/github.com/hashicorp/hcl/hcl/valuetype_string.go @@ -9,7 +9,7 @@ const _ValueType_name = "ValueTypeUnknownValueTypeFloatValueTypeIntValueTypeStri var _ValueType_index = [...]uint8{0, 16, 30, 42, 57, 70, 82, 95, 110} func (i ValueType) String() string { - if i+1 >= ValueType(len(_ValueType_index)) { + if i >= ValueType(len(_ValueType_index)-1) { return fmt.Sprintf("ValueType(%d)", i) } return _ValueType_name[_ValueType_index[i]:_ValueType_index[i+1]] diff --git a/Godeps/_workspace/src/github.com/hashicorp/logutils/README.md b/Godeps/_workspace/src/github.com/hashicorp/logutils/README.md index 57cad4d1c..49490eaeb 100644 --- a/Godeps/_workspace/src/github.com/hashicorp/logutils/README.md +++ b/Godeps/_workspace/src/github.com/hashicorp/logutils/README.md @@ -21,7 +21,7 @@ import ( func main() { filter := &logutils.LevelFilter{ Levels: []logutils.LogLevel{"DEBUG", "WARN", "ERROR"}, - MinLevel: "WARN", + MinLevel: logutils.LogLevel("WARN"), Writer: os.Stderr, } log.SetOutput(filter) diff --git a/Godeps/_workspace/src/github.com/kardianos/osext/README.md b/Godeps/_workspace/src/github.com/kardianos/osext/README.md index 820e1ecb5..61350baba 100644 --- a/Godeps/_workspace/src/github.com/kardianos/osext/README.md +++ b/Godeps/_workspace/src/github.com/kardianos/osext/README.md @@ -4,7 +4,9 @@ There is sometimes utility in finding the current executable file that is running. This can be used for upgrading the current executable -or finding resources located relative to the executable file. +or finding resources located relative to the executable file. Both +working directory and the os.Args[0] value are arbitrary and cannot +be relied on; os.Args[0] can be "faked". Multi-platform and supports: * Linux diff --git a/Godeps/_workspace/src/github.com/kardianos/osext/osext.go b/Godeps/_workspace/src/github.com/kardianos/osext/osext.go index 4ed4b9aa3..0eca579ec 100644 --- a/Godeps/_workspace/src/github.com/kardianos/osext/osext.go +++ b/Godeps/_workspace/src/github.com/kardianos/osext/osext.go @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // Extensions to the standard "os" package. -package osext +package osext // import "github.com/kardianos/osext" import "path/filepath" @@ -16,12 +16,12 @@ func Executable() (string, error) { } // Returns same path as Executable, returns just the folder -// path. Excludes the executable name. +// path. Excludes the executable name and any trailing slash. func ExecutableFolder() (string, error) { p, err := Executable() if err != nil { return "", err } - folder, _ := filepath.Split(p) - return folder, nil + + return filepath.Dir(p), nil } diff --git a/Godeps/_workspace/src/github.com/kardianos/osext/osext_test.go b/Godeps/_workspace/src/github.com/kardianos/osext/osext_test.go index 5aafa3af2..77ccc28e9 100644 --- a/Godeps/_workspace/src/github.com/kardianos/osext/osext_test.go +++ b/Godeps/_workspace/src/github.com/kardianos/osext/osext_test.go @@ -24,6 +24,29 @@ const ( executableEnvValueDelete = "delete" ) +func TestPrintExecutable(t *testing.T) { + ef, err := Executable() + if err != nil { + t.Fatalf("Executable failed: %v", err) + } + t.Log("Executable:", ef) +} +func TestPrintExecutableFolder(t *testing.T) { + ef, err := ExecutableFolder() + if err != nil { + t.Fatalf("ExecutableFolder failed: %v", err) + } + t.Log("Executable Folder:", ef) +} +func TestExecutableFolder(t *testing.T) { + ef, err := ExecutableFolder() + if err != nil { + t.Fatalf("ExecutableFolder failed: %v", err) + } + if ef[len(ef)-1] == filepath.Separator { + t.Fatal("ExecutableFolder ends with a trailing slash.") + } +} func TestExecutableMatch(t *testing.T) { ep, err := Executable() if err != nil { diff --git a/Godeps/_workspace/src/github.com/lib/pq/bench_test.go b/Godeps/_workspace/src/github.com/lib/pq/bench_test.go index 611edf87f..e71f41d06 100644 --- a/Godeps/_workspace/src/github.com/lib/pq/bench_test.go +++ b/Godeps/_workspace/src/github.com/lib/pq/bench_test.go @@ -325,7 +325,7 @@ var testIntBytes = []byte("1234") func BenchmarkDecodeInt64(b *testing.B) { for i := 0; i < b.N; i++ { - decode(¶meterStatus{}, testIntBytes, oid.T_int8) + decode(¶meterStatus{}, testIntBytes, oid.T_int8, formatText) } } @@ -333,7 +333,7 @@ var testFloatBytes = []byte("3.14159") func BenchmarkDecodeFloat64(b *testing.B) { for i := 0; i < b.N; i++ { - decode(¶meterStatus{}, testFloatBytes, oid.T_float8) + decode(¶meterStatus{}, testFloatBytes, oid.T_float8, formatText) } } @@ -341,7 +341,7 @@ var testBoolBytes = []byte{'t'} func BenchmarkDecodeBool(b *testing.B) { for i := 0; i < b.N; i++ { - decode(¶meterStatus{}, testBoolBytes, oid.T_bool) + decode(¶meterStatus{}, testBoolBytes, oid.T_bool, formatText) } } @@ -358,7 +358,7 @@ var testTimestamptzBytes = []byte("2013-09-17 22:15:32.360754-07") func BenchmarkDecodeTimestamptz(b *testing.B) { for i := 0; i < b.N; i++ { - decode(¶meterStatus{}, testTimestamptzBytes, oid.T_timestamptz) + decode(¶meterStatus{}, testTimestamptzBytes, oid.T_timestamptz, formatText) } } @@ -371,7 +371,7 @@ func BenchmarkDecodeTimestamptzMultiThread(b *testing.B) { f := func(wg *sync.WaitGroup, loops int) { defer wg.Done() for i := 0; i < loops; i++ { - decode(¶meterStatus{}, testTimestamptzBytes, oid.T_timestamptz) + decode(¶meterStatus{}, testTimestamptzBytes, oid.T_timestamptz, formatText) } } diff --git a/Godeps/_workspace/src/github.com/lib/pq/buf.go b/Godeps/_workspace/src/github.com/lib/pq/buf.go index fd966c394..e7ff57771 100644 --- a/Godeps/_workspace/src/github.com/lib/pq/buf.go +++ b/Godeps/_workspace/src/github.com/lib/pq/buf.go @@ -47,28 +47,44 @@ func (b *readBuf) byte() byte { return b.next(1)[0] } -type writeBuf []byte +type writeBuf struct { + buf []byte + pos int +} func (b *writeBuf) int32(n int) { x := make([]byte, 4) binary.BigEndian.PutUint32(x, uint32(n)) - *b = append(*b, x...) + b.buf = append(b.buf, x...) } func (b *writeBuf) int16(n int) { x := make([]byte, 2) binary.BigEndian.PutUint16(x, uint16(n)) - *b = append(*b, x...) + b.buf = append(b.buf, x...) } func (b *writeBuf) string(s string) { - *b = append(*b, (s + "\000")...) + b.buf = append(b.buf, (s + "\000")...) } func (b *writeBuf) byte(c byte) { - *b = append(*b, c) + b.buf = append(b.buf, c) } func (b *writeBuf) bytes(v []byte) { - *b = append(*b, v...) + b.buf = append(b.buf, v...) +} + +func (b *writeBuf) wrap() []byte { + p := b.buf[b.pos:] + binary.BigEndian.PutUint32(p, uint32(len(p))) + return b.buf +} + +func (b *writeBuf) next(c byte) { + p := b.buf[b.pos:] + binary.BigEndian.PutUint32(p, uint32(len(p))) + b.pos = len(b.buf) + 1 + b.buf = append(b.buf, c, 0, 0, 0, 0) } diff --git a/Godeps/_workspace/src/github.com/lib/pq/conn.go b/Godeps/_workspace/src/github.com/lib/pq/conn.go index 0c27984f3..3c26d0180 100644 --- a/Godeps/_workspace/src/github.com/lib/pq/conn.go +++ b/Godeps/_workspace/src/github.com/lib/pq/conn.go @@ -106,12 +106,41 @@ type conn struct { // If true, this connection is bad and all public-facing functions should // return ErrBadConn. bad bool + + // If set, this connection should never use the binary format when + // receiving query results from prepared statements. Only provided for + // debugging. + disablePreparedBinaryResult bool +} + +// Handle driver-side settings in parsed connection string. +func (c *conn) handleDriverSettings(o values) (err error) { + boolSetting := func(key string, val *bool) error { + if value := o.Get(key); value != "" { + if value == "yes" { + *val = true + } else if value == "no" { + *val = false + } else { + return fmt.Errorf("unrecognized value %q for disable_prepared_binary_result", value) + } + } + return nil + } + + err = boolSetting("disable_prepared_binary_result", &c.disablePreparedBinaryResult) + if err != nil { + return err + } + return nil } func (c *conn) writeBuf(b byte) *writeBuf { c.scratch[0] = b - w := writeBuf(c.scratch[:5]) - return &w + return &writeBuf{ + buf: c.scratch[:5], + pos: 1, + } } func Open(name string) (_ driver.Conn, err error) { @@ -119,22 +148,11 @@ func Open(name string) (_ driver.Conn, err error) { } func DialOpen(d Dialer, name string) (_ driver.Conn, err error) { - defer func() { - // Handle any panics during connection initialization. Note that we - // specifically do *not* want to use errRecover(), as that would turn - // any connection errors into ErrBadConns, hiding the real error - // message from the user. - e := recover() - if e == nil { - // Do nothing - return - } - var ok bool - err, ok = e.(error) - if !ok { - err = fmt.Errorf("pq: unexpected error: %#v", e) - } - }() + // Handle any panics during connection initialization. Note that we + // specifically do *not* want to use errRecover(), as that would turn any + // connection errors into ErrBadConns, hiding the real error message from + // the user. + defer errRecoverNoErrBadConn(&err) o := make(values) @@ -203,12 +221,16 @@ func DialOpen(d Dialer, name string) (_ driver.Conn, err error) { } } - c, err := dial(d, o) + cn := &conn{} + err = cn.handleDriverSettings(o) if err != nil { return nil, err } - cn := &conn{c: c} + cn.c, err = dial(d, o) + if err != nil { + return nil, err + } cn.ssl(o) cn.buf = bufio.NewReader(cn.c) cn.startup(o) @@ -505,7 +527,7 @@ func (cn *conn) simpleExec(q string) (res driver.Result, commandTag string, err } } -func (cn *conn) simpleQuery(q string) (res driver.Rows, err error) { +func (cn *conn) simpleQuery(q string) (res *rows, err error) { defer cn.errRecover(&err) st := &stmt{cn: cn, name: ""} @@ -526,7 +548,13 @@ func (cn *conn) simpleQuery(q string) (res driver.Rows, err error) { cn.bad = true errorf("unexpected message %q in simple query execution", t) } - res = &rows{st: st, done: true} + res = &rows{ + cn: cn, + cols: st.cols, + rowTyps: st.rowTyps, + rowFmts: st.rowFmts, + done: true, + } case 'Z': cn.processReadyForQuery(r) // done @@ -545,8 +573,8 @@ func (cn *conn) simpleQuery(q string) (res driver.Rows, err error) { case 'T': // res might be non-nil here if we received a previous // CommandComplete, but that's fine; just overwrite it - res = &rows{st: st} - st.cols, st.rowTyps = parseMeta(r) + res = &rows{cn: cn} + res.cols, res.rowFmts, res.rowTyps = parseMeta(r) // To work around a bug in QueryRow in Go 1.2 and earlier, wait // until the first DataRow has been received. @@ -557,6 +585,54 @@ func (cn *conn) simpleQuery(q string) (res driver.Rows, err error) { } } +// Decides which column formats to use for a prepared statement. The input is +// an array of type oids, one element per result column. +func decideColumnFormats(rowTyps []oid.Oid, forceText bool) (rowFmts []format, rowFmtData []byte) { + if len(rowTyps) == 0 { + return nil, rowFmtDataAllText + } + + rowFmts = make([]format, len(rowTyps)) + if forceText { + return rowFmts, rowFmtDataAllText + } + + allBinary := true + allText := true + for i, o := range rowTyps { + switch o { + // This is the list of types to use binary mode for when receiving them + // through a prepared statement. If a type appears in this list, it + // must also be implemented in binaryDecode in encode.go. + case oid.T_bytea: + fallthrough + case oid.T_int8: + fallthrough + case oid.T_int4: + fallthrough + case oid.T_int2: + rowFmts[i] = formatBinary + allText = false + + default: + allBinary = false + } + } + + if allBinary { + return rowFmts, rowFmtDataAllBinary + } else if allText { + return rowFmts, rowFmtDataAllText + } else { + rowFmtData = make([]byte, 2+len(rowFmts)*2) + binary.BigEndian.PutUint16(rowFmtData, uint16(len(rowFmts))) + for i, v := range rowFmts { + binary.BigEndian.PutUint16(rowFmtData[2+i*2:], uint16(v)) + } + return rowFmts, rowFmtData + } +} + func (cn *conn) prepareTo(q, stmtName string) (_ *stmt, err error) { st := &stmt{cn: cn, name: stmtName} @@ -564,14 +640,13 @@ func (cn *conn) prepareTo(q, stmtName string) (_ *stmt, err error) { b.string(st.name) b.string(q) b.int16(0) - cn.send(b) - b = cn.writeBuf('D') + b.next('D') b.byte('S') b.string(st.name) - cn.send(b) - cn.send(cn.writeBuf('S')) + b.next('S') + cn.send(b) for { t, r := cn.recv1() @@ -585,9 +660,11 @@ func (cn *conn) prepareTo(q, stmtName string) (_ *stmt, err error) { st.paramTyps[i] = r.oid() } case 'T': - st.cols, st.rowTyps = parseMeta(r) + st.cols, st.rowTyps = parseStatementRowDescribe(r) + st.rowFmts, st.rowFmtData = decideColumnFormats(st.rowTyps, cn.disablePreparedBinaryResult) case 'n': // no data + st.rowFmtData = rowFmtDataAllText case 'Z': cn.processReadyForQuery(r) return st, err @@ -647,7 +724,12 @@ func (cn *conn) Query(query string, args []driver.Value) (_ driver.Rows, err err } st.exec(args) - return &rows{st: st}, nil + return &rows{ + cn: cn, + cols: st.cols, + rowTyps: st.rowTyps, + rowFmts: st.rowFmts, + }, nil } // Implement the optional "Execer" interface for one-shot queries @@ -681,16 +763,20 @@ func (cn *conn) Exec(query string, args []driver.Value) (_ driver.Result, err er return r, err } -// Assumes len(*m) is > 5 func (cn *conn) send(m *writeBuf) { - b := (*m)[1:] - binary.BigEndian.PutUint32(b, uint32(len(b))) + _, err := cn.c.Write(m.wrap()) + if err != nil { + panic(err) + } +} - if (*m)[0] == 0 { - *m = b +func (cn *conn) sendStartupPacket(m *writeBuf) { + // sanity check + if m.buf[0] != 0 { + panic("oops") } - _, err := cn.c.Write(*m) + _, err := cn.c.Write((m.wrap())[1:]) if err != nil { panic(err) } @@ -830,7 +916,7 @@ func (cn *conn) ssl(o values) { w := cn.writeBuf(0) w.int32(80877103) - cn.send(w) + cn.sendStartupPacket(w) b := cn.scratch[:1] _, err := io.ReadFull(cn.c, b) @@ -967,6 +1053,8 @@ func isDriverSetting(key string) bool { return true case "connect_timeout": return true + case "disable_prepared_binary_result": + return true default: return false @@ -994,7 +1082,7 @@ func (cn *conn) startup(o values) { w.string(v) } w.string("") - cn.send(w) + cn.sendStartupPacket(w) for { t, r := cn.recv() @@ -1049,13 +1137,26 @@ func (cn *conn) auth(r *readBuf, o values) { } } +type format int + +const formatText format = 0 +const formatBinary format = 1 + +// One result-column format code with the value 1 (i.e. all binary). +var rowFmtDataAllBinary []byte = []byte{0, 1, 0, 1} + +// No result-column format codes (i.e. all text). +var rowFmtDataAllText []byte = []byte{0, 0} + type stmt struct { - cn *conn - name string - cols []string - rowTyps []oid.Oid - paramTyps []oid.Oid - closed bool + cn *conn + name string + cols []string + rowFmts []format + rowFmtData []byte + rowTyps []oid.Oid + paramTyps []oid.Oid + closed bool } func (st *stmt) Close() (err error) { @@ -1098,7 +1199,12 @@ func (st *stmt) Query(v []driver.Value) (r driver.Rows, err error) { defer st.cn.errRecover(&err) st.exec(v) - return &rows{st: st}, nil + return &rows{ + cn: st.cn, + cols: st.cols, + rowTyps: st.rowTyps, + rowFmts: st.rowFmts, + }, nil } func (st *stmt) Exec(v []driver.Value) (res driver.Result, err error) { @@ -1138,7 +1244,7 @@ func (st *stmt) exec(v []driver.Value) { } w := st.cn.writeBuf('B') - w.string("") + w.byte(0) w.string(st.name) w.int16(0) w.int16(len(v)) @@ -1151,15 +1257,14 @@ func (st *stmt) exec(v []driver.Value) { w.bytes(b) } } - w.int16(0) - st.cn.send(w) + w.bytes(st.rowFmtData) - w = st.cn.writeBuf('E') - w.string("") + w.next('E') + w.byte(0) w.int32(0) - st.cn.send(w) - st.cn.send(st.cn.writeBuf('S')) + w.next('S') + st.cn.send(w) var err error for { @@ -1271,9 +1376,12 @@ func (cn *conn) parseComplete(commandTag string) (driver.Result, string) { } type rows struct { - st *stmt - done bool - rb readBuf + cn *conn + cols []string + rowTyps []oid.Oid + rowFmts []format + done bool + rb readBuf } func (rs *rows) Close() error { @@ -1291,7 +1399,7 @@ func (rs *rows) Close() error { } func (rs *rows) Columns() []string { - return rs.st.cols + return rs.cols } func (rs *rows) Next(dest []driver.Value) (err error) { @@ -1299,7 +1407,7 @@ func (rs *rows) Next(dest []driver.Value) (err error) { return io.EOF } - conn := rs.st.cn + conn := rs.cn if conn.bad { return driver.ErrBadConn } @@ -1330,7 +1438,7 @@ func (rs *rows) Next(dest []driver.Value) (err error) { dest[i] = nil continue } - dest[i] = decode(&conn.parameterStatus, rs.rb.next(l), rs.st.rowTyps[i]) + dest[i] = decode(&conn.parameterStatus, rs.rb.next(l), rs.rowTyps[i], rs.rowFmts[i]) } return default: @@ -1392,7 +1500,7 @@ func (c *conn) processReadyForQuery(r *readBuf) { c.txnStatus = transactionStatus(r.byte()) } -func parseMeta(r *readBuf) (cols []string, rowTyps []oid.Oid) { +func parseStatementRowDescribe(r *readBuf) (cols []string, rowTyps []oid.Oid) { n := r.int16() cols = make([]string, n) rowTyps = make([]oid.Oid, n) @@ -1400,7 +1508,24 @@ func parseMeta(r *readBuf) (cols []string, rowTyps []oid.Oid) { cols[i] = r.string() r.next(6) rowTyps[i] = r.oid() - r.next(8) + r.next(6) + // format code not known; always 0 + r.next(2) + } + return +} + +func parseMeta(r *readBuf) (cols []string, rowFmts []format, rowTyps []oid.Oid) { + n := r.int16() + cols = make([]string, n) + rowFmts = make([]format, n) + rowTyps = make([]oid.Oid, n) + for i := range cols { + cols[i] = r.string() + r.next(6) + rowTyps[i] = r.oid() + r.next(6) + rowFmts[i] = format(r.int16()) } return } diff --git a/Godeps/_workspace/src/github.com/lib/pq/conn_test.go b/Godeps/_workspace/src/github.com/lib/pq/conn_test.go index 741fd761a..ec0d55cd8 100644 --- a/Godeps/_workspace/src/github.com/lib/pq/conn_test.go +++ b/Godeps/_workspace/src/github.com/lib/pq/conn_test.go @@ -338,6 +338,7 @@ func TestEncodeDecode(t *testing.T) { '2000-1-1 01:02:03.04-7'::timestamptz, 0::boolean, 123, + -321, 3.14::float8 WHERE E'\\000\\001\\002'::bytea = $1 @@ -366,9 +367,9 @@ func TestEncodeDecode(t *testing.T) { var got2 string var got3 = sql.NullInt64{Valid: true} var got4 time.Time - var got5, got6, got7 interface{} + var got5, got6, got7, got8 interface{} - err = r.Scan(&got1, &got2, &got3, &got4, &got5, &got6, &got7) + err = r.Scan(&got1, &got2, &got3, &got4, &got5, &got6, &got7, &got8) if err != nil { t.Fatal(err) } @@ -397,8 +398,12 @@ func TestEncodeDecode(t *testing.T) { t.Fatalf("expected 123, got %d", got6) } - if got7 != float64(3.14) { - t.Fatalf("expected 3.14, got %f", got7) + if got7 != int64(-321) { + t.Fatalf("expected -321, got %d", got7) + } + + if got8 != float64(3.14) { + t.Fatalf("expected 3.14, got %f", got8) } } diff --git a/Godeps/_workspace/src/github.com/lib/pq/copy_test.go b/Godeps/_workspace/src/github.com/lib/pq/copy_test.go index 14cd8245e..6af4c9c76 100644 --- a/Godeps/_workspace/src/github.com/lib/pq/copy_test.go +++ b/Godeps/_workspace/src/github.com/lib/pq/copy_test.go @@ -387,12 +387,14 @@ func TestCopyRespLoopConnectionError(t *testing.T) { t.Fatal(err) } - // We have to try and send something over, since postgres won't process - // SIGTERMs while it's waiting for CopyData/CopyEnd messages; see - // tcop/postgres.c. - _, err = stmt.Exec(1) - if err != nil { - t.Fatal(err) + if getServerVersion(t, db) < 90500 { + // We have to try and send something over, since postgres before + // version 9.5 won't process SIGTERMs while it's waiting for + // CopyData/CopyEnd messages; see tcop/postgres.c. + _, err = stmt.Exec(1) + if err != nil { + t.Fatal(err) + } } _, err = stmt.Exec() if err == nil { diff --git a/Godeps/_workspace/src/github.com/lib/pq/encode.go b/Godeps/_workspace/src/github.com/lib/pq/encode.go index ad5f9683f..6d8b5e460 100644 --- a/Godeps/_workspace/src/github.com/lib/pq/encode.go +++ b/Godeps/_workspace/src/github.com/lib/pq/encode.go @@ -3,6 +3,7 @@ package pq import ( "bytes" "database/sql/driver" + "encoding/binary" "encoding/hex" "fmt" "math" @@ -44,7 +45,33 @@ func encode(parameterStatus *parameterStatus, x interface{}, pgtypOid oid.Oid) [ panic("not reached") } -func decode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} { +func decode(parameterStatus *parameterStatus, s []byte, typ oid.Oid, f format) interface{} { + if f == formatBinary { + return binaryDecode(parameterStatus, s, typ) + } else { + return textDecode(parameterStatus, s, typ) + } +} + +func binaryDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} { + switch typ { + case oid.T_bytea: + return s + case oid.T_int8: + return int64(binary.BigEndian.Uint64(s)) + case oid.T_int4: + return int64(int32(binary.BigEndian.Uint32(s))) + case oid.T_int2: + return int64(int16(binary.BigEndian.Uint16(s))) + + default: + errorf("don't know how to decode binary parameter of type %u", uint32(typ)) + } + + panic("not reached") +} + +func textDecode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} { switch typ { case oid.T_bytea: return parseBytea(s) @@ -58,7 +85,7 @@ func decode(parameterStatus *parameterStatus, s []byte, typ oid.Oid) interface{} return mustParse("15:04:05-07", typ, s) case oid.T_bool: return s[0] == 't' - case oid.T_int8, oid.T_int2, oid.T_int4: + case oid.T_int8, oid.T_int4, oid.T_int2: i, err := strconv.ParseInt(string(s), 10, 64) if err != nil { errorf("%s", err) diff --git a/Godeps/_workspace/src/github.com/lib/pq/encode_test.go b/Godeps/_workspace/src/github.com/lib/pq/encode_test.go index 50fbaf33f..abfc1156c 100644 --- a/Godeps/_workspace/src/github.com/lib/pq/encode_test.go +++ b/Godeps/_workspace/src/github.com/lib/pq/encode_test.go @@ -2,6 +2,7 @@ package pq import ( "bytes" + "database/sql" "fmt" "testing" "time" @@ -460,7 +461,7 @@ func TestByteaOutputFormats(t *testing.T) { return } - testByteaOutputFormat := func(f string) { + testByteaOutputFormat := func(f string, usePrepared bool) { expectedData := []byte("\x5c\x78\x00\xff\x61\x62\x63\x01\x08") sqlQuery := "SELECT decode('5c7800ff6162630108', 'hex')" @@ -477,8 +478,18 @@ func TestByteaOutputFormats(t *testing.T) { if err != nil { t.Fatal(err) } - // use Query; QueryRow would hide the actual error - rows, err := txn.Query(sqlQuery) + var rows *sql.Rows + var stmt *sql.Stmt + if usePrepared { + stmt, err = txn.Prepare(sqlQuery) + if err != nil { + t.Fatal(err) + } + rows, err = stmt.Query() + } else { + // use Query; QueryRow would hide the actual error + rows, err = txn.Query(sqlQuery) + } if err != nil { t.Fatal(err) } @@ -496,13 +507,21 @@ func TestByteaOutputFormats(t *testing.T) { if err != nil { t.Fatal(err) } + if stmt != nil { + err = stmt.Close() + if err != nil { + t.Fatal(err) + } + } if !bytes.Equal(data, expectedData) { t.Errorf("unexpected bytea value %v for format %s; expected %v", data, f, expectedData) } } - testByteaOutputFormat("hex") - testByteaOutputFormat("escape") + testByteaOutputFormat("hex", false) + testByteaOutputFormat("escape", false) + testByteaOutputFormat("hex", true) + testByteaOutputFormat("escape", true) } func TestAppendEncodedText(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/lib/pq/error.go b/Godeps/_workspace/src/github.com/lib/pq/error.go index 0a49364d9..b4bb44cee 100644 --- a/Godeps/_workspace/src/github.com/lib/pq/error.go +++ b/Godeps/_workspace/src/github.com/lib/pq/error.go @@ -459,6 +459,19 @@ func errorf(s string, args ...interface{}) { panic(fmt.Errorf("pq: %s", fmt.Sprintf(s, args...))) } +func errRecoverNoErrBadConn(err *error) { + e := recover() + if e == nil { + // Do nothing + return + } + var ok bool + *err, ok = e.(error) + if !ok { + *err = fmt.Errorf("pq: unexpected error: %#v", e) + } +} + func (c *conn) errRecover(err *error) { e := recover() switch v := e.(type) { diff --git a/Godeps/_workspace/src/github.com/lib/pq/notify.go b/Godeps/_workspace/src/github.com/lib/pq/notify.go index e3b08d59a..8cad57815 100644 --- a/Godeps/_workspace/src/github.com/lib/pq/notify.go +++ b/Godeps/_workspace/src/github.com/lib/pq/notify.go @@ -6,7 +6,6 @@ package pq import ( "errors" "fmt" - "io" "sync" "sync/atomic" "time" @@ -87,12 +86,16 @@ func NewListenerConn(name string, notificationChan chan<- *Notification) (*Liste // Returns an error if an unrecoverable error has occurred and the ListenerConn // should be abandoned. func (l *ListenerConn) acquireSenderLock() error { - l.connectionLock.Lock() - defer l.connectionLock.Unlock() - if l.err != nil { - return l.err - } + // we must acquire senderLock first to avoid deadlocks; see ExecSimpleQuery l.senderLock.Lock() + + l.connectionLock.Lock() + err := l.err + l.connectionLock.Unlock() + if err != nil { + l.senderLock.Unlock() + return err + } return nil } @@ -125,7 +128,7 @@ func (l *ListenerConn) setState(newState int32) bool { // away or should be discarded because we couldn't agree on the state with the // server backend. func (l *ListenerConn) listenerConnLoop() (err error) { - defer l.cn.errRecover(&err) + defer errRecoverNoErrBadConn(&err) r := &readBuf{} for { @@ -140,6 +143,9 @@ func (l *ListenerConn) listenerConnLoop() (err error) { // about the scratch buffer being overwritten. l.notificationChan <- recvNotification(r) + case 'T', 'D': + // only used by tests; ignore + case 'E': // We might receive an ErrorResponse even when not in a query; it // is expected that the server will close the connection after @@ -238,7 +244,7 @@ func (l *ListenerConn) Ping() error { // The caller must be holding senderLock (see acquireSenderLock and // releaseSenderLock). func (l *ListenerConn) sendSimpleQuery(q string) (err error) { - defer l.cn.errRecover(&err) + defer errRecoverNoErrBadConn(&err) // must set connection state before sending the query if !l.setState(connStateExpectResponse) { @@ -247,8 +253,10 @@ func (l *ListenerConn) sendSimpleQuery(q string) (err error) { // Can't use l.cn.writeBuf here because it uses the scratch buffer which // might get overwritten by listenerConnLoop. - data := writeBuf([]byte("Q\x00\x00\x00\x00")) - b := &data + b := &writeBuf{ + buf: []byte("Q\x00\x00\x00\x00"), + pos: 1, + } b.string(q) l.cn.send(b) @@ -277,13 +285,13 @@ func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error) { // We can't know what state the protocol is in, so we need to abandon // this connection. l.connectionLock.Lock() - defer l.connectionLock.Unlock() // Set the error pointer if it hasn't been set already; see // listenerConnMain. if l.err == nil { l.err = err } - l.cn.Close() + l.connectionLock.Unlock() + l.cn.c.Close() return false, err } @@ -292,8 +300,11 @@ func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error) { m, ok := <-l.replyChan if !ok { // We lost the connection to server, don't bother waiting for a - // a response. - return false, io.EOF + // a response. err should have been set already. + l.connectionLock.Lock() + err := l.err + l.connectionLock.Unlock() + return false, err } switch m.typ { case 'Z': @@ -320,12 +331,15 @@ func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error) { func (l *ListenerConn) Close() error { l.connectionLock.Lock() - defer l.connectionLock.Unlock() if l.err != nil { + l.connectionLock.Unlock() return errListenerConnClosed } l.err = errListenerConnClosed - return l.cn.Close() + l.connectionLock.Unlock() + // We can't send anything on the connection without holding senderLock. + // Simply close the net.Conn to wake up everyone operating on it. + return l.cn.c.Close() } // Err() returns the reason the connection was closed. It is not safe to call diff --git a/Godeps/_workspace/src/github.com/lib/pq/notify_test.go b/Godeps/_workspace/src/github.com/lib/pq/notify_test.go index 73dcb750d..fe8941a4e 100644 --- a/Godeps/_workspace/src/github.com/lib/pq/notify_test.go +++ b/Godeps/_workspace/src/github.com/lib/pq/notify_test.go @@ -5,6 +5,9 @@ import ( "fmt" "io" "os" + "runtime" + "sync" + "sync/atomic" "testing" "time" ) @@ -210,6 +213,75 @@ func TestConnPing(t *testing.T) { } } +// Test for deadlock where a query fails while another one is queued +func TestConnExecDeadlock(t *testing.T) { + l, _ := newTestListenerConn(t) + defer l.Close() + + var wg sync.WaitGroup + wg.Add(2) + + go func() { + l.ExecSimpleQuery("SELECT pg_sleep(60)") + wg.Done() + }() + runtime.Gosched() + go func() { + l.ExecSimpleQuery("SELECT 1") + wg.Done() + }() + // give the two goroutines some time to get into position + runtime.Gosched() + // calls Close on the net.Conn; equivalent to a network failure + l.Close() + + var done int32 = 0 + go func() { + time.Sleep(10 * time.Second) + if atomic.LoadInt32(&done) != 1 { + panic("timed out") + } + }() + wg.Wait() + atomic.StoreInt32(&done, 1) +} + +// Test for ListenerConn being closed while a slow query is executing +func TestListenerConnCloseWhileQueryIsExecuting(t *testing.T) { + l, _ := newTestListenerConn(t) + defer l.Close() + + var wg sync.WaitGroup + wg.Add(1) + + go func() { + sent, err := l.ExecSimpleQuery("SELECT pg_sleep(60)") + if sent { + panic("expected sent=false") + } + // could be any of a number of errors + if err == nil { + panic("expected error") + } + wg.Done() + }() + // give the above goroutine some time to get into position + runtime.Gosched() + err := l.Close() + if err != nil { + t.Fatal(err) + } + var done int32 = 0 + go func() { + time.Sleep(10 * time.Second) + if atomic.LoadInt32(&done) != 1 { + panic("timed out") + } + }() + wg.Wait() + atomic.StoreInt32(&done, 1) +} + func TestNotifyExtra(t *testing.T) { db := openTestConn(t) defer db.Close() diff --git a/Godeps/_workspace/src/github.com/mitchellh/cli/README.md b/Godeps/_workspace/src/github.com/mitchellh/cli/README.md index 60d46045d..5afa0944a 100644 --- a/Godeps/_workspace/src/github.com/mitchellh/cli/README.md +++ b/Godeps/_workspace/src/github.com/mitchellh/cli/README.md @@ -10,6 +10,9 @@ cli is the library that powers the CLI for * Easy sub-command based CLIs: `cli foo`, `cli bar`, etc. +* Optional support for default subcommands so `cli` does something + other than error. + * Automatic help generation for listing subcommands * Automatic help flag recognition of `-h`, `--help`, etc. diff --git a/Godeps/_workspace/src/github.com/mitchellh/cli/cli.go b/Godeps/_workspace/src/github.com/mitchellh/cli/cli.go index 56459ed70..bb676e321 100644 --- a/Godeps/_workspace/src/github.com/mitchellh/cli/cli.go +++ b/Godeps/_workspace/src/github.com/mitchellh/cli/cli.go @@ -15,7 +15,9 @@ type CLI struct { Args []string // Commands is a mapping of subcommand names to a factory function - // for creating that Command implementation. + // for creating that Command implementation. If there is a command + // with a blank string "", then it will be used as the default command + // if no subcommand is specified. Commands map[string]CommandFactory // Name defines the name of the CLI. @@ -40,6 +42,7 @@ type CLI struct { isHelp bool subcommand string subcommandArgs []string + topFlags []string isVersion bool } @@ -78,10 +81,19 @@ func (c *CLI) Run() (int, error) { return 1, nil } + // If there is an invalid flag, then error + if len(c.topFlags) > 0 { + c.HelpWriter.Write([]byte( + "Invalid flags before the subcommand. If these flags are for\n" + + "the subcommand, please put them after the subcommand.\n\n")) + c.HelpWriter.Write([]byte(c.HelpFunc(c.Commands) + "\n")) + return 1, nil + } + // Attempt to get the factory function for creating the command // implementation. If the command is invalid or blank, it is an error. commandFunc, ok := c.Commands[c.Subcommand()] - if !ok || c.Subcommand() == "" { + if !ok { c.HelpWriter.Write([]byte(c.HelpFunc(c.Commands) + "\n")) return 1, nil } @@ -133,7 +145,6 @@ func (c *CLI) init() { func (c *CLI) processArgs() { for i, arg := range c.Args { - if c.subcommand == "" { // Check for version and help flags if not in a subcommand if arg == "-v" || arg == "-version" || arg == "--version" { @@ -144,15 +155,31 @@ func (c *CLI) processArgs() { c.isHelp = true continue } + + if arg != "" && arg[0] == '-' { + // Record the arg... + c.topFlags = append(c.topFlags, arg) + } } // If we didn't find a subcommand yet and this is the first non-flag // argument, then this is our subcommand. j - if c.subcommand == "" && arg[0] != '-' { + if c.subcommand == "" && arg != "" && arg[0] != '-' { c.subcommand = arg // The remaining args the subcommand arguments c.subcommandArgs = c.Args[i+1:] } } + + // If we never found a subcommand and support a default command, then + // switch to using that. + if c.subcommand == "" { + if _, ok := c.Commands[""]; ok { + args := c.topFlags + args = append(args, c.subcommandArgs...) + c.topFlags = nil + c.subcommandArgs = args + } + } } diff --git a/Godeps/_workspace/src/github.com/mitchellh/cli/cli_test.go b/Godeps/_workspace/src/github.com/mitchellh/cli/cli_test.go index 9ec5f9a19..8b0af00e0 100644 --- a/Godeps/_workspace/src/github.com/mitchellh/cli/cli_test.go +++ b/Godeps/_workspace/src/github.com/mitchellh/cli/cli_test.go @@ -3,6 +3,7 @@ package cli import ( "bytes" "reflect" + "strings" "testing" ) @@ -87,11 +88,75 @@ func TestCLIRun(t *testing.T) { } } +func TestCLIRun_blank(t *testing.T) { + command := new(MockCommand) + cli := &CLI{ + Args: []string{"", "foo", "-bar", "-baz"}, + Commands: map[string]CommandFactory{ + "foo": func() (Command, error) { + return command, nil + }, + }, + } + + exitCode, err := cli.Run() + if err != nil { + t.Fatalf("err: %s", err) + } + + if exitCode != command.RunResult { + t.Fatalf("bad: %d", exitCode) + } + + if !command.RunCalled { + t.Fatalf("run should be called") + } + + if !reflect.DeepEqual(command.RunArgs, []string{"-bar", "-baz"}) { + t.Fatalf("bad args: %#v", command.RunArgs) + } +} + +func TestCLIRun_default(t *testing.T) { + commandBar := new(MockCommand) + commandBar.RunResult = 42 + + cli := &CLI{ + Args: []string{"-bar", "-baz"}, + Commands: map[string]CommandFactory{ + "": func() (Command, error) { + return commandBar, nil + }, + "foo": func() (Command, error) { + return new(MockCommand), nil + }, + }, + } + + exitCode, err := cli.Run() + if err != nil { + t.Fatalf("err: %s", err) + } + + if exitCode != commandBar.RunResult { + t.Fatalf("bad: %d", exitCode) + } + + if !commandBar.RunCalled { + t.Fatalf("run should be called") + } + + if !reflect.DeepEqual(commandBar.RunArgs, []string{"-bar", "-baz"}) { + t.Fatalf("bad args: %#v", commandBar.RunArgs) + } +} + func TestCLIRun_printHelp(t *testing.T) { testCases := [][]string{ {}, {"-h"}, {"i-dont-exist"}, + {"-bad-flag", "foo"}, } for _, testCase := range testCases { @@ -100,6 +165,11 @@ func TestCLIRun_printHelp(t *testing.T) { cli := &CLI{ Args: testCase, + Commands: map[string]CommandFactory{ + "foo": func() (Command, error) { + return new(MockCommand), nil + }, + }, HelpFunc: func(map[string]CommandFactory) string { return helpText }, @@ -117,7 +187,7 @@ func TestCLIRun_printHelp(t *testing.T) { continue } - if buf.String() != (helpText + "\n") { + if !strings.Contains(buf.String(), helpText) { t.Errorf("Args: %#v. Text: %v", testCase, buf.String()) } } diff --git a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/.travis.yml b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/.travis.yml new file mode 100644 index 000000000..7f3fe9a96 --- /dev/null +++ b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/.travis.yml @@ -0,0 +1,7 @@ +language: go + +go: + - 1.4 + +script: + - go test diff --git a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/decode_hooks.go b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/decode_hooks.go index 087a392b9..aa91f76ce 100644 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/decode_hooks.go +++ b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/decode_hooks.go @@ -1,11 +1,59 @@ package mapstructure import ( + "errors" "reflect" "strconv" "strings" + "time" ) +// typedDecodeHook takes a raw DecodeHookFunc (an interface{}) and turns +// it into the proper DecodeHookFunc type, such as DecodeHookFuncType. +func typedDecodeHook(h DecodeHookFunc) DecodeHookFunc { + // Create variables here so we can reference them with the reflect pkg + var f1 DecodeHookFuncType + var f2 DecodeHookFuncKind + + // Fill in the variables into this interface and the rest is done + // automatically using the reflect package. + potential := []interface{}{f1, f2} + + v := reflect.ValueOf(h) + vt := v.Type() + for _, raw := range potential { + pt := reflect.ValueOf(raw).Type() + if vt.ConvertibleTo(pt) { + return v.Convert(pt).Interface() + } + } + + return nil +} + +// DecodeHookExec executes the given decode hook. This should be used +// since it'll naturally degrade to the older backwards compatible DecodeHookFunc +// that took reflect.Kind instead of reflect.Type. +func DecodeHookExec( + raw DecodeHookFunc, + from reflect.Type, to reflect.Type, + data interface{}) (interface{}, error) { + // Build our arguments that reflect expects + argVals := make([]reflect.Value, 3) + argVals[0] = reflect.ValueOf(from) + argVals[1] = reflect.ValueOf(to) + argVals[2] = reflect.ValueOf(data) + + switch f := typedDecodeHook(raw).(type) { + case DecodeHookFuncType: + return f(from, to, data) + case DecodeHookFuncKind: + return f(from.Kind(), to.Kind(), data) + default: + return nil, errors.New("invalid decode hook signature") + } +} + // ComposeDecodeHookFunc creates a single DecodeHookFunc that // automatically composes multiple DecodeHookFuncs. // @@ -13,18 +61,18 @@ import ( // previous transformation. func ComposeDecodeHookFunc(fs ...DecodeHookFunc) DecodeHookFunc { return func( - f reflect.Kind, - t reflect.Kind, + f reflect.Type, + t reflect.Type, data interface{}) (interface{}, error) { var err error for _, f1 := range fs { - data, err = f1(f, t, data) + data, err = DecodeHookExec(f1, f, t, data) if err != nil { return nil, err } // Modify the from kind to be correct with the new data - f = getKind(reflect.ValueOf(data)) + f = reflect.ValueOf(data).Type() } return data, nil @@ -51,6 +99,25 @@ func StringToSliceHookFunc(sep string) DecodeHookFunc { } } +// StringToTimeDurationHookFunc returns a DecodeHookFunc that converts +// strings to time.Duration. +func StringToTimeDurationHookFunc() DecodeHookFunc { + return func( + f reflect.Type, + t reflect.Type, + data interface{}) (interface{}, error) { + if f.Kind() != reflect.String { + return data, nil + } + if t != reflect.TypeOf(time.Duration(5)) { + return data, nil + } + + // Convert it by parsing + return time.ParseDuration(data.(string)) + } +} + func WeaklyTypedHook( f reflect.Kind, t reflect.Kind, diff --git a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/decode_hooks_test.go b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/decode_hooks_test.go index b417deeb6..53289afcf 100644 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/decode_hooks_test.go +++ b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/decode_hooks_test.go @@ -4,6 +4,7 @@ import ( "errors" "reflect" "testing" + "time" ) func TestComposeDecodeHookFunc(t *testing.T) { @@ -23,7 +24,8 @@ func TestComposeDecodeHookFunc(t *testing.T) { f := ComposeDecodeHookFunc(f1, f2) - result, err := f(reflect.String, reflect.Slice, "") + result, err := DecodeHookExec( + f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), "") if err != nil { t.Fatalf("bad: %s", err) } @@ -43,7 +45,8 @@ func TestComposeDecodeHookFunc_err(t *testing.T) { f := ComposeDecodeHookFunc(f1, f2) - _, err := f(reflect.String, reflect.Slice, 42) + _, err := DecodeHookExec( + f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), 42) if err.Error() != "foo" { t.Fatalf("bad: %s", err) } @@ -69,7 +72,8 @@ func TestComposeDecodeHookFunc_kinds(t *testing.T) { f := ComposeDecodeHookFunc(f1, f2) - _, err := f(reflect.String, reflect.Slice, "") + _, err := DecodeHookExec( + f, reflect.TypeOf(""), reflect.TypeOf([]byte("")), "") if err != nil { t.Fatalf("bad: %s", err) } @@ -81,24 +85,26 @@ func TestComposeDecodeHookFunc_kinds(t *testing.T) { func TestStringToSliceHookFunc(t *testing.T) { f := StringToSliceHookFunc(",") + strType := reflect.TypeOf("") + sliceType := reflect.TypeOf([]byte("")) cases := []struct { - f, t reflect.Kind + f, t reflect.Type data interface{} result interface{} err bool }{ - {reflect.Slice, reflect.Slice, 42, 42, false}, - {reflect.String, reflect.String, 42, 42, false}, + {sliceType, sliceType, 42, 42, false}, + {strType, strType, 42, 42, false}, { - reflect.String, - reflect.Slice, + strType, + sliceType, "foo,bar,baz", []string{"foo", "bar", "baz"}, false, }, { - reflect.String, - reflect.Slice, + strType, + sliceType, "", []string{}, false, @@ -106,7 +112,36 @@ func TestStringToSliceHookFunc(t *testing.T) { } for i, tc := range cases { - actual, err := f(tc.f, tc.t, tc.data) + actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data) + if tc.err != (err != nil) { + t.Fatalf("case %d: expected err %#v", i, tc.err) + } + if !reflect.DeepEqual(actual, tc.result) { + t.Fatalf( + "case %d: expected %#v, got %#v", + i, tc.result, actual) + } + } +} + +func TestStringToTimeDurationHookFunc(t *testing.T) { + f := StringToTimeDurationHookFunc() + + strType := reflect.TypeOf("") + timeType := reflect.TypeOf(time.Duration(5)) + cases := []struct { + f, t reflect.Type + data interface{} + result interface{} + err bool + }{ + {strType, timeType, "5s", 5 * time.Second, false}, + {strType, timeType, "5", time.Duration(0), true}, + {strType, strType, "5", "5", false}, + } + + for i, tc := range cases { + actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data) if tc.err != (err != nil) { t.Fatalf("case %d: expected err %#v", i, tc.err) } @@ -121,56 +156,59 @@ func TestStringToSliceHookFunc(t *testing.T) { func TestWeaklyTypedHook(t *testing.T) { var f DecodeHookFunc = WeaklyTypedHook + boolType := reflect.TypeOf(true) + strType := reflect.TypeOf("") + sliceType := reflect.TypeOf([]byte("")) cases := []struct { - f, t reflect.Kind + f, t reflect.Type data interface{} result interface{} err bool }{ // TO STRING { - reflect.Bool, - reflect.String, + boolType, + strType, false, "0", false, }, { - reflect.Bool, - reflect.String, + boolType, + strType, true, "1", false, }, { - reflect.Float32, - reflect.String, + reflect.TypeOf(float32(1)), + strType, float32(7), "7", false, }, { - reflect.Int, - reflect.String, + reflect.TypeOf(int(1)), + strType, int(7), "7", false, }, { - reflect.Slice, - reflect.String, + sliceType, + strType, []uint8("foo"), "foo", false, }, { - reflect.Uint, - reflect.String, + reflect.TypeOf(uint(1)), + strType, uint(7), "7", false, @@ -178,7 +216,7 @@ func TestWeaklyTypedHook(t *testing.T) { } for i, tc := range cases { - actual, err := f(tc.f, tc.t, tc.data) + actual, err := DecodeHookExec(f, tc.f, tc.t, tc.data) if tc.err != (err != nil) { t.Fatalf("case %d: expected err %#v", i, tc.err) } diff --git a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/error.go b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/error.go index f97c4164d..47a99e5af 100644 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/error.go +++ b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/error.go @@ -1,6 +1,7 @@ package mapstructure import ( + "errors" "fmt" "sort" "strings" @@ -24,6 +25,21 @@ func (e *Error) Error() string { len(e.Errors), strings.Join(points, "\n")) } +// WrappedErrors implements the errwrap.Wrapper interface to make this +// return value more useful with the errwrap and go-multierror libraries. +func (e *Error) WrappedErrors() []error { + if e == nil { + return nil + } + + result := make([]error, len(e.Errors)) + for i, e := range e.Errors { + result[i] = errors.New(e) + } + + return result +} + func appendErrors(errors []string, err error) []string { switch e := err.(type) { case *Error: diff --git a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure.go b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure.go index 381ba5d48..40be5116d 100644 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure.go +++ b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure.go @@ -19,10 +19,20 @@ import ( // DecodeHookFunc is the callback function that can be used for // data transformations. See "DecodeHook" in the DecoderConfig // struct. -type DecodeHookFunc func( - from reflect.Kind, - to reflect.Kind, - data interface{}) (interface{}, error) +// +// The type should be DecodeHookFuncType or DecodeHookFuncKind. +// Either is accepted. Types are a superset of Kinds (Types can return +// Kinds) and are generally a richer thing to use, but Kinds are simpler +// if you only need those. +// +// The reason DecodeHookFunc is multi-typed is for backwards compatibility: +// we started with Kinds and then realized Types were the better solution, +// but have a promise to not break backwards compat so we now support +// both. +type DecodeHookFunc interface{} + +type DecodeHookFuncType func(reflect.Type, reflect.Type, interface{}) (interface{}, error) +type DecodeHookFuncKind func(reflect.Kind, reflect.Kind, interface{}) (interface{}, error) // DecoderConfig is the configuration that is used to create a new decoder // and allows customization of various aspects of decoding. @@ -40,6 +50,11 @@ type DecoderConfig struct { // (extra keys). ErrorUnused bool + // ZeroFields, if set to true, will zero fields before writing them. + // For example, a map will be emptied before decoded values are put in + // it. If this is false, a map will be merged. + ZeroFields bool + // If WeaklyTypedInput is true, the decoder will make the following // "weak" conversions: // @@ -51,6 +66,7 @@ type DecoderConfig struct { // - string to bool (accepts: 1, t, T, TRUE, true, True, 0, f, F, // FALSE, false, False. Anything else is an error) // - empty array = empty map and vice versa + // - negative numbers to overflowed uint values (base 10) // WeaklyTypedInput bool @@ -180,7 +196,9 @@ func (d *Decoder) decode(name string, data interface{}, val reflect.Value) error if d.config.DecodeHook != nil { // We have a DecodeHook, so let's pre-process the data. var err error - data, err = d.config.DecodeHook(getKind(dataVal), getKind(val), data) + data, err = DecodeHookExec( + d.config.DecodeHook, + dataVal.Type(), val.Type(), data) if err != nil { return err } @@ -319,11 +337,21 @@ func (d *Decoder) decodeUint(name string, data interface{}, val reflect.Value) e switch { case dataKind == reflect.Int: - val.SetUint(uint64(dataVal.Int())) + i := dataVal.Int() + if i < 0 && !d.config.WeaklyTypedInput { + return fmt.Errorf("cannot parse '%s', %d overflows uint", + name, i) + } + val.SetUint(uint64(i)) case dataKind == reflect.Uint: val.SetUint(dataVal.Uint()) case dataKind == reflect.Float32: - val.SetUint(uint64(dataVal.Float())) + f := dataVal.Float() + if f < 0 && !d.config.WeaklyTypedInput { + return fmt.Errorf("cannot parse '%s', %f overflows uint", + name, f) + } + val.SetUint(uint64(f)) case dataKind == reflect.Bool && d.config.WeaklyTypedInput: if dataVal.Bool() { val.SetUint(1) @@ -415,9 +443,15 @@ func (d *Decoder) decodeMap(name string, data interface{}, val reflect.Value) er valKeyType := valType.Key() valElemType := valType.Elem() - // Make a new map to hold our result - mapType := reflect.MapOf(valKeyType, valElemType) - valMap := reflect.MakeMap(mapType) + // By default we overwrite keys in the current map + valMap := val + + // If the map is nil or we're purposely zeroing fields, make a new map + if valMap.IsNil() || d.config.ZeroFields { + // Make a new map to hold our result + mapType := reflect.MapOf(valKeyType, valElemType) + valMap = reflect.MakeMap(mapType) + } // Check input type dataVal := reflect.Indirect(reflect.ValueOf(data)) @@ -530,6 +564,14 @@ func (d *Decoder) decodeSlice(name string, data interface{}, val reflect.Value) func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) error { dataVal := reflect.Indirect(reflect.ValueOf(data)) + + // If the type of the value to write to and the data match directly, + // then we just set it directly instead of recursing into the structure. + if dataVal.Type() == val.Type() { + val.Set(dataVal) + return nil + } + dataValKind := dataVal.Kind() if dataValKind != reflect.Map { return fmt.Errorf("'%s' expected a map, got '%s'", name, dataValKind) @@ -575,22 +617,21 @@ func (d *Decoder) decodeStruct(name string, data interface{}, val reflect.Value) fmt.Errorf("%s: unsupported type: %s", fieldType.Name, fieldKind)) continue } + } - // We have an embedded field. We "squash" the fields down - // if specified in the tag. - squash := false - tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",") - for _, tag := range tagParts[1:] { - if tag == "squash" { - squash = true - break - } + // If "squash" is specified in the tag, we squash the field down. + squash := false + tagParts := strings.Split(fieldType.Tag.Get(d.config.TagName), ",") + for _, tag := range tagParts[1:] { + if tag == "squash" { + squash = true + break } + } - if squash { - structs = append(structs, val.FieldByName(fieldType.Name)) - continue - } + if squash { + structs = append(structs, val.FieldByName(fieldType.Name)) + continue } // Normal struct field, store it away diff --git a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_test.go b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_test.go index 036e6b5f5..8a27647b5 100644 --- a/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_test.go +++ b/Godeps/_workspace/src/github.com/mitchellh/mapstructure/mapstructure_test.go @@ -17,6 +17,10 @@ type Basic struct { Vdata interface{} } +type BasicSquash struct { + Test Basic `mapstructure:",squash"` +} + type Embedded struct { Basic Vunique string @@ -158,6 +162,47 @@ func TestBasic_IntWithFloat(t *testing.T) { } } +func TestBasic_Merge(t *testing.T) { + t.Parallel() + + input := map[string]interface{}{ + "vint": 42, + } + + var result Basic + result.Vuint = 100 + err := Decode(input, &result) + if err != nil { + t.Fatalf("got an err: %s", err) + } + + expected := Basic{ + Vint: 42, + Vuint: 100, + } + if !reflect.DeepEqual(result, expected) { + t.Fatalf("bad: %#v", result) + } +} + +func TestDecode_BasicSquash(t *testing.T) { + t.Parallel() + + input := map[string]interface{}{ + "vstring": "foo", + } + + var result BasicSquash + err := Decode(input, &result) + if err != nil { + t.Fatalf("got an err: %s", err.Error()) + } + + if result.Test.Vstring != "foo" { + t.Errorf("vstring value should be 'foo': %#v", result.Test.Vstring) + } +} + func TestDecode_Embedded(t *testing.T) { t.Parallel() @@ -261,6 +306,43 @@ func TestDecode_DecodeHook(t *testing.T) { } } +func TestDecode_DecodeHookType(t *testing.T) { + t.Parallel() + + input := map[string]interface{}{ + "vint": "WHAT", + } + + decodeHook := func(from reflect.Type, to reflect.Type, v interface{}) (interface{}, error) { + if from.Kind() == reflect.String && + to.Kind() != reflect.String { + return 5, nil + } + + return v, nil + } + + var result Basic + config := &DecoderConfig{ + DecodeHook: decodeHook, + Result: &result, + } + + decoder, err := NewDecoder(config) + if err != nil { + t.Fatalf("err: %s", err) + } + + err = decoder.Decode(input) + if err != nil { + t.Fatalf("got an err: %s", err) + } + + if result.Vint != 5 { + t.Errorf("vint should be 5: %#v", result.Vint) + } +} + func TestDecode_Nil(t *testing.T) { t.Parallel() @@ -298,6 +380,26 @@ func TestDecode_NonStruct(t *testing.T) { } } +func TestDecode_StructMatch(t *testing.T) { + t.Parallel() + + input := map[string]interface{}{ + "vbar": Basic{ + Vstring: "foo", + }, + } + + var result Nested + err := Decode(input, &result) + if err != nil { + t.Fatalf("got an err: %s", err.Error()) + } + + if result.Vbar.Vstring != "foo" { + t.Errorf("bad: %#v", result) + } +} + func TestDecode_TypeConversion(t *testing.T) { input := map[string]interface{}{ "IntToFloat": 42, @@ -460,6 +562,38 @@ func TestMap(t *testing.T) { } } +func TestMapMerge(t *testing.T) { + t.Parallel() + + input := map[string]interface{}{ + "vfoo": "foo", + "vother": map[interface{}]interface{}{ + "foo": "foo", + "bar": "bar", + }, + } + + var result Map + result.Vother = map[string]string{"hello": "world"} + err := Decode(input, &result) + if err != nil { + t.Fatalf("got an error: %s", err) + } + + if result.Vfoo != "foo" { + t.Errorf("vfoo value should be 'foo': %#v", result.Vfoo) + } + + expected := map[string]string{ + "foo": "foo", + "bar": "bar", + "hello": "world", + } + if !reflect.DeepEqual(result.Vother, expected) { + t.Errorf("bad: %#v", result.Vother) + } +} + func TestMapOfStruct(t *testing.T) { t.Parallel() @@ -658,6 +792,42 @@ func TestInvalidType(t *testing.T) { if derr.Errors[0] != "'Vstring' expected type 'string', got unconvertible type 'int'" { t.Errorf("got unexpected error: %s", err) } + + inputNegIntUint := map[string]interface{}{ + "vuint": -42, + } + + err = Decode(inputNegIntUint, &result) + if err == nil { + t.Fatal("error should exist") + } + + derr, ok = err.(*Error) + if !ok { + t.Fatalf("error should be kind of Error, instead: %#v", err) + } + + if derr.Errors[0] != "cannot parse 'Vuint', -42 overflows uint" { + t.Errorf("got unexpected error: %s", err) + } + + inputNegFloatUint := map[string]interface{}{ + "vuint": -42.0, + } + + err = Decode(inputNegFloatUint, &result) + if err == nil { + t.Fatal("error should exist") + } + + derr, ok = err.(*Error) + if !ok { + t.Fatalf("error should be kind of Error, instead: %#v", err) + } + + if derr.Errors[0] != "cannot parse 'Vuint', -42.000000 overflows uint" { + t.Errorf("got unexpected error: %s", err) + } } func TestMetadata(t *testing.T) { diff --git a/Godeps/_workspace/src/github.com/mitchellh/reflectwalk/reflectwalk.go b/Godeps/_workspace/src/github.com/mitchellh/reflectwalk/reflectwalk.go index 8c1dd5594..1f2066598 100644 --- a/Godeps/_workspace/src/github.com/mitchellh/reflectwalk/reflectwalk.go +++ b/Godeps/_workspace/src/github.com/mitchellh/reflectwalk/reflectwalk.go @@ -113,17 +113,7 @@ func walk(v reflect.Value, w interface{}) (err error) { switch k { // Primitives - case reflect.Bool: - fallthrough - case reflect.Chan: - fallthrough - case reflect.Func: - fallthrough - case reflect.Int: - fallthrough - case reflect.String: - fallthrough - case reflect.Invalid: + case reflect.Bool, reflect.Chan, reflect.Func, reflect.Int, reflect.String, reflect.Invalid: err = walkPrimitive(originalV, w) return case reflect.Map: diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/conn.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/conn.go index 47d5534a8..eef2572de 100644 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/conn.go +++ b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/conn.go @@ -1,3 +1,4 @@ +// Package zk is a native Go client library for the ZooKeeper orchestration service. package zk /* @@ -14,7 +15,6 @@ import ( "errors" "fmt" "io" - "log" "net" "strconv" "strings" @@ -23,8 +23,17 @@ import ( "time" ) +// ErrNoServer indicates that an operation cannot be completed +// because attempts to connect to all servers in the list failed. var ErrNoServer = errors.New("zk: could not connect to a server") +// ErrInvalidPath indicates that an operation was being attempted on +// an invalid path. (e.g. empty path) +var ErrInvalidPath = errors.New("zk: invalid path") + +// DefaultLogger uses the stdlib log package for logging. +var DefaultLogger = defaultLogger{} + const ( bufferSize = 1536 * 1024 eventChanSize = 6 @@ -47,6 +56,11 @@ type watchPathType struct { type Dialer func(network, address string, timeout time.Duration) (net.Conn, error) +// Logger is an interface that can be implemented to provide custom log output. +type Logger interface { + Printf(string, ...interface{}) +} + type Conn struct { lastZxid int64 sessionID int64 @@ -74,6 +88,8 @@ type Conn struct { // Debug (used by unit tests) reconnectDelay time.Duration + + logger Logger } type request struct { @@ -160,6 +176,7 @@ func ConnectWithDialer(servers []string, sessionTimeout time.Duration, dialer Di watchers: make(map[watchPathType][]chan Event), passwd: emptyPassword, timeout: int32(sessionTimeout.Nanoseconds() / 1e6), + logger: DefaultLogger, // Debug reconnectDelay: 0, @@ -182,10 +199,17 @@ func (c *Conn) Close() { } } +// States returns the current state of the connection. func (c *Conn) State() State { return State(atomic.LoadInt32((*int32)(&c.state))) } +// SetLogger sets the logger to be used for printing errors. +// Logger is an interface provided by this package. +func (c *Conn) SetLogger(l Logger) { + c.logger = l +} + func (c *Conn) setState(state State) { atomic.StoreInt32((*int32)(&c.state), int32(state)) select { @@ -221,7 +245,7 @@ func (c *Conn) connect() error { return nil } - log.Printf("Failed to connect to %s: %+v", c.servers[c.serverIndex], err) + c.logger.Printf("Failed to connect to %s: %+v", c.servers[c.serverIndex], err) } } @@ -267,7 +291,7 @@ func (c *Conn) loop() { // Yeesh if err != io.EOF && err != ErrSessionExpired && !strings.Contains(err.Error(), "use of closed network connection") { - log.Println(err) + c.logger.Printf(err.Error()) } select { @@ -367,7 +391,7 @@ func (c *Conn) sendSetWatches() { res := &setWatchesResponse{} _, err := c.request(opSetWatches, req, res, nil) if err != nil { - log.Printf("Failed to set previous watches: %s", err.Error()) + c.logger.Printf("Failed to set previous watches: %s", err.Error()) } }() } @@ -582,7 +606,7 @@ func (c *Conn) recvLoop(conn net.Conn) error { } else if res.Xid == -2 { // Ping response. Ignore. } else if res.Xid < 0 { - log.Printf("Xid < 0 (%d) but not ping or watcher event", res.Xid) + c.logger.Printf("Xid < 0 (%d) but not ping or watcher event", res.Xid) } else { if res.Zxid > 0 { c.lastZxid = res.Zxid @@ -596,7 +620,7 @@ func (c *Conn) recvLoop(conn net.Conn) error { c.requestsLock.Unlock() if !ok { - log.Printf("Response for unknown request with xid %d", res.Xid) + c.logger.Printf("Response for unknown request with xid %d", res.Xid) } else { if res.Err != 0 { err = res.Err.toError() @@ -694,6 +718,9 @@ func (c *Conn) GetW(path string) ([]byte, *Stat, <-chan Event, error) { } func (c *Conn) Set(path string, data []byte, version int32) (*Stat, error) { + if path == "" { + return nil, ErrInvalidPath + } res := &setDataResponse{} _, err := c.request(opSetData, &SetDataRequest{path, data, version}, res, nil) return &res.Stat, err diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/lock.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/lock.go index fb77e4a53..f13a8b0ba 100644 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/lock.go +++ b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/lock.go @@ -8,10 +8,13 @@ import ( ) var ( - ErrDeadlock = errors.New("zk: trying to acquire a lock twice") + // ErrDeadlock is returned by Lock when trying to lock twice without unlocking first + ErrDeadlock = errors.New("zk: trying to acquire a lock twice") + // ErrNotLocked is returned by Unlock when trying to release a lock that has not first be acquired. ErrNotLocked = errors.New("zk: not locked") ) +// Lock is a mutual exclusion lock. type Lock struct { c *Conn path string @@ -20,6 +23,9 @@ type Lock struct { seq int } +// NewLock creates a new lock instance using the provided connection, path, and acl. +// The path must be a node that is only used by this lock. A lock instances starts +// unlocked until Lock() is called. func NewLock(c *Conn, path string, acl []ACL) *Lock { return &Lock{ c: c, @@ -33,6 +39,9 @@ func parseSeq(path string) (int, error) { return strconv.Atoi(parts[len(parts)-1]) } +// Lock attempts to acquire the lock. It will wait to return until the lock +// is acquired or an error occurs. If this instance already has the lock +// then ErrDeadlock is returned. func (l *Lock) Lock() error { if l.lockPath != "" { return ErrDeadlock @@ -118,6 +127,8 @@ func (l *Lock) Lock() error { return nil } +// Unlock releases an acquired lock. If the lock is not currently acquired by +// this Lock instance than ErrNotLocked is returned. func (l *Lock) Unlock() error { if l.lockPath == "" { return ErrNotLocked diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs.go index 3c9058adb..8fbc069ee 100644 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs.go +++ b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs.go @@ -3,6 +3,7 @@ package zk import ( "encoding/binary" "errors" + "log" "reflect" "runtime" "time" @@ -14,6 +15,12 @@ var ( ErrShortBuffer = errors.New("zk: buffer too small") ) +type defaultLogger struct{} + +func (defaultLogger) Printf(format string, a ...interface{}) { + log.Printf(format, a...) +} + type ACL struct { Perms int32 Scheme string diff --git a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs_test.go b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs_test.go index 64f18e8d3..cafbbd95c 100644 --- a/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs_test.go +++ b/Godeps/_workspace/src/github.com/samuel/go-zookeeper/zk/structs_test.go @@ -58,3 +58,14 @@ func TestDecodeShortBuffer(t *testing.T) { return } } + +func BenchmarkEncode(b *testing.B) { + buf := make([]byte, 4096) + st := &connectRequest{Passwd: []byte("1234567890")} + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if _, err := encodePacket(buf, st); err != nil { + b.Fatal(err) + } + } +} diff --git a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util.go b/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util.go index 0763c9a97..598e3df77 100644 --- a/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util.go +++ b/Godeps/_workspace/src/golang.org/x/crypto/ssh/terminal/util.go @@ -14,7 +14,7 @@ // panic(err) // } // defer terminal.Restore(0, oldState) -package terminal +package terminal // import "golang.org/x/crypto/ssh/terminal" import ( "io" diff --git a/Godeps/_workspace/src/golang.org/x/net/context/context.go b/Godeps/_workspace/src/golang.org/x/net/context/context.go index ef2f3e86f..e7ee376c4 100644 --- a/Godeps/_workspace/src/golang.org/x/net/context/context.go +++ b/Godeps/_workspace/src/golang.org/x/net/context/context.go @@ -34,7 +34,7 @@ // // See http://blog.golang.org/context for example code for a server that uses // Contexts. -package context +package context // import "golang.org/x/net/context" import ( "errors" diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/README.md b/Godeps/_workspace/src/golang.org/x/oauth2/README.md index a5afeca22..0d5141733 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/README.md +++ b/Godeps/_workspace/src/golang.org/x/oauth2/README.md @@ -43,7 +43,7 @@ with the `oauth2` package. "golang.org/x/oauth2" "golang.org/x/oauth2/google" newappengine "google.golang.org/appengine" - newurlftech "google.golang.org/urlfetch" + newurlfetch "google.golang.org/appengine/urlfetch" "appengine" ) diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials.go b/Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials.go index 452fb8c12..baebced2a 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/clientcredentials/clientcredentials.go @@ -11,7 +11,7 @@ // server. // // See http://tools.ietf.org/html/draft-ietf-oauth-v2-31#section-4.4 -package clientcredentials +package clientcredentials // import "golang.org/x/oauth2/clientcredentials" import ( "net/http" diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/facebook/facebook.go b/Godeps/_workspace/src/golang.org/x/oauth2/facebook/facebook.go index 9c816ff80..962e86b0e 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/facebook/facebook.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/facebook/facebook.go @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // Package facebook provides constants for using OAuth2 to access Facebook. -package facebook +package facebook // import "golang.org/x/oauth2/facebook" import ( "golang.org/x/oauth2" diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/github/github.go b/Godeps/_workspace/src/golang.org/x/oauth2/github/github.go index 82ca623dd..1648cb58d 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/github/github.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/github/github.go @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // Package github provides constants for using OAuth2 to access Github. -package github +package github // import "golang.org/x/oauth2/github" import ( "golang.org/x/oauth2" diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/google/google.go b/Godeps/_workspace/src/golang.org/x/oauth2/google/google.go index 2077d9866..74aa7d911 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/google/google.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/google/google.go @@ -12,7 +12,7 @@ // https://developers.google.com/accounts/docs/OAuth2 // and // https://developers.google.com/accounts/docs/application-default-credentials. -package google +package google // import "golang.org/x/oauth2/google" import ( "encoding/json" diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/internal/token.go b/Godeps/_workspace/src/golang.org/x/oauth2/internal/token.go index 727d957ff..ea6716c98 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/internal/token.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/internal/token.go @@ -108,6 +108,7 @@ var brokenAuthHeaderProviders = []string{ "https://www.strava.com/oauth/", "https://app.box.com/", "https://test-sandbox.auth.corp.google.com", + "https://user.gini.net/", } // providerAuthHeaderWorks reports whether the OAuth2 server identified by the tokenURL diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/jws/jws.go b/Godeps/_workspace/src/golang.org/x/oauth2/jws/jws.go index 396b3fac8..362323c4e 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/jws/jws.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/jws/jws.go @@ -4,7 +4,7 @@ // Package jws provides encoding and decoding utilities for // signed JWS messages. -package jws +package jws // import "golang.org/x/oauth2/jws" import ( "bytes" diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/linkedin/linkedin.go b/Godeps/_workspace/src/golang.org/x/oauth2/linkedin/linkedin.go index d93fded6a..de91d5b94 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/linkedin/linkedin.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/linkedin/linkedin.go @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // Package linkedin provides constants for using OAuth2 to access LinkedIn. -package linkedin +package linkedin // import "golang.org/x/oauth2/linkedin" import ( "golang.org/x/oauth2" diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/oauth2.go b/Godeps/_workspace/src/golang.org/x/oauth2/oauth2.go index 031b9d00c..cca8b1803 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/oauth2.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/oauth2.go @@ -5,7 +5,7 @@ // Package oauth2 provides support for making // OAuth2 authorized and authenticated HTTP requests. // It can additionally grant authorization with Bearer JWT. -package oauth2 +package oauth2 // import "golang.org/x/oauth2" import ( "bytes" @@ -253,6 +253,22 @@ func (s *reuseTokenSource) Token() (*Token, error) { 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 diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/odnoklassniki/odnoklassniki.go b/Godeps/_workspace/src/golang.org/x/oauth2/odnoklassniki/odnoklassniki.go index f0b66f97d..2f7a9621e 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/odnoklassniki/odnoklassniki.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/odnoklassniki/odnoklassniki.go @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // Package odnoklassniki provides constants for using OAuth2 to access Odnoklassniki. -package odnoklassniki +package odnoklassniki // import "golang.org/x/oauth2/odnoklassniki" import ( "golang.org/x/oauth2" diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/paypal/paypal.go b/Godeps/_workspace/src/golang.org/x/oauth2/paypal/paypal.go index a99366b6e..baeaa2372 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/paypal/paypal.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/paypal/paypal.go @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // Package paypal provides constants for using OAuth2 to access PayPal. -package paypal +package paypal // import "golang.org/x/oauth2/paypal" import ( "golang.org/x/oauth2" diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/token.go b/Godeps/_workspace/src/golang.org/x/oauth2/token.go index 252cfc7d9..ebbdddbdc 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/token.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/token.go @@ -7,6 +7,7 @@ package oauth2 import ( "net/http" "net/url" + "strings" "time" "golang.org/x/net/context" @@ -53,6 +54,15 @@ type Token struct { // 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 } diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/transport_test.go b/Godeps/_workspace/src/golang.org/x/oauth2/transport_test.go index efb8232ac..35cb25ed5 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/transport_test.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/transport_test.go @@ -32,6 +32,39 @@ func TestTransportTokenSource(t *testing.T) { client.Get(server.URL) } +// Test for case-sensitive token types, per https://github.com/golang/oauth2/issues/113 +func TestTransportTokenSourceTypes(t *testing.T) { + const val = "abc" + tests := []struct { + key string + val string + want string + }{ + {key: "bearer", val: val, want: "Bearer abc"}, + {key: "mac", val: val, want: "MAC abc"}, + {key: "basic", val: val, want: "Basic abc"}, + } + for _, tc := range tests { + ts := &tokenSource{ + token: &Token{ + AccessToken: tc.val, + TokenType: tc.key, + }, + } + tr := &Transport{ + Source: ts, + } + server := newMockServer(func(w http.ResponseWriter, r *http.Request) { + if got, want := r.Header.Get("Authorization"), tc.want; got != want { + t.Errorf("Authorization header (%q) = %q; want %q", val, got, want) + } + }) + defer server.Close() + client := http.Client{Transport: tr} + client.Get(server.URL) + } +} + func TestTokenValidNoAccessToken(t *testing.T) { token := &Token{} if token.Valid() { diff --git a/Godeps/_workspace/src/golang.org/x/oauth2/vk/vk.go b/Godeps/_workspace/src/golang.org/x/oauth2/vk/vk.go index 00e929357..5acdeb18f 100644 --- a/Godeps/_workspace/src/golang.org/x/oauth2/vk/vk.go +++ b/Godeps/_workspace/src/golang.org/x/oauth2/vk/vk.go @@ -3,7 +3,7 @@ // license that can be found in the LICENSE file. // Package vk provides constants for using OAuth2 to access VK.com. -package vk +package vk // import "golang.org/x/oauth2/vk" import ( "golang.org/x/oauth2"