forked from tomnomnom/gron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatements.go
267 lines (223 loc) · 6.12 KB
/
statements.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"strconv"
"unicode"
"unicode/utf8"
"github.com/pkg/errors"
)
// formatter is an interchangeable statement formatter. It's
// interchangeable so that it can be swapped between the
// monochrome and color formatters
var formatter statementFormatter = colorFormatter{}
// statements is a list of assignment statements.
// E.g statement: json.foo = "bar";
type statements []string
// Add adds a new statement to the list given the key and a value
func (ss *statements) Add(key string, value interface{}) {
*ss = append(*ss, formatter.assignment(key, value))
}
// AddFull adds a new statement to the list given the entire statement
func (ss *statements) AddFull(s string) {
*ss = append(*ss, s)
}
// AddMulti adds a whole other list of statements
func (ss *statements) AddMulti(l statements) {
*ss = append(*ss, l...)
}
// Len returns the number of statements for sort.Sort
func (ss statements) Len() int {
return len(ss)
}
// Swap swaps two statements for sort.Sort
func (ss statements) Swap(i, j int) {
ss[i], ss[j] = ss[j], ss[i]
}
// ungron turns statements into a proper datastructure
func (ss statements) ungron() (interface{}, error) {
// Get all the individually parsed statements
var parsed []interface{}
for _, s := range ss {
l := newLexer(s)
u, err := ungronTokens(l.lex())
switch err.(type) {
case nil:
// no problem :)
case errRecoverable:
continue
default:
return nil, errors.Wrapf(err, "ungron failed for `%s`", s)
}
parsed = append(parsed, u)
}
if len(parsed) == 0 {
return nil, fmt.Errorf("no statements were parsed")
}
merged := parsed[0]
for _, p := range parsed[1:] {
m, err := recursiveMerge(merged, p)
if err != nil {
return nil, errors.Wrap(err, "failed to merge statements")
}
merged = m
}
return merged, nil
}
// Less compares two statements for sort.Sort
// Implements a natural sort to keep array indexes in order
func (ss statements) Less(a, b int) bool {
// Two statements should never be identical, but I can't bring
// myself not to guard against the possibility
if ss[a] == ss[b] {
return true
}
// The statements may contain ANSI color codes. We don't
// want to sort based on the colors so we need to strip
// them out first
aStr := stripColors(ss[a])
bStr := stripColors(ss[b])
// Find where the two strings start to differ, keeping track
// of where any numbers start so that we can compare them properly
numStart := -1
diffStart := -1
for i, ra := range aStr {
rb, _ := utf8.DecodeRuneInString(bStr[i:])
// Are we looking at a number?
isNum := unicode.IsNumber(ra) && unicode.IsNumber(rb)
// If we are looking at a number but don't have a start
// position then this is the start of a new number
if isNum && numStart == -1 {
numStart = i
}
// Found a difference
if ra != rb {
diffStart = i
break
}
// There was no difference yet, so if we're not looking at a
// number: reset numStart so we start looking again
if !isNum {
numStart = -1
}
}
// If diffStart is still -1 then the only difference must be
// that string B is longer than A, so A should come first
if diffStart == -1 {
return true
}
// If we don't have a start position for a number, that means the
// difference we found wasn't numeric, so do a regular comparison
// on the remainder of the strings
if numStart == -1 {
return aStr[diffStart:] < bStr[diffStart:]
}
// Read and compare the numbers from each string
return readNum(aStr[numStart:]) < readNum(bStr[numStart:])
}
// stripColors removes ANSI colors from a string
func stripColors(in string) string {
var buf bytes.Buffer
inColor := false
for i := 0; i < len(in); {
r, l := utf8.DecodeRuneInString(in[i:])
i += l
if inColor && r == 'm' {
inColor = false
continue
}
// Escape char
if r == 0x001B {
inColor = true
}
if inColor {
continue
}
// buf.WriteRune doesn't actually ever return
// an error, so it's safe to ignore it
_, _ = buf.WriteRune(r)
}
return buf.String()
}
// readNum reads digits from a string until it hits a non-digit,
// returning the digits as an integer
func readNum(str string) int {
numEnd := len(str)
for i, r := range str {
// If we hit a non-number then we've found the end
if !unicode.IsNumber(r) {
numEnd = i
break
}
}
// If we've failed to parse a number then zero is
// just fine; it's being used for sorting only
num, _ := strconv.Atoi(str[:numEnd])
return num
}
// Contains searches the statements for a given statement
// Mostly to make testing things easier
func (ss statements) Contains(search string) bool {
for _, i := range ss {
// The Contains method is used exclusively for testing
// so while stripping the colors out of every statement
// every time Contains is called isn't very efficient,
// it won't affect users' performance.
i = stripColors(i)
if i == search {
return true
}
}
return false
}
// makeStatementsFromJSON takes an io.Reader containing JSON
// and returns statements or an error on failure
func makeStatementsFromJSON(r io.Reader) (statements, error) {
var top interface{}
d := json.NewDecoder(r)
d.UseNumber()
err := d.Decode(&top)
if err != nil {
return nil, err
}
return makeStatements("json", top)
}
// makeStatements takes a prefix and interface value and returns
// a statements list or an error on failure
func makeStatements(prefix string, v interface{}) (statements, error) {
ss := make(statements, 0)
// Add a statement for the current prefix and value
ss.Add(prefix, v)
// Recurse into objects and arrays
switch vv := v.(type) {
case map[string]interface{}:
// It's an object
for k, sub := range vv {
newPrefix, err := formatter.prefix(prefix, k)
if err != nil {
return ss, err
}
extra, err := makeStatements(newPrefix, sub)
if err != nil {
return ss, err
}
ss.AddMulti(extra)
}
case []interface{}:
// It's an array
for k, sub := range vv {
newPrefix, err := formatter.prefix(prefix, k)
if err != nil {
return ss, err
}
extra, err := makeStatements(newPrefix, sub)
if err != nil {
return ss, err
}
ss.AddMulti(extra)
}
}
return ss, nil
}