-
Notifications
You must be signed in to change notification settings - Fork 4
/
parse.go
310 lines (265 loc) · 7.89 KB
/
parse.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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"strings"
"github.com/alecthomas/kingpin"
"github.com/flynn/json5"
"github.com/hashicorp/hcl"
isatty "github.com/mattn/go-isatty"
"github.com/pkg/errors"
)
const (
DefaultBufferSize = 16384
)
type ParseMode struct {
*GlobalConfig
BufferSize int
PrettyPrint bool
InputFormat string
OutputFormat string
}
func NewParseMode(globals *GlobalConfig) ParseMode {
return ParseMode{
GlobalConfig: globals,
BufferSize: DefaultBufferSize,
}
}
func ConfigureParseCommand(app *kingpin.Application, globals *GlobalConfig) error {
parseMode := NewParseMode(globals)
parseCommand := app.Command("convert", "Convert a configuration file to JSON").
Default().
Action(parseMode.run)
parseCommand.Flag("in-format", `Input format ("json", "json5", or "hcl")`).
Short('I').
Default("*").
StringVar(&parseMode.InputFormat)
parseCommand.Flag("out-format", `Output format ("json")`).
Short('O').
Default("json").
StringVar(&parseMode.OutputFormat)
parseCommand.Flag("pretty", "Pretty-print the output (true if output is a terminal)").
Short('p').
Default(fmt.Sprintf("%t", isatty.IsTerminal(os.Stdout.Fd()))).
BoolVar(&parseMode.PrettyPrint)
return nil
}
func (m *ParseMode) run(c *kingpin.ParseContext) error {
var f *os.File
var err error
if m.InFilename == "-" {
// When the input is stdin, write the input to a tempfile so in the event of
// an error highlightPosition() can scan the file to provide a useful hint
// regarding the syntax error.
f, err = ioutil.TempFile(os.TempDir(), "json5")
if err != nil {
return errors.Wrap(err, "unable to create temp file for stdin")
}
defer os.Remove(f.Name())
defer f.Close()
w := bufio.NewWriterSize(f, m.BufferSize)
io.Copy(w, bufio.NewReaderSize(os.Stdin, m.BufferSize))
err = w.Flush()
if err != nil {
return errors.Wrap(err, "unable to flush temp file")
}
f.Seek(0, os.SEEK_SET)
} else {
var err error
f, err = os.Open(m.InFilename)
if err != nil {
return errors.Wrap(err, "unable to read input")
}
defer f.Close()
}
var buf bytes.Buffer
if _, err := io.Copy(&buf, f); err != nil {
return errors.Wrap(err, "unable to read input")
}
var raw interface{}
var tryAllFormats bool
errList := make([]error, 0, 3)
switch m.InputFormat {
case "*":
tryAllFormats = true
fallthrough
case "json":
raw, err = ParseJSON(strings.NewReader(string(buf.Bytes())))
if err == nil {
break
}
var errWrapped error
switch parseErr := errors.Cause(err).(type) {
case *json.SyntaxError:
f.Seek(0, os.SEEK_SET)
// Grab the error location, and return a string to point to offending syntax error
line, col, highlight := highlightPosition(f, parseErr.Offset)
errWrapped = errors.Wrapf(err, "unable to parse %q as %q: %s\nSyntax error at line %d, column %d (offset %d):\n%s", m.InFilename, m.InputFormat, parseErr, line, col, parseErr.Offset, highlight)
default:
errWrapped = errors.Wrapf(err, "unable to parse config file as %q", m.InputFormat)
}
if !tryAllFormats {
return errWrapped
} else {
errList = append(errList, errWrapped)
}
fallthrough
case "json5":
raw, err = ParseJSON5(strings.NewReader(string(buf.Bytes())))
if err == nil {
break
}
var errWrapped error
switch parseErr := errors.Cause(err).(type) {
case *json5.SyntaxError:
f.Seek(0, os.SEEK_SET)
// Grab the error location, and return a string to point to offending syntax error
line, col, highlight := highlightPosition(f, parseErr.Offset)
errWrapped = errors.Wrapf(err, "unable to parse %q as %q: %s\nSyntax error at line %d, column %d (offset %d):\n%s", m.InFilename, m.InputFormat, parseErr, line, col, parseErr.Offset, highlight)
default:
errWrapped = errors.Wrapf(err, "unable to parse config file as %q", m.InputFormat)
}
if !tryAllFormats {
return errWrapped
} else {
errList = append(errList, errWrapped)
}
fallthrough
case "hcl":
raw, err = ParseHCL(string(buf.Bytes()))
if err == nil {
break
}
var errWrapped error
switch parseErr := errors.Cause(err).(type) {
default:
_ = parseErr // Preserve structure for future and improved error handling
errWrapped = errors.Wrapf(err, "unable to parse config file as %q", m.InputFormat)
}
if !tryAllFormats {
return errWrapped
} else {
errList = append(errList, errWrapped)
}
fallthrough
default:
if len(errList) > 0 {
return fmt.Errorf("Unsupported input type: %q: %v", m.InputFormat, errList)
} else {
return fmt.Errorf("Unsupported input type: %q", m.InputFormat)
}
}
var w *bufio.Writer
switch m.OutFilename {
case "-":
w = bufio.NewWriterSize(os.Stdout, m.BufferSize)
default:
// Assume a file
fo, err := os.Create(m.OutFilename)
if err != nil {
return errors.Wrap(err, "unable to open output file")
}
// FIXME (seanc@): Need to not panic() in a defer
defer func() {
if err := fo.Close(); err != nil {
panic(err)
}
}()
// FIXME (seanc@): Need to not panic() in a defer
defer func() {
if err := fo.Sync(); err != nil {
panic(err)
}
}()
w = bufio.NewWriter(fo)
}
defer w.Flush()
switch m.OutputFormat {
case "json":
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
if m.PrettyPrint || (m.OutFilename == "-" && m.PrettyPrint) {
enc.SetIndent("", " ")
}
if err = enc.Encode(raw); err != nil {
return errors.Wrap(err, "unable to encode")
}
default:
return fmt.Errorf("Unsupported output type: %q", m.OutputFormat)
}
return nil
}
// ParseHCL takes the given io.Reader and parses a Template object out of it.
func ParseHCL(input string) (interface{}, error) {
var raw interface{}
if err := hcl.Decode(&raw, input); err != nil {
return nil, errors.Wrap(err, "unable to decode HCL")
}
return raw, nil
}
// ParseJSON takes the given io.Reader and parses a Template object out of it.
func ParseJSON(r io.Reader) (interface{}, error) {
// Create a buffer to copy what we read
// var buf bytes.Buffer
// r = io.TeeReader(r, &buf)
// First, decode the object into an interface{}. We do this instead of
// the rawTemplate directly because we'd rather use mapstructure to
// decode since it has richer errors.
var raw interface{}
if err := json.NewDecoder(r).Decode(&raw); err != nil {
return nil, errors.Wrap(err, "unable to decode JSON")
}
return raw, nil
}
// ParseJSON5 takes the given io.Reader and parses a Template object out of it.
func ParseJSON5(r io.Reader) (interface{}, error) {
// Create a buffer to copy what we read
// var buf bytes.Buffer
// r = io.TeeReader(r, &buf)
// First, decode the object into an interface{}. We do this instead of
// the rawTemplate directly because we'd rather use mapstructure to
// decode since it has richer errors.
var raw interface{}
if err := json5.NewDecoder(r).Decode(&raw); err != nil {
return nil, errors.Wrap(err, "unable to decode JSON5")
}
return raw, nil
}
// Takes a file and the location in bytes of a parse error from
// json5.SyntaxError.Offset and returns the line, column, and pretty-printed
// context around the error with an arrow indicating the exact position of the
// syntax error.
func highlightPosition(f *os.File, pos int64) (line, col int, highlight string) {
// Modified version of the function in Camlistore by Brad Fitzpatrick
// https://github.com/camlistore/camlistore/blob/4b5403dd5310cf6e1ae8feb8533fd59262701ebc/vendor/go4.org/errorutil/highlight.go
line = 1
br := bufio.NewReader(f)
lastLine := ""
thisLine := new(bytes.Buffer)
for n := int64(0); n < pos; n++ {
b, err := br.ReadByte()
if err != nil {
break
}
if b == '\n' {
lastLine = thisLine.String()
thisLine.Reset()
line++
col = 1
} else {
col++
thisLine.WriteByte(b)
}
}
if line > 1 {
highlight += fmt.Sprintf("%5d: %s\n", line-1, lastLine)
}
highlight += fmt.Sprintf("%5d: %s\n", line, thisLine.String())
highlight += fmt.Sprintf("%s^\n", strings.Repeat(" ", col+5))
return
}