forked from cue-lang/cue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.go
327 lines (297 loc) · 7.66 KB
/
encoder.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
// 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.
package encoding
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"cuelang.org/go/cue"
"cuelang.org/go/cue/ast"
"cuelang.org/go/cue/build"
"cuelang.org/go/cue/errors"
"cuelang.org/go/cue/format"
"cuelang.org/go/cue/token"
"cuelang.org/go/encoding/openapi"
"cuelang.org/go/encoding/protobuf/jsonpb"
"cuelang.org/go/encoding/protobuf/textproto"
"cuelang.org/go/encoding/toml"
"cuelang.org/go/encoding/yaml"
"cuelang.org/go/internal"
"cuelang.org/go/internal/filetypes"
)
// An Encoder converts CUE to various file formats, including CUE itself.
// An Encoder allows
type Encoder struct {
ctx *cue.Context
cfg *Config
close func() error
interpret func(cue.Value) (*ast.File, error)
encFile func(*ast.File) error
encValue func(cue.Value) error
autoSimplify bool
concrete bool
}
// IsConcrete reports whether the output is required to be concrete.
//
// INTERNAL ONLY: this is just to work around a problem related to issue #553
// of catching errors only after syntax generation, dropping line number
// information.
func (e *Encoder) IsConcrete() bool {
return e.concrete
}
func (e Encoder) Close() error {
if e.close == nil {
return nil
}
return e.close()
}
// NewEncoder writes content to the file with the given specification.
func NewEncoder(ctx *cue.Context, f *build.File, cfg *Config) (*Encoder, error) {
w, close := writer(f, cfg)
e := &Encoder{
ctx: ctx,
cfg: cfg,
close: close,
}
switch f.Interpretation {
case "":
case build.OpenAPI:
// TODO: get encoding options
cfg := &openapi.Config{}
e.interpret = func(v cue.Value) (*ast.File, error) {
return openapi.Generate(v, cfg)
}
case build.ProtobufJSON:
e.interpret = func(v cue.Value) (*ast.File, error) {
f := internal.ToFile(v.Syntax())
return f, jsonpb.NewEncoder(v).RewriteFile(f)
}
// case build.JSONSchema:
// // TODO: get encoding options
// cfg := openapi.Config{}
// i.interpret = func(inst *cue.Instance) (*ast.File, error) {
// return jsonschmea.Generate(inst, cfg)
// }
default:
return nil, fmt.Errorf("unsupported interpretation %q", f.Interpretation)
}
switch f.Encoding {
case build.CUE:
fi, err := filetypes.FromFile(f, cfg.Mode)
if err != nil {
return nil, err
}
e.concrete = !fi.Incomplete
synOpts := []cue.Option{}
if !fi.KeepDefaults || !fi.Incomplete {
synOpts = append(synOpts, cue.Final())
}
synOpts = append(synOpts,
cue.Docs(fi.Docs),
cue.Attributes(fi.Attributes),
cue.Optional(fi.Optional),
cue.Concrete(!fi.Incomplete),
cue.Definitions(fi.Definitions),
cue.DisallowCycles(!fi.Cycles),
cue.InlineImports(cfg.InlineImports),
)
opts := []format.Option{}
opts = append(opts, cfg.Format...)
useSep := false
format := func(name string, n ast.Node) error {
if name != "" && cfg.Stream {
// TODO: make this relative to DIR
fmt.Fprintf(w, "// %s\n", filepath.Base(name))
} else if useSep {
fmt.Println("// ---")
}
useSep = true
opts := opts
if e.autoSimplify {
opts = append(opts, format.Simplify())
}
// Casting an ast.Expr to an ast.File ensures that it always ends
// with a newline.
f := internal.ToFile(n)
if e.cfg.PkgName != "" && f.PackageName() == "" {
pkg := &ast.Package{
PackagePos: token.NoPos.WithRel(token.NewSection),
Name: ast.NewIdent(e.cfg.PkgName),
}
doc, rest := internal.FileComments(f)
ast.SetComments(pkg, doc)
ast.SetComments(f, rest)
f.Decls = append([]ast.Decl{pkg}, f.Decls...)
}
b, err := format.Node(f, opts...)
if err != nil {
return err
}
_, err = w.Write(b)
return err
}
e.encValue = func(v cue.Value) error {
return format("", v.Syntax(synOpts...))
}
e.encFile = func(f *ast.File) error { return format(f.Filename, f) }
case build.JSON, build.JSONL:
e.concrete = true
d := json.NewEncoder(w)
d.SetIndent("", " ")
d.SetEscapeHTML(cfg.EscapeHTML)
e.encValue = func(v cue.Value) error {
err := d.Encode(v)
if x, ok := err.(*json.MarshalerError); ok {
err = x.Err
}
return err
}
case build.YAML:
e.concrete = true
streamed := false
// TODO(mvdan): use a NewEncoder API like in TOML below.
e.encValue = func(v cue.Value) error {
if streamed {
fmt.Fprintln(w, "---")
}
streamed = true
b, err := yaml.Encode(v)
if err != nil {
return err
}
_, err = w.Write(b)
return err
}
case build.TOML:
e.concrete = true
enc := toml.NewEncoder(w)
e.encValue = enc.Encode
case build.TextProto:
// TODO: verify that the schema is given. Otherwise err out.
e.concrete = true
e.encValue = func(v cue.Value) error {
v = v.Unify(cfg.Schema)
b, err := textproto.NewEncoder().Encode(v)
if err != nil {
return err
}
_, err = w.Write(b)
return err
}
case build.Text:
e.concrete = true
e.encValue = func(v cue.Value) error {
s, err := v.String()
if err != nil {
return err
}
_, err = fmt.Fprint(w, s)
if err != nil {
return err
}
_, err = fmt.Fprintln(w)
return err
}
case build.Binary:
e.concrete = true
e.encValue = func(v cue.Value) error {
b, err := v.Bytes()
if err != nil {
return err
}
_, err = w.Write(b)
return err
}
default:
return nil, fmt.Errorf("unsupported encoding %q", f.Encoding)
}
return e, nil
}
func (e *Encoder) EncodeFile(f *ast.File) error {
e.autoSimplify = false
return e.encodeFile(f, e.interpret)
}
func (e *Encoder) Encode(v cue.Value) error {
e.autoSimplify = true
if err := v.Validate(cue.Concrete(e.concrete)); err != nil {
return err
}
if e.interpret != nil {
f, err := e.interpret(v)
if err != nil {
return err
}
return e.encodeFile(f, nil)
}
if e.encValue != nil {
return e.encValue(v)
}
return e.encFile(internal.ToFile(v.Syntax()))
}
func (e *Encoder) encodeFile(f *ast.File, interpret func(cue.Value) (*ast.File, error)) error {
if interpret == nil && e.encFile != nil {
return e.encFile(f)
}
e.autoSimplify = true
v := e.ctx.BuildFile(f)
if err := v.Err(); err != nil {
return err
}
if interpret != nil {
return e.Encode(v)
}
if err := v.Validate(cue.Concrete(e.concrete)); err != nil {
return err
}
return e.encValue(v)
}
func writer(f *build.File, cfg *Config) (_ io.Writer, close func() error) {
if cfg.Out != nil {
return cfg.Out, nil
}
path := f.Filename
if path == "-" {
if cfg.Stdout == nil {
return os.Stdout, nil
}
return cfg.Stdout, nil
}
// Delay opening the file until we can write it to completion.
// This prevents clobbering the file in case of a crash.
b := &bytes.Buffer{}
fn := func() error {
mode := os.O_WRONLY | os.O_CREATE | os.O_EXCL
if cfg.Force {
// Swap O_EXCL for O_TRUNC to allow replacing an entire existing file.
mode = os.O_WRONLY | os.O_CREATE | os.O_TRUNC
}
f, err := os.OpenFile(path, mode, 0o666)
if err != nil {
if errors.Is(err, fs.ErrExist) {
return errors.Wrapf(fs.ErrExist, token.NoPos, "error writing %q", path)
}
return err
}
_, err = f.Write(b.Bytes())
if err1 := f.Close(); err1 != nil && err == nil {
err = err1
}
return err
}
return b, fn
}