forked from cue-lang/cue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filetypes.go
315 lines (280 loc) · 8.01 KB
/
filetypes.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
// Copyright 2020 CUE Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:generate go run gen.go
package filetypes
import (
"path/filepath"
"strings"
"github.com/wylswz/cue-se/cue"
"github.com/wylswz/cue-se/cue/build"
"github.com/wylswz/cue-se/cue/errors"
"github.com/wylswz/cue-se/cue/token"
)
// Mode indicate the base mode of operation and indicates a different set of
// defaults.
type Mode int
const (
Input Mode = iota // The default
Export
Def
Eval
)
func (m Mode) String() string {
switch m {
default:
return "input"
case Eval:
return "eval"
case Export:
return "export"
case Def:
return "def"
}
}
// FileInfo defines the parsing plan for a file.
type FileInfo struct {
*build.File
Definitions bool `json:"definitions"` // include/allow definition fields
Data bool `json:"data"` // include/allow regular fields
Optional bool `json:"optional"` // include/allow definition fields
Constraints bool `json:"constraints"` // include/allow constraints
References bool `json:"references"` // don't resolve/allow references
Cycles bool `json:"cycles"` // cycles are permitted
KeepDefaults bool `json:"keepDefaults"` // select/allow default values
Incomplete bool `json:"incomplete"` // permit incomplete values
Imports bool `json:"imports"` // don't expand/allow imports
Stream bool `json:"stream"` // permit streaming
Docs bool `json:"docs"` // show/allow docs
Attributes bool `json:"attributes"` // include/allow attributes
}
// FromFile return detailed file info for a given build file.
// Encoding must be specified.
// TODO: mode should probably not be necessary here.
func FromFile(b *build.File, mode Mode) (*FileInfo, error) {
// Handle common case. This allows certain test cases to be analyzed in
// isolation without interference from evaluating these files.
if mode == Input &&
b.Encoding == build.CUE &&
b.Form == build.Schema &&
b.Interpretation == "" {
return &FileInfo{
File: b,
Definitions: true,
Data: true,
Optional: true,
Constraints: true,
References: true,
Cycles: true,
KeepDefaults: true,
Incomplete: true,
Imports: true,
Stream: true,
Docs: true,
Attributes: true,
}, nil
}
i, errs := update(nil, cuegenValue, cuegenValue, "modes", mode.String())
v := i.LookupDef("FileInfo")
v = v.Fill(b)
if b.Encoding == "" {
ext := i.Lookup("extensions", fileExt(b.Filename))
if ext.Exists() {
v = v.Unify(ext)
}
}
interpretation, _ := v.Lookup("interpretation").String()
if b.Form != "" {
v, errs = update(errs, v, i, "forms", string(b.Form))
// may leave some encoding-dependent options open in data mode.
} else if interpretation != "" {
// always sets schema form.
v, errs = update(errs, v, i, "interpretations", interpretation)
}
if interpretation == "" {
s, err := v.Lookup("encoding").String()
if err != nil {
return nil, err
}
v, errs = update(errs, v, i, "encodings", s)
}
fi := &FileInfo{}
if err := v.Decode(fi); err != nil {
return nil, errors.Wrapf(err, token.NoPos, "could not parse arguments")
}
return fi, errs
}
func update(errs errors.Error, v, i cue.Value, field, value string) (cue.Value, errors.Error) {
v = v.Unify(i.Lookup(field, value))
if err := v.Err(); err != nil {
errs = errors.Append(errs,
errors.Newf(token.NoPos, "unknown %s %s", field, value))
}
return v, errs
}
// ParseArgs converts a sequence of command line arguments representing
// files into a sequence of build file specifications.
//
// The arguments are of the form
//
// file* (spec: file+)*
//
// where file is a filename and spec is itself of the form
//
// tag[=value]('+'tag[=value])*
//
// A file type spec applies to all its following files and until a next spec
// is found.
//
// Examples:
//
// json: foo.data bar.data json+schema: bar.schema
func ParseArgs(args []string) (files []*build.File, err error) {
var inst, v cue.Value
qualifier := ""
hasFiles := false
for i, s := range args {
a := strings.Split(s, ":")
switch {
case len(a) == 1 || len(a[0]) == 1: // filename
if !v.Exists() {
if len(a) == 1 && strings.HasSuffix(a[0], ".cue") {
// Handle majority case.
files = append(files, &build.File{
Filename: a[0],
Encoding: build.CUE,
Form: build.Schema,
})
hasFiles = true
continue
}
inst, v, err = parseType("", Input)
if err != nil {
return nil, err
}
}
f, err := toFile(inst, v, s)
if err != nil {
return nil, err
}
files = append(files, f)
hasFiles = true
case len(a) > 2 || a[0] == "":
return nil, errors.Newf(token.NoPos,
"unsupported file name %q: may not have ':'", s)
case a[1] != "":
return nil, errors.Newf(token.NoPos, "cannot combine scope with file")
default: // scope
switch {
case i == len(args)-1:
qualifier = a[0]
fallthrough
case qualifier != "" && !hasFiles:
return nil, errors.Newf(token.NoPos, "scoped qualifier %q without file", qualifier+":")
}
inst, v, err = parseType(a[0], Input)
if err != nil {
return nil, err
}
qualifier = a[0]
hasFiles = false
}
}
return files, nil
}
// ParseFile parses a single-argument file specifier, such as when a file is
// passed to a command line argument.
//
// Example:
//
// cue eval -o yaml:foo.data
func ParseFile(s string, mode Mode) (*build.File, error) {
scope := ""
file := s
if p := strings.LastIndexByte(s, ':'); p >= 0 {
scope = s[:p]
file = s[p+1:]
if scope == "" {
return nil, errors.Newf(token.NoPos, "unsupported file name %q: may not have ':", s)
}
}
if file == "" {
return nil, errors.Newf(token.NoPos, "empty file name in %q", s)
}
inst, val, err := parseType(scope, mode)
if err != nil {
return nil, err
}
return toFile(inst, val, file)
}
func hasEncoding(v cue.Value) (concrete, hasDefault bool) {
enc := v.Lookup("encoding")
d, _ := enc.Default()
return enc.IsConcrete(), d.IsConcrete()
}
func toFile(i, v cue.Value, filename string) (*build.File, error) {
v = v.Fill(filename, "filename")
if concrete, hasDefault := hasEncoding(v); !concrete {
if filename == "-" {
if !hasDefault {
v = v.Unify(i.LookupDef("Default"))
}
} else if ext := fileExt(filename); ext != "" {
if x := i.Lookup("extensions", ext); x.Exists() || !hasDefault {
v = v.Unify(x)
if err := v.Err(); err != nil {
return nil, errors.Newf(token.NoPos,
"unknown file extension %s", ext)
}
}
} else if !hasDefault {
return nil, errors.Newf(token.NoPos,
"no encoding specified for file %q", filename)
}
}
f := &build.File{}
if err := v.Decode(&f); err != nil {
return nil, errors.Wrapf(err, token.NoPos,
"could not determine file type")
}
return f, nil
}
func parseType(s string, mode Mode) (inst, val cue.Value, err error) {
i := cuegenValue
i = i.Unify(i.Lookup("modes", mode.String()))
v := i.LookupDef("File")
if s != "" {
for _, t := range strings.Split(s, "+") {
if p := strings.IndexByte(t, '='); p >= 0 {
v = v.Fill(t[p+1:], "tags", t[:p])
} else {
info := i.Lookup("tags", t)
if !info.Exists() {
return inst, val, errors.Newf(token.NoPos,
"unknown filetype %s", t)
}
v = v.Unify(info)
}
}
}
return i, v, nil
}
// fileExt is like filepath.Ext except we don't treat file names starting with "." as having an extension
// unless there's also another . in the name.
func fileExt(f string) string {
e := filepath.Ext(f)
if e == "" || e == filepath.Base(f) {
return ""
}
return e
}