File: log_formatter.go

package info (click to toggle)
golang-github-cli-go-gh 1.2.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 444 kB
  • sloc: makefile: 2
file content (47 lines) | stat: -rw-r--r-- 1,372 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package api

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"strings"

	"github.com/cli/go-gh/pkg/jsonpretty"
)

type graphqlBody struct {
	Query         string          `json:"query"`
	OperationName string          `json:"operationName"`
	Variables     json.RawMessage `json:"variables"`
}

// jsonFormatter is a httpretty.Formatter that prettifies JSON payloads and GraphQL queries.
type jsonFormatter struct {
	colorize bool
}

func (f *jsonFormatter) Format(w io.Writer, src []byte) error {
	var graphqlQuery graphqlBody
	// TODO: find more precise way to detect a GraphQL query from the JSON payload alone
	if err := json.Unmarshal(src, &graphqlQuery); err == nil && graphqlQuery.Query != "" && len(graphqlQuery.Variables) > 0 {
		colorHighlight := "\x1b[35;1m"
		colorReset := "\x1b[m"
		if !f.colorize {
			colorHighlight = ""
			colorReset = ""
		}
		if _, err := fmt.Fprintf(w, "%sGraphQL query:%s\n%s\n", colorHighlight, colorReset, strings.ReplaceAll(strings.TrimSpace(graphqlQuery.Query), "\t", "  ")); err != nil {
			return err
		}
		if _, err := fmt.Fprintf(w, "%sGraphQL variables:%s %s\n", colorHighlight, colorReset, string(graphqlQuery.Variables)); err != nil {
			return err
		}
		return nil
	}
	return jsonpretty.Format(w, bytes.NewReader(src), "  ", f.colorize)
}

func (f *jsonFormatter) Match(t string) bool {
	return jsonTypeRE.MatchString(t)
}