-
Notifications
You must be signed in to change notification settings - Fork 5
/
parse.go
473 lines (397 loc) · 12.6 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
package raml
import (
"bufio"
"context"
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"gopkg.in/yaml.v3"
"github.com/acronis/go-stacktrace"
)
// ReadHead reads, reset file and returns the trimmed first line of a file.
func ReadHead(f io.ReadSeeker) (string, error) {
r := bufio.NewReader(f)
head, err := r.ReadString('\n')
if err != nil {
return "", fmt.Errorf("read fragment head: %w", err)
}
_, err = f.Seek(0, io.SeekStart)
if err != nil {
return "", fmt.Errorf("seek to start: %w", err)
}
head = strings.TrimRight(head, "\r\n ")
return head, nil
}
// IdentifyFragment returns the kind of the fragment by its head.
func IdentifyFragment(head string) (FragmentKind, error) {
switch head {
case "#%RAML 1.0 Library":
return FragmentLibrary, nil
case "#%RAML 1.0 DataType":
return FragmentDataType, nil
case "#%RAML 1.0 NamedExample":
return FragmentNamedExample, nil
default:
return FragmentUnknown, fmt.Errorf("unknown fragment kind: head: %s", head)
}
}
// ReadRawFile reads a file
func ReadRawFile(path string) (io.ReadCloser, error) {
f, err := openFragmentFile(path)
if err != nil {
return nil, StacktraceNewWrapped("open fragment file", err, path,
stacktrace.WithType(StacktraceTypeReading))
}
return f, nil
}
// decodeDataType decodes a data type (*DataType) from a file.
func (r *RAML) decodeDataType(f io.Reader, path string) (*DataType, error) {
// TODO: This is a temporary workaround for JSON data types.
if strings.HasSuffix(path, ".json") {
data, err := io.ReadAll(f)
if err != nil {
return nil, StacktraceNewWrapped("read file", err, path,
stacktrace.WithType(StacktraceTypeReading))
}
dt, err := r.MakeJSONDataType(data, path)
if err != nil {
return nil, StacktraceNewWrapped("make json data type", err, path,
stacktrace.WithType(StacktraceTypeParsing))
}
r.PutFragment(path, dt)
return dt, nil
}
decoder := yaml.NewDecoder(f)
dt := r.MakeDataType(path)
if err := decoder.Decode(&dt); err != nil {
return nil, StacktraceNewWrapped("decode fragment", err, path,
stacktrace.WithType(StacktraceTypeParsing))
}
r.PutFragment(path, dt)
baseDir := filepath.Dir(dt.Location)
for pair := dt.Uses.Oldest(); pair != nil; pair = pair.Next() {
include := pair.Value
sublib, err := r.parseLibrary(filepath.Join(baseDir, include.Value))
if err != nil {
return nil, StacktraceNewWrapped("parse library", err, dt.Location,
stacktrace.WithType(StacktraceTypeParsing))
}
include.Link = sublib
}
return dt, nil
}
func CheckFragmentKind(f *os.File, kind FragmentKind) error {
// Allow JSON data types.
if kind == FragmentDataType && strings.HasSuffix(f.Name(), ".json") {
return nil
}
head, err := ReadHead(f)
if err != nil {
return fmt.Errorf("read head: %w", err)
}
frag, err := IdentifyFragment(head)
if err != nil {
return fmt.Errorf("identify fragment: %w", err)
}
if frag != kind {
return fmt.Errorf("unexpected fragment frag != kind: %v != %v", frag, kind)
}
return nil
}
const HookBeforeParseDataType = "before:RAML.parseDataType"
func (r *RAML) parseDataType(path string) (*DataType, error) {
if err := r.callHooks(HookBeforeParseDataType, path); err != nil {
return nil, err
}
// IMPORTANT: May generate recursive structure.
// Consumers (resolvers, validators, external clients) must implement recursion detection when traversing links.
// Fragment paths must be normalized to absolute paths to simplify dependent libraries resolution.
if dt := r.GetFragment(path); dt != nil {
// log.Printf("reusing fragment %s", path)
return dt.(*DataType), nil
}
f, err := openFragmentFile(path)
if err != nil {
return nil, StacktraceNewWrapped("open fragment file", err, path,
stacktrace.WithType(StacktraceTypeReading))
}
defer func(f *os.File) {
err = f.Close()
if err != nil {
log.Fatalf("close file error: %v", err)
}
}(f)
if err = CheckFragmentKind(f, FragmentDataType); err != nil {
return nil, StacktraceNewWrapped("check fragment kind", err, path,
stacktrace.WithType(StacktraceTypeReading))
}
dt, err := r.decodeDataType(f, path)
if err != nil {
return nil, StacktraceNewWrapped("decode data type", err, path,
stacktrace.WithType(StacktraceTypeParsing))
}
return dt, nil
}
func openFragmentFile(path string) (*os.File, error) {
// TODO: Maybe fragments should be loaded against specified base URI.
// If base URI is not specified, use current workdir.
if !filepath.IsAbs(path) {
workdir, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("get workdir: %w", err)
}
path = filepath.Join(workdir, path)
}
f, err := os.OpenFile(path, os.O_RDONLY, os.ModePerm)
if err != nil {
return nil, fmt.Errorf("open file: %w", err)
}
return f, nil
}
func (r *RAML) decodeLibrary(f io.Reader, path string) (*Library, error) {
decoder := yaml.NewDecoder(f)
lib := r.MakeLibrary(path)
if err := decoder.Decode(&lib); err != nil {
return nil, StacktraceNewWrapped("decode fragment", err, path,
stacktrace.WithType(StacktraceTypeParsing))
}
var st *stacktrace.StackTrace
r.PutFragment(path, lib)
// Resolve included libraries in a separate stage.
baseDir := filepath.Dir(lib.Location)
for pair := lib.Uses.Oldest(); pair != nil; pair = pair.Next() {
include := pair.Value
sublib, err := r.parseLibrary(filepath.Join(baseDir, include.Value))
if err != nil {
se := StacktraceNewWrapped("parse uses library", err, path,
stacktrace.WithType(StacktraceTypeParsing), stacktrace.WithPosition(&include.Position))
if st == nil {
st = se
} else {
st = st.Append(se)
}
}
include.Link = sublib
}
if st != nil {
return nil, st
}
return lib, nil
}
func (r *RAML) parseLibrary(path string) (*Library, error) {
// IMPORTANT: May generate recursive structure.
// Consumers (resolvers, validators, external clients) must implement recursion detection when traversing links.
// Fragment paths must be normalized to absolute paths to simplify dependent libraries resolution.
// TODO: Add support for URI
var err error
if lib := r.GetFragment(path); lib != nil {
// slog.Debug("reusing fragment", slog.String("path", path))
return lib.(*Library), nil
}
f, err := openFragmentFile(path)
if err != nil {
return nil, StacktraceNewWrapped("open fragment file", err, path,
stacktrace.WithType(StacktraceTypeLoading))
}
defer func(f *os.File) {
err = f.Close()
if err != nil {
log.Fatalf("close file error: %v", err)
}
}(f)
if err = CheckFragmentKind(f, FragmentLibrary); err != nil {
return nil, StacktraceNewWrapped("check fragment kind", err, path,
stacktrace.WithType(StacktraceTypeReading))
}
lib, err := r.decodeLibrary(f, path)
if err != nil {
return nil, StacktraceNewWrapped("decode library", err, path,
stacktrace.WithType(StacktraceTypeParsing))
}
return lib, nil
}
func (r *RAML) decodeNamedExample(f io.Reader, path string) (*NamedExample, error) {
decoder := yaml.NewDecoder(f)
ne := r.MakeNamedExample(path)
if err := decoder.Decode(&ne); err != nil {
return nil, StacktraceNewWrapped("decode fragment", err, path,
stacktrace.WithType(StacktraceTypeParsing))
}
r.PutFragment(path, ne)
return ne, nil
}
func (r *RAML) parseNamedExample(path string) (*NamedExample, error) {
// Library paths must be normalized to simplify dependent libraries resolution.
// Convert rel to abs relative to current workdir if necessary.
if lib := r.GetFragment(path); lib != nil {
// slog.Debug("reusing fragment", slog.String("path", path))
return lib.(*NamedExample), nil
}
f, err := openFragmentFile(path)
if err != nil {
return nil, fmt.Errorf("open fragment file: %w", err)
}
defer func(f *os.File) {
err = f.Close()
if err != nil {
log.Fatalf("close file error: %v", err)
}
}(f)
if err = CheckFragmentKind(f, FragmentNamedExample); err != nil {
return nil, StacktraceNewWrapped("check fragment kind", err, path,
stacktrace.WithType(StacktraceTypeReading))
}
ne, err := r.decodeNamedExample(f, path)
if err != nil {
return nil, StacktraceNewWrapped("decode named example", err, path,
stacktrace.WithType(StacktraceTypeParsing))
}
return ne, nil
}
func (r *RAML) ParseFromPath(path string, opts ...ParseOpt) error {
// Library paths must be normalized to simplify dependent libraries resolution.
// Convert rel to abs relative to current workdir if necessary.
pOpts := &parserOptions{}
for _, opt := range opts {
opt.Apply(pOpts)
}
f, err := openFragmentFile(path)
if err != nil {
return StacktraceNewWrapped("open fragment file", err, path,
stacktrace.WithType(StacktraceTypeReading))
}
defer func(f *os.File) {
err = f.Close()
if err != nil {
log.Fatalf("close file error: %v", err)
}
}(f)
return r.parseFragment(f, f.Name(), pOpts)
}
func (r *RAML) ParseFromString(content string, fileName string, baseDir string, opts ...ParseOpt) error {
pOpts := &parserOptions{}
for _, opt := range opts {
opt.Apply(pOpts)
}
f := strings.NewReader(content)
return r.parseFragment(f, filepath.Join(baseDir, fileName), pOpts)
}
func (r *RAML) parseFragment(f io.ReadSeeker, fragmentPath string, pOpts *parserOptions) error {
head, err := ReadHead(f)
if err != nil {
return StacktraceNewWrapped("read head", err, fragmentPath,
stacktrace.WithType(StacktraceTypeParsing))
}
frag, err := IdentifyFragment(head)
if err != nil {
return StacktraceNewWrapped("identify fragment", err, fragmentPath,
stacktrace.WithType(StacktraceTypeParsing))
}
switch frag {
case FragmentUnknown:
return StacktraceNew("unknown fragment kind", fragmentPath,
stacktrace.WithType(StacktraceTypeParsing))
case FragmentLibrary:
lib, errDecode := r.decodeLibrary(f, fragmentPath)
if errDecode != nil {
return StacktraceNewWrapped("parse library", errDecode, fragmentPath,
stacktrace.WithType(StacktraceTypeParsing))
}
r.SetEntryPoint(lib)
case FragmentDataType:
dt, errDecode := r.decodeDataType(f, fragmentPath)
if errDecode != nil {
return StacktraceNewWrapped("parse data type", errDecode, fragmentPath,
stacktrace.WithType(StacktraceTypeParsing))
}
r.SetEntryPoint(dt)
case FragmentNamedExample:
ne, errDecode := r.decodeNamedExample(f, fragmentPath)
if errDecode != nil {
return StacktraceNewWrapped("parse named example", errDecode, fragmentPath,
stacktrace.WithType(StacktraceTypeParsing))
}
r.SetEntryPoint(ne)
default:
return StacktraceNew("unknown fragment kind", fragmentPath,
stacktrace.WithInfo("head", head), stacktrace.WithType(StacktraceTypeParsing))
}
err = r.resolveShapes()
if err != nil {
return StacktraceNewWrapped("resolve shapes", err, fragmentPath,
stacktrace.WithType(StacktraceTypeParsing))
}
err = r.resolveDomainExtensions()
if err != nil {
return StacktraceNewWrapped("resolve domain extensions", err, fragmentPath,
stacktrace.WithType(StacktraceTypeParsing))
}
if pOpts.withUnwrapOpt {
err = r.UnwrapShapes()
if err != nil {
return StacktraceNewWrapped("unwrap shapes", err, fragmentPath,
stacktrace.WithType(StacktraceTypeParsing))
}
}
if pOpts.withValidateOpt {
err = r.ValidateShapes()
if err != nil {
return StacktraceNewWrapped("validate shapes", err, fragmentPath,
stacktrace.WithType(StacktraceTypeParsing))
}
}
return nil
}
func ParseFromPathCtx(ctx context.Context, path string, opts ...ParseOpt) (*RAML, error) {
if ctx == nil {
return nil, fmt.Errorf("context is nil")
}
rml := New(ctx)
err := rml.ParseFromPath(path, opts...)
return rml, err
}
func ParseFromPath(path string, opts ...ParseOpt) (*RAML, error) {
return ParseFromPathCtx(context.Background(), path, opts...)
}
func ParseFromStringCtx(
ctx context.Context, content string, fileName string,
baseDir string, opts ...ParseOpt,
) (*RAML, error) {
if ctx == nil {
return nil, fmt.Errorf("context is nil")
}
rml := New(ctx)
err := rml.ParseFromString(content, fileName, baseDir, opts...)
return rml, err
}
func ParseFromString(content string, fileName string, baseDir string, opts ...ParseOpt) (*RAML, error) {
// TODO: Probably needs to be a bit more flexible. Maybe baseDir must be defined as parser option?
if !filepath.IsAbs(baseDir) {
return nil, fmt.Errorf("baseDir must be an absolute path")
}
return ParseFromStringCtx(context.Background(), content, fileName, baseDir, opts...)
}
type parserOptions struct {
withUnwrapOpt bool
withValidateOpt bool
}
type ParseOpt interface {
Apply(*parserOptions)
}
type parseOptWithUnwrap struct{}
func (parseOptWithUnwrap) Apply(opt *parserOptions) {
opt.withUnwrapOpt = true
}
func OptWithUnwrap() ParseOpt {
return parseOptWithUnwrap{}
}
type parseOptWithValidate struct{}
func (parseOptWithValidate) Apply(opt *parserOptions) {
opt.withValidateOpt = true
}
func OptWithValidate() ParseOpt {
return parseOptWithValidate{}
}