-
Notifications
You must be signed in to change notification settings - Fork 0
/
query_string.go
129 lines (110 loc) · 2.49 KB
/
query_string.go
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"bytes"
"fmt"
"github.com/mattn/go-zglob"
"github.com/vektah/gqlparser/v2/ast"
"github.com/vektah/gqlparser/v2/formatter"
"github.com/vektah/gqlparser/v2/parser"
"io"
"io/ioutil"
"log"
"os"
)
func main() {
if err := queryStringMain(); err != nil {
log.Fatalf("error: %+v", err)
}
}
func queryStringMain() error {
paths := os.Args[1:]
if len(paths) == 0 {
if err := processFile("<standard input>", os.Stdin, os.Stdout); err != nil {
return fmt.Errorf("failed to process stdin: %w", err)
}
return nil
}
extractGlobPathMap := make(map[string]struct{}, 0)
for _, path := range paths {
extracts, err := zglob.Glob(path)
if err != nil {
return fmt.Errorf("failed to glob: %w", err)
}
for _, extract := range extracts {
extractGlobPathMap[extract] = struct{}{}
}
}
var extractGlobPaths []string
for extractGlobPath := range extractGlobPathMap {
extractGlobPaths = append(extractGlobPaths, extractGlobPath)
}
for _, path := range extractGlobPaths {
if err := processFile(path, nil, os.Stdout); err != nil {
return fmt.Errorf("failed to read file: %w", err)
}
}
return nil
}
func processFile(filename string, in io.Reader, out io.Writer) error {
if in == nil {
f, err := os.Open(filename)
if err != nil {
return fmt.Errorf(": %w", err)
}
defer f.Close()
in = f
}
src, err := ioutil.ReadAll(in)
if err != nil {
return fmt.Errorf(": %w", err)
}
queryString := queryString(src)
if len(queryString) > 0 {
fmt.Fprintf(out, string(queryString))
}
return nil
}
func queryString(b []byte) []byte {
var queryStrings [][]byte
var start int
for {
stringLiteral, end := singleStringLiteral(b, start)
start = end + 1
query, isQuery := formatQuery(stringLiteral)
if isQuery {
queryStrings = append(queryStrings, query)
}
if start >= len(b) {
break
}
}
return bytes.Join(queryStrings, []byte(""))
}
func singleStringLiteral(b []byte, start int) ([]byte, int) {
begin, end := -1, -1
for i, c := range b[start:] {
if c == '`' {
if begin < 0 {
begin = i
} else {
end = i
break
}
}
}
if end < 0 {
return []byte{}, len(b)
}
return b[start+begin+1 : start+end], start + end
}
func formatQuery(src []byte) ([]byte, bool) {
source := &ast.Source{Name: "", Input: string(src)}
query, err := parser.ParseQuery(source)
if err != nil {
return nil, false
}
var buf bytes.Buffer
astFormatter := formatter.NewFormatter(&buf)
astFormatter.FormatQueryDocument(query)
return buf.Bytes(), true
}