...
1 package api
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "io"
8 "strings"
9
10 "github.com/cli/go-gh/v2/pkg/jsonpretty"
11 )
12
13 type graphqlBody struct {
14 Query string `json:"query"`
15 OperationName string `json:"operationName"`
16 Variables json.RawMessage `json:"variables"`
17 }
18
19
20 type jsonFormatter struct {
21 colorize bool
22 }
23
24 func (f *jsonFormatter) Format(w io.Writer, src []byte) error {
25 var graphqlQuery graphqlBody
26
27 if err := json.Unmarshal(src, &graphqlQuery); err == nil && graphqlQuery.Query != "" && len(graphqlQuery.Variables) > 0 {
28 colorHighlight := "\x1b[35;1m"
29 colorReset := "\x1b[m"
30 if !f.colorize {
31 colorHighlight = ""
32 colorReset = ""
33 }
34 if _, err := fmt.Fprintf(w, "%sGraphQL query:%s\n%s\n", colorHighlight, colorReset, strings.ReplaceAll(strings.TrimSpace(graphqlQuery.Query), "\t", " ")); err != nil {
35 return err
36 }
37 if _, err := fmt.Fprintf(w, "%sGraphQL variables:%s %s\n", colorHighlight, colorReset, string(graphqlQuery.Variables)); err != nil {
38 return err
39 }
40 return nil
41 }
42 return jsonpretty.Format(w, bytes.NewReader(src), " ", f.colorize)
43 }
44
45 func (f *jsonFormatter) Match(t string) bool {
46 return jsonTypeRE.MatchString(t)
47 }
48
View as plain text