diff options
author | Michael Muré <batolettre@gmail.com> | 2018-09-24 19:22:32 +0200 |
---|---|---|
committer | Michael Muré <batolettre@gmail.com> | 2018-09-24 19:22:32 +0200 |
commit | c4a207622a894ba9839f1a3c47c9d78beff9b861 (patch) | |
tree | 009d80b363b5392e6eba4bec85b0ae74b3942995 /vendor/github.com/shurcooL/graphql | |
parent | c86e7231b223d532e26ab5449715c65b6b4e3fde (diff) | |
download | git-bug-c4a207622a894ba9839f1a3c47c9d78beff9b861.tar.gz |
github: query most of the data
Diffstat (limited to 'vendor/github.com/shurcooL/graphql')
-rw-r--r-- | vendor/github.com/shurcooL/graphql/.travis.yml | 16 | ||||
-rw-r--r-- | vendor/github.com/shurcooL/graphql/LICENSE | 21 | ||||
-rw-r--r-- | vendor/github.com/shurcooL/graphql/README.md | 293 | ||||
-rw-r--r-- | vendor/github.com/shurcooL/graphql/doc.go | 11 | ||||
-rw-r--r-- | vendor/github.com/shurcooL/graphql/graphql.go | 119 | ||||
-rw-r--r-- | vendor/github.com/shurcooL/graphql/ident/ident.go | 240 | ||||
-rw-r--r-- | vendor/github.com/shurcooL/graphql/internal/jsonutil/graphql.go | 308 | ||||
-rw-r--r-- | vendor/github.com/shurcooL/graphql/query.go | 131 | ||||
-rw-r--r-- | vendor/github.com/shurcooL/graphql/scalar.go | 51 |
9 files changed, 1190 insertions, 0 deletions
diff --git a/vendor/github.com/shurcooL/graphql/.travis.yml b/vendor/github.com/shurcooL/graphql/.travis.yml new file mode 100644 index 00000000..93b1fcdb --- /dev/null +++ b/vendor/github.com/shurcooL/graphql/.travis.yml @@ -0,0 +1,16 @@ +sudo: false +language: go +go: + - 1.x + - master +matrix: + allow_failures: + - go: master + fast_finish: true +install: + - # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step). +script: + - go get -t -v ./... + - diff -u <(echo -n) <(gofmt -d -s .) + - go tool vet . + - go test -v -race ./... diff --git a/vendor/github.com/shurcooL/graphql/LICENSE b/vendor/github.com/shurcooL/graphql/LICENSE new file mode 100644 index 00000000..ca4c7764 --- /dev/null +++ b/vendor/github.com/shurcooL/graphql/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Dmitri Shuralyov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/shurcooL/graphql/README.md b/vendor/github.com/shurcooL/graphql/README.md new file mode 100644 index 00000000..6fa03bd4 --- /dev/null +++ b/vendor/github.com/shurcooL/graphql/README.md @@ -0,0 +1,293 @@ +graphql +======= + +[![Build Status](https://travis-ci.org/shurcooL/graphql.svg?branch=master)](https://travis-ci.org/shurcooL/graphql) [![GoDoc](https://godoc.org/github.com/shurcooL/graphql?status.svg)](https://godoc.org/github.com/shurcooL/graphql) + +Package `graphql` provides a GraphQL client implementation. + +For more information, see package [`github.com/shurcooL/githubv4`](https://github.com/shurcooL/githubv4), which is a specialized version targeting GitHub GraphQL API v4. That package is driving the feature development. + +**Status:** In active early research and development. The API will change when opportunities for improvement are discovered; it is not yet frozen. + +Installation +------------ + +`graphql` requires Go version 1.8 or later. + +```bash +go get -u github.com/shurcooL/graphql +``` + +Usage +----- + +Construct a GraphQL client, specifying the GraphQL server URL. Then, you can use it to make GraphQL queries and mutations. + +```Go +client := graphql.NewClient("https://example.com/graphql", nil) +// Use client... +``` + +### Authentication + +Some GraphQL servers may require authentication. The `graphql` package does not directly handle authentication. Instead, when creating a new client, you're expected to pass an `http.Client` that performs authentication. The easiest and recommended way to do this is to use the [`golang.org/x/oauth2`](https://golang.org/x/oauth2) package. You'll need an OAuth token with the right scopes. Then: + +```Go +import "golang.org/x/oauth2" + +func main() { + src := oauth2.StaticTokenSource( + &oauth2.Token{AccessToken: os.Getenv("GRAPHQL_TOKEN")}, + ) + httpClient := oauth2.NewClient(context.Background(), src) + + client := graphql.NewClient("https://example.com/graphql", httpClient) + // Use client... +``` + +### Simple Query + +To make a GraphQL query, you need to define a corresponding Go type. + +For example, to make the following GraphQL query: + +```GraphQL +query { + me { + name + } +} +``` + +You can define this variable: + +```Go +var query struct { + Me struct { + Name graphql.String + } +} +``` + +Then call `client.Query`, passing a pointer to it: + +```Go +err := client.Query(context.Background(), &query, nil) +if err != nil { + // Handle error. +} +fmt.Println(query.Me.Name) + +// Output: Luke Skywalker +``` + +### Arguments and Variables + +Often, you'll want to specify arguments on some fields. You can use the `graphql` struct field tag for this. + +For example, to make the following GraphQL query: + +```GraphQL +{ + human(id: "1000") { + name + height(unit: METER) + } +} +``` + +You can define this variable: + +```Go +var q struct { + Human struct { + Name graphql.String + Height graphql.Float `graphql:"height(unit: METER)"` + } `graphql:"human(id: \"1000\")"` +} +``` + +Then call `client.Query`: + +```Go +err := client.Query(context.Background(), &q, nil) +if err != nil { + // Handle error. +} +fmt.Println(q.Human.Name) +fmt.Println(q.Human.Height) + +// Output: +// Luke Skywalker +// 1.72 +``` + +However, that'll only work if the arguments are constant and known in advance. Otherwise, you will need to make use of variables. Replace the constants in the struct field tag with variable names: + +```Go +var q struct { + Human struct { + Name graphql.String + Height graphql.Float `graphql:"height(unit: $unit)"` + } `graphql:"human(id: $id)"` +} +``` + +Then, define a `variables` map with their values: + +```Go +variables := map[string]interface{}{ + "id": graphql.ID(id), + "unit": starwars.LengthUnit("METER"), +} +``` + +Finally, call `client.Query` providing `variables`: + +```Go +err := client.Query(context.Background(), &q, variables) +if err != nil { + // Handle error. +} +``` + +### Inline Fragments + +Some GraphQL queries contain inline fragments. You can use the `graphql` struct field tag to express them. + +For example, to make the following GraphQL query: + +```GraphQL +{ + hero(episode: "JEDI") { + name + ... on Droid { + primaryFunction + } + ... on Human { + height + } + } +} +``` + +You can define this variable: + +```Go +var q struct { + Hero struct { + Name graphql.String + Droid struct { + PrimaryFunction graphql.String + } `graphql:"... on Droid"` + Human struct { + Height graphql.Float + } `graphql:"... on Human"` + } `graphql:"hero(episode: \"JEDI\")"` +} +``` + +Alternatively, you can define the struct types corresponding to inline fragments, and use them as embedded fields in your query: + +```Go +type ( + DroidFragment struct { + PrimaryFunction graphql.String + } + HumanFragment struct { + Height graphql.Float + } +) + +var q struct { + Hero struct { + Name graphql.String + DroidFragment `graphql:"... on Droid"` + HumanFragment `graphql:"... on Human"` + } `graphql:"hero(episode: \"JEDI\")"` +} +``` + +Then call `client.Query`: + +```Go +err := client.Query(context.Background(), &q, nil) +if err != nil { + // Handle error. +} +fmt.Println(q.Hero.Name) +fmt.Println(q.Hero.PrimaryFunction) +fmt.Println(q.Hero.Height) + +// Output: +// R2-D2 +// Astromech +// 0 +``` + +### Mutations + +Mutations often require information that you can only find out by performing a query first. Let's suppose you've already done that. + +For example, to make the following GraphQL mutation: + +```GraphQL +mutation($ep: Episode!, $review: ReviewInput!) { + createReview(episode: $ep, review: $review) { + stars + commentary + } +} +variables { + "ep": "JEDI", + "review": { + "stars": 5, + "commentary": "This is a great movie!" + } +} +``` + +You can define: + +```Go +var m struct { + CreateReview struct { + Stars graphql.Int + Commentary graphql.String + } `graphql:"createReview(episode: $ep, review: $review)"` +} +variables := map[string]interface{}{ + "ep": starwars.Episode("JEDI"), + "review": starwars.ReviewInput{ + Stars: graphql.Int(5), + Commentary: graphql.String("This is a great movie!"), + }, +} +``` + +Then call `client.Mutate`: + +```Go +err := client.Mutate(context.Background(), &m, variables) +if err != nil { + // Handle error. +} +fmt.Printf("Created a %v star review: %v\n", m.CreateReview.Stars, m.CreateReview.Commentary) + +// Output: +// Created a 5 star review: This is a great movie! +``` + +Directories +----------- + +| Path | Synopsis | +|----------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------| +| [example/graphqldev](https://godoc.org/github.com/shurcooL/graphql/example/graphqldev) | graphqldev is a test program currently being used for developing graphql package. | +| [ident](https://godoc.org/github.com/shurcooL/graphql/ident) | Package ident provides functions for parsing and converting identifier names between various naming convention. | +| [internal/jsonutil](https://godoc.org/github.com/shurcooL/graphql/internal/jsonutil) | Package jsonutil provides a function for decoding JSON into a GraphQL query data structure. | + +License +------- + +- [MIT License](LICENSE) diff --git a/vendor/github.com/shurcooL/graphql/doc.go b/vendor/github.com/shurcooL/graphql/doc.go new file mode 100644 index 00000000..69ec4e03 --- /dev/null +++ b/vendor/github.com/shurcooL/graphql/doc.go @@ -0,0 +1,11 @@ +// Package graphql provides a GraphQL client implementation. +// +// For more information, see package github.com/shurcooL/githubv4, +// which is a specialized version targeting GitHub GraphQL API v4. +// That package is driving the feature development. +// +// Status: In active early research and development. The API will change when +// opportunities for improvement are discovered; it is not yet frozen. +// +// For now, see README for more details. +package graphql // import "github.com/shurcooL/graphql" diff --git a/vendor/github.com/shurcooL/graphql/graphql.go b/vendor/github.com/shurcooL/graphql/graphql.go new file mode 100644 index 00000000..f2c5b54f --- /dev/null +++ b/vendor/github.com/shurcooL/graphql/graphql.go @@ -0,0 +1,119 @@ +package graphql + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "net/http" + + "github.com/shurcooL/go/ctxhttp" + "github.com/shurcooL/graphql/internal/jsonutil" +) + +// Client is a GraphQL client. +type Client struct { + url string // GraphQL server URL. + httpClient *http.Client +} + +// NewClient creates a GraphQL client targeting the specified GraphQL server URL. +// If httpClient is nil, then http.DefaultClient is used. +func NewClient(url string, httpClient *http.Client) *Client { + if httpClient == nil { + httpClient = http.DefaultClient + } + return &Client{ + url: url, + httpClient: httpClient, + } +} + +// Query executes a single GraphQL query request, +// with a query derived from q, populating the response into it. +// q should be a pointer to struct that corresponds to the GraphQL schema. +func (c *Client) Query(ctx context.Context, q interface{}, variables map[string]interface{}) error { + return c.do(ctx, queryOperation, q, variables) +} + +// Mutate executes a single GraphQL mutation request, +// with a mutation derived from m, populating the response into it. +// m should be a pointer to struct that corresponds to the GraphQL schema. +func (c *Client) Mutate(ctx context.Context, m interface{}, variables map[string]interface{}) error { + return c.do(ctx, mutationOperation, m, variables) +} + +// do executes a single GraphQL operation. +func (c *Client) do(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}) error { + var query string + switch op { + case queryOperation: + query = constructQuery(v, variables) + case mutationOperation: + query = constructMutation(v, variables) + } + in := struct { + Query string `json:"query"` + Variables map[string]interface{} `json:"variables,omitempty"` + }{ + Query: query, + Variables: variables, + } + var buf bytes.Buffer + err := json.NewEncoder(&buf).Encode(in) + if err != nil { + return err + } + resp, err := ctxhttp.Post(ctx, c.httpClient, c.url, "application/json", &buf) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("unexpected status: %v", resp.Status) + } + var out struct { + Data *json.RawMessage + Errors errors + //Extensions interface{} // Unused. + } + err = json.NewDecoder(resp.Body).Decode(&out) + if err != nil { + return err + } + if out.Data != nil { + err := jsonutil.UnmarshalGraphQL(*out.Data, v) + if err != nil { + return err + } + } + if len(out.Errors) > 0 { + return out.Errors + } + return nil +} + +// errors represents the "errors" array in a response from a GraphQL server. +// If returned via error interface, the slice is expected to contain at least 1 element. +// +// Specification: https://facebook.github.io/graphql/#sec-Errors. +type errors []struct { + Message string + Locations []struct { + Line int + Column int + } +} + +// Error implements error interface. +func (e errors) Error() string { + return e[0].Message +} + +type operationType uint8 + +const ( + queryOperation operationType = iota + mutationOperation + //subscriptionOperation // Unused. +) diff --git a/vendor/github.com/shurcooL/graphql/ident/ident.go b/vendor/github.com/shurcooL/graphql/ident/ident.go new file mode 100644 index 00000000..29e498ed --- /dev/null +++ b/vendor/github.com/shurcooL/graphql/ident/ident.go @@ -0,0 +1,240 @@ +// Package ident provides functions for parsing and converting identifier names +// between various naming convention. It has support for MixedCaps, lowerCamelCase, +// and SCREAMING_SNAKE_CASE naming conventions. +package ident + +import ( + "strings" + "unicode" + "unicode/utf8" +) + +// ParseMixedCaps parses a MixedCaps identifier name. +// +// E.g., "ClientMutationID" -> {"Client", "Mutation", "ID"}. +func ParseMixedCaps(name string) Name { + var words Name + + // Split name at any lower -> Upper or Upper -> Upper,lower transitions. + // Check each word for initialisms. + runes := []rune(name) + w, i := 0, 0 // Index of start of word, scan. + for i+1 <= len(runes) { + eow := false // Whether we hit the end of a word. + if i+1 == len(runes) { + eow = true + } else if unicode.IsLower(runes[i]) && unicode.IsUpper(runes[i+1]) { + // lower -> Upper. + eow = true + } else if i+2 < len(runes) && unicode.IsUpper(runes[i]) && unicode.IsUpper(runes[i+1]) && unicode.IsLower(runes[i+2]) { + // Upper -> Upper,lower. End of acronym, followed by a word. + eow = true + + if string(runes[i:i+3]) == "IDs" { // Special case, plural form of ID initialism. + eow = false + } + } + i++ + if !eow { + continue + } + + // [w, i) is a word. + word := string(runes[w:i]) + if initialism, ok := isInitialism(word); ok { + words = append(words, initialism) + } else if i1, i2, ok := isTwoInitialisms(word); ok { + words = append(words, i1, i2) + } else { + words = append(words, word) + } + w = i + } + return words +} + +// ParseLowerCamelCase parses a lowerCamelCase identifier name. +// +// E.g., "clientMutationId" -> {"client", "Mutation", "Id"}. +func ParseLowerCamelCase(name string) Name { + var words Name + + // Split name at any Upper letters. + runes := []rune(name) + w, i := 0, 0 // Index of start of word, scan. + for i+1 <= len(runes) { + eow := false // Whether we hit the end of a word. + if i+1 == len(runes) { + eow = true + } else if unicode.IsUpper(runes[i+1]) { + // Upper letter. + eow = true + } + i++ + if !eow { + continue + } + + // [w, i) is a word. + words = append(words, string(runes[w:i])) + w = i + } + return words +} + +// ParseScreamingSnakeCase parses a SCREAMING_SNAKE_CASE identifier name. +// +// E.g., "CLIENT_MUTATION_ID" -> {"CLIENT", "MUTATION", "ID"}. +func ParseScreamingSnakeCase(name string) Name { + var words Name + + // Split name at '_' characters. + runes := []rune(name) + w, i := 0, 0 // Index of start of word, scan. + for i+1 <= len(runes) { + eow := false // Whether we hit the end of a word. + if i+1 == len(runes) { + eow = true + } else if runes[i+1] == '_' { + // Underscore. + eow = true + } + i++ + if !eow { + continue + } + + // [w, i) is a word. + words = append(words, string(runes[w:i])) + if i < len(runes) && runes[i] == '_' { + // Skip underscore. + i++ + } + w = i + } + return words +} + +// Name is an identifier name, broken up into individual words. +type Name []string + +// ToMixedCaps expresses identifer name in MixedCaps naming convention. +// +// E.g., "ClientMutationID". +func (n Name) ToMixedCaps() string { + for i, word := range n { + if strings.EqualFold(word, "IDs") { // Special case, plural form of ID initialism. + n[i] = "IDs" + continue + } + if initialism, ok := isInitialism(word); ok { + n[i] = initialism + continue + } + if brand, ok := isBrand(word); ok { + n[i] = brand + continue + } + r, size := utf8.DecodeRuneInString(word) + n[i] = string(unicode.ToUpper(r)) + strings.ToLower(word[size:]) + } + return strings.Join(n, "") +} + +// ToLowerCamelCase expresses identifer name in lowerCamelCase naming convention. +// +// E.g., "clientMutationId". +func (n Name) ToLowerCamelCase() string { + for i, word := range n { + if i == 0 { + n[i] = strings.ToLower(word) + continue + } + r, size := utf8.DecodeRuneInString(word) + n[i] = string(unicode.ToUpper(r)) + strings.ToLower(word[size:]) + } + return strings.Join(n, "") +} + +// isInitialism reports whether word is an initialism. +func isInitialism(word string) (string, bool) { + initialism := strings.ToUpper(word) + _, ok := initialisms[initialism] + return initialism, ok +} + +// isTwoInitialisms reports whether word is two initialisms. +func isTwoInitialisms(word string) (string, string, bool) { + word = strings.ToUpper(word) + for i := 2; i <= len(word)-2; i++ { // Shortest initialism is 2 characters long. + _, ok1 := initialisms[word[:i]] + _, ok2 := initialisms[word[i:]] + if ok1 && ok2 { + return word[:i], word[i:], true + } + } + return "", "", false +} + +// initialisms is the set of initialisms in the MixedCaps naming convention. +// Only add entries that are highly unlikely to be non-initialisms. +// For instance, "ID" is fine (Freudian code is rare), but "AND" is not. +var initialisms = map[string]struct{}{ + // These are the common initialisms from golint. Keep them in sync + // with https://gotools.org/github.com/golang/lint#commonInitialisms. + "ACL": {}, + "API": {}, + "ASCII": {}, + "CPU": {}, + "CSS": {}, + "DNS": {}, + "EOF": {}, + "GUID": {}, + "HTML": {}, + "HTTP": {}, + "HTTPS": {}, + "ID": {}, + "IP": {}, + "JSON": {}, + "LHS": {}, + "QPS": {}, + "RAM": {}, + "RHS": {}, + "RPC": {}, + "SLA": {}, + "SMTP": {}, + "SQL": {}, + "SSH": {}, + "TCP": {}, + "TLS": {}, + "TTL": {}, + "UDP": {}, + "UI": {}, + "UID": {}, + "UUID": {}, + "URI": {}, + "URL": {}, + "UTF8": {}, + "VM": {}, + "XML": {}, + "XMPP": {}, + "XSRF": {}, + "XSS": {}, + + // Additional common initialisms. + "RSS": {}, +} + +// isBrand reports whether word is a brand. +func isBrand(word string) (string, bool) { + brand, ok := brands[strings.ToLower(word)] + return brand, ok +} + +// brands is the map of brands in the MixedCaps naming convention; +// see https://dmitri.shuralyov.com/idiomatic-go#for-brands-or-words-with-more-than-1-capital-letter-lowercase-all-letters. +// Key is the lower case version of the brand, value is the canonical brand spelling. +// Only add entries that are highly unlikely to be non-brands. +var brands = map[string]string{ + "github": "GitHub", +} diff --git a/vendor/github.com/shurcooL/graphql/internal/jsonutil/graphql.go b/vendor/github.com/shurcooL/graphql/internal/jsonutil/graphql.go new file mode 100644 index 00000000..9e75791d --- /dev/null +++ b/vendor/github.com/shurcooL/graphql/internal/jsonutil/graphql.go @@ -0,0 +1,308 @@ +// Package jsonutil provides a function for decoding JSON +// into a GraphQL query data structure. +package jsonutil + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "reflect" + "strings" +) + +// UnmarshalGraphQL parses the JSON-encoded GraphQL response data and stores +// the result in the GraphQL query data structure pointed to by v. +// +// The implementation is created on top of the JSON tokenizer available +// in "encoding/json".Decoder. +func UnmarshalGraphQL(data []byte, v interface{}) error { + dec := json.NewDecoder(bytes.NewReader(data)) + dec.UseNumber() + err := (&decoder{tokenizer: dec}).Decode(v) + if err != nil { + return err + } + tok, err := dec.Token() + switch err { + case io.EOF: + // Expect to get io.EOF. There shouldn't be any more + // tokens left after we've decoded v successfully. + return nil + case nil: + return fmt.Errorf("invalid token '%v' after top-level value", tok) + default: + return err + } +} + +// decoder is a JSON decoder that performs custom unmarshaling behavior +// for GraphQL query data structures. It's implemented on top of a JSON tokenizer. +type decoder struct { + tokenizer interface { + Token() (json.Token, error) + } + + // Stack of what part of input JSON we're in the middle of - objects, arrays. + parseState []json.Delim + + // Stacks of values where to unmarshal. + // The top of each stack is the reflect.Value where to unmarshal next JSON value. + // + // The reason there's more than one stack is because we might be unmarshaling + // a single JSON value into multiple GraphQL fragments or embedded structs, so + // we keep track of them all. + vs [][]reflect.Value +} + +// Decode decodes a single JSON value from d.tokenizer into v. +func (d *decoder) Decode(v interface{}) error { + rv := reflect.ValueOf(v) + if rv.Kind() != reflect.Ptr { + return fmt.Errorf("cannot decode into non-pointer %T", v) + } + d.vs = [][]reflect.Value{{rv.Elem()}} + return d.decode() +} + +// decode decodes a single JSON value from d.tokenizer into d.vs. +func (d *decoder) decode() error { + // The loop invariant is that the top of each d.vs stack + // is where we try to unmarshal the next JSON value we see. + for len(d.vs) > 0 { + tok, err := d.tokenizer.Token() + if err == io.EOF { + return errors.New("unexpected end of JSON input") + } else if err != nil { + return err + } + + switch { + + // Are we inside an object and seeing next key (rather than end of object)? + case d.state() == '{' && tok != json.Delim('}'): + key, ok := tok.(string) + if !ok { + return errors.New("unexpected non-key in JSON input") + } + someFieldExist := false + for i := range d.vs { + v := d.vs[i][len(d.vs[i])-1] + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + var f reflect.Value + if v.Kind() == reflect.Struct { + f = fieldByGraphQLName(v, key) + if f.IsValid() { + someFieldExist = true + } + } + d.vs[i] = append(d.vs[i], f) + } + if !someFieldExist { + return fmt.Errorf("struct field for %s doesn't exist in any of %v places to unmarshal", key, len(d.vs)) + } + + // We've just consumed the current token, which was the key. + // Read the next token, which should be the value, and let the rest of code process it. + tok, err = d.tokenizer.Token() + if err == io.EOF { + return errors.New("unexpected end of JSON input") + } else if err != nil { + return err + } + + // Are we inside an array and seeing next value (rather than end of array)? + case d.state() == '[' && tok != json.Delim(']'): + someSliceExist := false + for i := range d.vs { + v := d.vs[i][len(d.vs[i])-1] + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + var f reflect.Value + if v.Kind() == reflect.Slice { + v.Set(reflect.Append(v, reflect.Zero(v.Type().Elem()))) // v = append(v, T). + f = v.Index(v.Len() - 1) + someSliceExist = true + } + d.vs[i] = append(d.vs[i], f) + } + if !someSliceExist { + return fmt.Errorf("slice doesn't exist in any of %v places to unmarshal", len(d.vs)) + } + } + + switch tok := tok.(type) { + case string, json.Number, bool, nil: + // Value. + + for i := range d.vs { + v := d.vs[i][len(d.vs[i])-1] + if !v.IsValid() { + continue + } + err := unmarshalValue(tok, v) + if err != nil { + return err + } + } + d.popAllVs() + + case json.Delim: + switch tok { + case '{': + // Start of object. + + d.pushState(tok) + + frontier := make([]reflect.Value, len(d.vs)) // Places to look for GraphQL fragments/embedded structs. + for i := range d.vs { + v := d.vs[i][len(d.vs[i])-1] + frontier[i] = v + // TODO: Do this recursively or not? Add a test case if needed. + if v.Kind() == reflect.Ptr && v.IsNil() { + v.Set(reflect.New(v.Type().Elem())) // v = new(T). + } + } + // Find GraphQL fragments/embedded structs recursively, adding to frontier + // as new ones are discovered and exploring them further. + for len(frontier) > 0 { + v := frontier[0] + frontier = frontier[1:] + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + if v.Kind() != reflect.Struct { + continue + } + for i := 0; i < v.NumField(); i++ { + if isGraphQLFragment(v.Type().Field(i)) || v.Type().Field(i).Anonymous { + // Add GraphQL fragment or embedded struct. + d.vs = append(d.vs, []reflect.Value{v.Field(i)}) + frontier = append(frontier, v.Field(i)) + } + } + } + case '[': + // Start of array. + + d.pushState(tok) + + for i := range d.vs { + v := d.vs[i][len(d.vs[i])-1] + // TODO: Confirm this is needed, write a test case. + //if v.Kind() == reflect.Ptr && v.IsNil() { + // v.Set(reflect.New(v.Type().Elem())) // v = new(T). + //} + + // Reset slice to empty (in case it had non-zero initial value). + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + if v.Kind() != reflect.Slice { + continue + } + v.Set(reflect.MakeSlice(v.Type(), 0, 0)) // v = make(T, 0, 0). + } + case '}', ']': + // End of object or array. + d.popAllVs() + d.popState() + default: + return errors.New("unexpected delimiter in JSON input") + } + default: + return errors.New("unexpected token in JSON input") + } + } + return nil +} + +// pushState pushes a new parse state s onto the stack. +func (d *decoder) pushState(s json.Delim) { + d.parseState = append(d.parseState, s) +} + +// popState pops a parse state (already obtained) off the stack. +// The stack must be non-empty. +func (d *decoder) popState() { + d.parseState = d.parseState[:len(d.parseState)-1] +} + +// state reports the parse state on top of stack, or 0 if empty. +func (d *decoder) state() json.Delim { + if len(d.parseState) == 0 { + return 0 + } + return d.parseState[len(d.parseState)-1] +} + +// popAllVs pops from all d.vs stacks, keeping only non-empty ones. +func (d *decoder) popAllVs() { + var nonEmpty [][]reflect.Value + for i := range d.vs { + d.vs[i] = d.vs[i][:len(d.vs[i])-1] + if len(d.vs[i]) > 0 { + nonEmpty = append(nonEmpty, d.vs[i]) + } + } + d.vs = nonEmpty +} + +// fieldByGraphQLName returns a struct field of struct v that matches GraphQL name, +// or invalid reflect.Value if none found. +func fieldByGraphQLName(v reflect.Value, name string) reflect.Value { + for i := 0; i < v.NumField(); i++ { + if hasGraphQLName(v.Type().Field(i), name) { + return v.Field(i) + } + } + return reflect.Value{} +} + +// hasGraphQLName reports whether struct field f has GraphQL name. +func hasGraphQLName(f reflect.StructField, name string) bool { + value, ok := f.Tag.Lookup("graphql") + if !ok { + // TODO: caseconv package is relatively slow. Optimize it, then consider using it here. + //return caseconv.MixedCapsToLowerCamelCase(f.Name) == name + return strings.EqualFold(f.Name, name) + } + value = strings.TrimSpace(value) // TODO: Parse better. + if strings.HasPrefix(value, "...") { + // GraphQL fragment. It doesn't have a name. + return false + } + if i := strings.Index(value, "("); i != -1 { + value = value[:i] + } + if i := strings.Index(value, ":"); i != -1 { + value = value[:i] + } + return strings.TrimSpace(value) == name +} + +// isGraphQLFragment reports whether struct field f is a GraphQL fragment. +func isGraphQLFragment(f reflect.StructField) bool { + value, ok := f.Tag.Lookup("graphql") + if !ok { + return false + } + value = strings.TrimSpace(value) // TODO: Parse better. + return strings.HasPrefix(value, "...") +} + +// unmarshalValue unmarshals JSON value into v. +func unmarshalValue(value json.Token, v reflect.Value) error { + b, err := json.Marshal(value) // TODO: Short-circuit (if profiling says it's worth it). + if err != nil { + return err + } + if !v.CanAddr() { + return fmt.Errorf("value %v is not addressable", v) + } + return json.Unmarshal(b, v.Addr().Interface()) +} diff --git a/vendor/github.com/shurcooL/graphql/query.go b/vendor/github.com/shurcooL/graphql/query.go new file mode 100644 index 00000000..e10b7718 --- /dev/null +++ b/vendor/github.com/shurcooL/graphql/query.go @@ -0,0 +1,131 @@ +package graphql + +import ( + "bytes" + "encoding/json" + "io" + "reflect" + "sort" + + "github.com/shurcooL/graphql/ident" +) + +func constructQuery(v interface{}, variables map[string]interface{}) string { + query := query(v) + if len(variables) > 0 { + return "query(" + queryArguments(variables) + ")" + query + } + return query +} + +func constructMutation(v interface{}, variables map[string]interface{}) string { + query := query(v) + if len(variables) > 0 { + return "mutation(" + queryArguments(variables) + ")" + query + } + return "mutation" + query +} + +// queryArguments constructs a minified arguments string for variables. +// +// E.g., map[string]interface{}{"a": Int(123), "b": NewBoolean(true)} -> "$a:Int!$b:Boolean". +func queryArguments(variables map[string]interface{}) string { + // Sort keys in order to produce deterministic output for testing purposes. + // TODO: If tests can be made to work with non-deterministic output, then no need to sort. + keys := make([]string, 0, len(variables)) + for k := range variables { + keys = append(keys, k) + } + sort.Strings(keys) + + var buf bytes.Buffer + for _, k := range keys { + io.WriteString(&buf, "$") + io.WriteString(&buf, k) + io.WriteString(&buf, ":") + writeArgumentType(&buf, reflect.TypeOf(variables[k]), true) + // Don't insert a comma here. + // Commas in GraphQL are insignificant, and we want minified output. + // See https://facebook.github.io/graphql/October2016/#sec-Insignificant-Commas. + } + return buf.String() +} + +// writeArgumentType writes a minified GraphQL type for t to w. +// value indicates whether t is a value (required) type or pointer (optional) type. +// If value is true, then "!" is written at the end of t. +func writeArgumentType(w io.Writer, t reflect.Type, value bool) { + if t.Kind() == reflect.Ptr { + // Pointer is an optional type, so no "!" at the end of the pointer's underlying type. + writeArgumentType(w, t.Elem(), false) + return + } + + switch t.Kind() { + case reflect.Slice, reflect.Array: + // List. E.g., "[Int]". + io.WriteString(w, "[") + writeArgumentType(w, t.Elem(), true) + io.WriteString(w, "]") + default: + // Named type. E.g., "Int". + name := t.Name() + if name == "string" { // HACK: Workaround for https://github.com/shurcooL/githubv4/issues/12. + name = "ID" + } + io.WriteString(w, name) + } + + if value { + // Value is a required type, so add "!" to the end. + io.WriteString(w, "!") + } +} + +// query uses writeQuery to recursively construct +// a minified query string from the provided struct v. +// +// E.g., struct{Foo Int, BarBaz *Boolean} -> "{foo,barBaz}". +func query(v interface{}) string { + var buf bytes.Buffer + writeQuery(&buf, reflect.TypeOf(v), false) + return buf.String() +} + +// writeQuery writes a minified query for t to w. +// If inline is true, the struct fields of t are inlined into parent struct. +func writeQuery(w io.Writer, t reflect.Type, inline bool) { + switch t.Kind() { + case reflect.Ptr, reflect.Slice: + writeQuery(w, t.Elem(), false) + case reflect.Struct: + // If the type implements json.Unmarshaler, it's a scalar. Don't expand it. + if reflect.PtrTo(t).Implements(jsonUnmarshaler) { + return + } + if !inline { + io.WriteString(w, "{") + } + for i := 0; i < t.NumField(); i++ { + if i != 0 { + io.WriteString(w, ",") + } + f := t.Field(i) + value, ok := f.Tag.Lookup("graphql") + inlineField := f.Anonymous && !ok + if !inlineField { + if ok { + io.WriteString(w, value) + } else { + io.WriteString(w, ident.ParseMixedCaps(f.Name).ToLowerCamelCase()) + } + } + writeQuery(w, f.Type, inlineField) + } + if !inline { + io.WriteString(w, "}") + } + } +} + +var jsonUnmarshaler = reflect.TypeOf((*json.Unmarshaler)(nil)).Elem() diff --git a/vendor/github.com/shurcooL/graphql/scalar.go b/vendor/github.com/shurcooL/graphql/scalar.go new file mode 100644 index 00000000..0f7ceea5 --- /dev/null +++ b/vendor/github.com/shurcooL/graphql/scalar.go @@ -0,0 +1,51 @@ +package graphql + +// Note: These custom types are meant to be used in queries for now. +// But the plan is to switch to using native Go types (string, int, bool, time.Time, etc.). +// See https://github.com/shurcooL/githubv4/issues/9 for details. +// +// These custom types currently provide documentation, and their use +// is required for sending outbound queries. However, native Go types +// can be used for unmarshaling. Once https://github.com/shurcooL/githubv4/issues/9 +// is resolved, native Go types can completely replace these. + +type ( + // Boolean represents true or false values. + Boolean bool + + // Float represents signed double-precision fractional values as + // specified by IEEE 754. + Float float64 + + // ID represents a unique identifier that is Base64 obfuscated. It + // is often used to refetch an object or as key for a cache. The ID + // type appears in a JSON response as a String; however, it is not + // intended to be human-readable. When expected as an input type, + // any string (such as "VXNlci0xMA==") or integer (such as 4) input + // value will be accepted as an ID. + ID interface{} + + // Int represents non-fractional signed whole numeric values. + // Int can represent values between -(2^31) and 2^31 - 1. + Int int32 + + // String represents textual data as UTF-8 character sequences. + // This type is most often used by GraphQL to represent free-form + // human-readable text. + String string +) + +// NewBoolean is a helper to make a new *Boolean. +func NewBoolean(v Boolean) *Boolean { return &v } + +// NewFloat is a helper to make a new *Float. +func NewFloat(v Float) *Float { return &v } + +// NewID is a helper to make a new *ID. +func NewID(v ID) *ID { return &v } + +// NewInt is a helper to make a new *Int. +func NewInt(v Int) *Int { return &v } + +// NewString is a helper to make a new *String. +func NewString(v String) *String { return &v } |