Skip to content

Commit 4954491

Browse files
committed
cue/format: simplify Node API
Change-Id: Idc5b0c12128d22c71aa977c660e48d4eda5b3481 Reviewed-on: https://cue-review.googlesource.com/c/cue/+/2362 Reviewed-by: Marcel van Lohuizen <[email protected]>
1 parent d87f9d4 commit 4954491

File tree

9 files changed

+47
-61
lines changed

9 files changed

+47
-61
lines changed

cmd/cue/cmd/eval.go

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,12 +122,14 @@ func runEval(cmd *cobra.Command, args []string) error {
122122
continue
123123
}
124124
}
125-
format.Node(w, getSyntax(v, syn), opts...)
125+
b, _ := format.Node(getSyntax(v, syn), opts...)
126+
w.Write(b)
126127
}
127128
for _, e := range exprs {
128129
if len(exprs) > 1 {
129130
fmt.Fprint(w, "// ")
130-
format.Node(w, e)
131+
b, _ := format.Node(e)
132+
w.Write(b)
131133
fmt.Fprintln(w)
132134
}
133135
v := inst.Eval(e)
@@ -137,7 +139,8 @@ func runEval(cmd *cobra.Command, args []string) error {
137139
continue
138140
}
139141
}
140-
format.Node(w, getSyntax(v, syn), opts...)
142+
b, _ := format.Node(getSyntax(v, syn), opts...)
143+
w.Write(b)
141144
fmt.Fprintln(w)
142145
}
143146
}

cmd/cue/cmd/import.go

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
package cmd
1616

1717
import (
18-
"bytes"
1918
"encoding/json"
2019
"fmt"
2120
"io"
@@ -355,12 +354,12 @@ func handleFile(cmd *cobra.Command, pkg, filename string) (err error) {
355354
func processFile(cmd *cobra.Command, file *ast.File) (err error) {
356355
name := file.Filename + ".cue"
357356

358-
buf := &bytes.Buffer{}
359-
if err := format.Node(buf, file); err != nil {
357+
b, err := format.Node(file)
358+
if err != nil {
360359
return err
361360
}
362361

363-
return ioutil.WriteFile(name, buf.Bytes(), 0644)
362+
return ioutil.WriteFile(name, b, 0644)
364363
}
365364

366365
func processStream(cmd *cobra.Command, pkg, filename string, objs []ast.Expr) error {
@@ -516,17 +515,16 @@ func combineExpressions(cmd *cobra.Command, pkg, cueFile string, objs ...ast.Exp
516515
}
517516
}
518517

519-
var buf bytes.Buffer
520-
err := format.Node(&buf, f, format.Simplify())
518+
b, err := format.Node(f, format.Simplify())
521519
if err != nil {
522520
return fmt.Errorf("error formatting file: %v", err)
523521
}
524522

525523
if cueFile == "-" {
526-
_, err := io.Copy(cmd.OutOrStdout(), &buf)
524+
_, err := cmd.OutOrStdout().Write(b)
527525
return err
528526
}
529-
return ioutil.WriteFile(cueFile, buf.Bytes(), 0644)
527+
return ioutil.WriteFile(cueFile, b, 0644)
530528
}
531529

532530
type listIndex struct {

cmd/cue/cmd/trim.go

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ package cmd
1717
import (
1818
"bytes"
1919
"fmt"
20-
"io"
2120
"io/ioutil"
2221
"os"
2322
"strconv"
@@ -143,14 +142,13 @@ func runTrim(cmd *cobra.Command, args []string) error {
143142
opts = append(opts, format.Simplify())
144143
}
145144

146-
var buf bytes.Buffer
147-
err := format.Node(&buf, f, opts...)
145+
b, err := format.Node(f, opts...)
148146
if err != nil {
149147
return fmt.Errorf("error formatting file: %v", err)
150148
}
151149

152150
if dst == "-" {
153-
_, err := io.Copy(cmd.OutOrStdout(), &buf)
151+
_, err := cmd.OutOrStdout().Write(b)
154152
if err != nil {
155153
return err
156154
}
@@ -159,7 +157,7 @@ func runTrim(cmd *cobra.Command, args []string) error {
159157
filename = dst
160158
}
161159

162-
err = ioutil.WriteFile(filename, buf.Bytes(), 0644)
160+
err = ioutil.WriteFile(filename, b, 0644)
163161
if err != nil {
164162
return err
165163
}

cue/export_test.go

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
package cue
1616

1717
import (
18-
"bytes"
1918
"fmt"
2019
"log"
2120
"strings"
@@ -321,13 +320,12 @@ func TestExport(t *testing.T) {
321320
n := root.(*structLit).arcs[0].v
322321
v := newValueRoot(ctx, n)
323322

324-
buf := &bytes.Buffer{}
325323
opts := options{raw: !tc.eval}
326-
err := format.Node(buf, export(ctx, v.eval(ctx), opts), format.Simplify())
324+
b, err := format.Node(export(ctx, v.eval(ctx), opts), format.Simplify())
327325
if err != nil {
328326
log.Fatal(err)
329327
}
330-
if got := buf.String(); got != tc.out {
328+
if got := string(b); got != tc.out {
331329
t.Errorf("\ngot %v;\nwant %v", got, tc.out)
332330
}
333331
})
@@ -374,13 +372,12 @@ func TestExportFile(t *testing.T) {
374372
v := inst.Value()
375373
ctx := r.index().newContext()
376374

377-
buf := &bytes.Buffer{}
378375
opts := options{raw: false}
379-
err = format.Node(buf, export(ctx, v.eval(ctx), opts), format.Simplify())
376+
b, err := format.Node(export(ctx, v.eval(ctx), opts), format.Simplify())
380377
if err != nil {
381378
log.Fatal(err)
382379
}
383-
if got := strings.TrimSpace(buf.String()); got != tc.out {
380+
if got := strings.TrimSpace(string(b)); got != tc.out {
384381
t.Errorf("\ngot:\n%v\nwant:\n%v", got, tc.out)
385382
}
386383
})

cue/format/format.go

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ package format // import "cuelang.org/go/cue/format"
1818
import (
1919
"bytes"
2020
"fmt"
21-
"io"
2221
"strings"
2322
"text/tabwriter"
2423

@@ -70,9 +69,9 @@ func TabIndent(indent bool) Option {
7069
// The function may return early (before the entire result is written) and
7170
// return a formatting error, for instance due to an incorrect AST.
7271
//
73-
func Node(dst io.Writer, node ast.Node, opt ...Option) error {
72+
func Node(node ast.Node, opt ...Option) ([]byte, error) {
7473
cfg := newConfig(opt)
75-
return cfg.fprint(dst, node)
74+
return cfg.fprint(node)
7675
}
7776

7877
// Source formats src in canonical cue fmt style and returns the result or an
@@ -97,11 +96,7 @@ func Source(b []byte, opt ...Option) ([]byte, error) {
9796
}
9897

9998
// print AST
100-
var buf bytes.Buffer
101-
if err := cfg.fprint(&buf, f); err != nil {
102-
return nil, fmt.Errorf("print: %s", err)
103-
}
104-
return buf.Bytes(), nil
99+
return cfg.fprint(f)
105100
}
106101

107102
type config struct {
@@ -126,11 +121,11 @@ func newConfig(opt []Option) *config {
126121
}
127122

128123
// Config defines the output of Fprint.
129-
func (cfg *config) fprint(output io.Writer, node interface{}) (err error) {
124+
func (cfg *config) fprint(node interface{}) (out []byte, err error) {
130125
var p printer
131126
p.init(cfg)
132127
if err = printNode(node, &p); err != nil {
133-
return err
128+
return p.output, err
134129
}
135130

136131
padchar := byte('\t')
@@ -153,15 +148,14 @@ func (cfg *config) fprint(output io.Writer, node interface{}) (err error) {
153148

154149
err = tw.Flush()
155150
if err != nil {
156-
return err
151+
return buf.Bytes(), err
157152
}
158153

159154
b := buf.Bytes()
160155
if !cfg.TabIndent {
161156
b = bytes.ReplaceAll(b, []byte{'\t'}, bytes.Repeat([]byte{' '}, cfg.Tabwidth))
162157
}
163-
_, err = output.Write(b)
164-
return err
158+
return b, nil
165159
}
166160

167161
// A formatter walks a syntax.Node, interspersed with comments and spacing

cue/format/format_test.go

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -209,13 +209,13 @@ func TestFiles(t *testing.T) {
209209
// Verify that the printer can be invoked during initialization.
210210
func init() {
211211
const name = "foobar"
212-
var buf bytes.Buffer
213-
if err := Fprint(&buf, &ast.Ident{Name: name}); err != nil {
212+
b, err := Fprint(&ast.Ident{Name: name})
213+
if err != nil {
214214
panic(err) // error in test
215215
}
216216
// in debug mode, the result contains additional information;
217217
// ignore it
218-
if s := buf.String(); !debug && s != name {
218+
if s := string(b); !debug && s != name {
219219
panic("got " + s + ", want " + name)
220220
}
221221
}
@@ -228,10 +228,9 @@ func TestBadNodes(t *testing.T) {
228228
if err == nil {
229229
t.Error("expected illegal program") // error in test
230230
}
231-
var buf bytes.Buffer
232-
Fprint(&buf, f)
233-
if buf.String() != res {
234-
t.Errorf("got %q, expected %q", buf.String(), res)
231+
b, _ := Fprint(f)
232+
if string(b) != res {
233+
t.Errorf("got %q, expected %q", string(b), res)
235234
}
236235
}
237236
func TestPackage(t *testing.T) {
@@ -246,13 +245,12 @@ func TestPackage(t *testing.T) {
246245
},
247246
},
248247
}
249-
var buf bytes.Buffer
250-
err := Node(&buf, f)
248+
b, err := Node(f)
251249
if err != nil {
252250
t.Fatal(err)
253251
}
254252
const want = "package foo\n\n1\n"
255-
if got := buf.String(); got != want {
253+
if got := string(b); got != want {
256254
t.Errorf("got %q, expected %q", got, want)
257255
}
258256
}
@@ -316,18 +314,16 @@ e2: c*t.z
316314
}
317315

318316
// pretty-print original
319-
var buf bytes.Buffer
320-
err = (&config{UseSpaces: true, Tabwidth: 8}).fprint(&buf, f1)
317+
b, err := (&config{UseSpaces: true, Tabwidth: 8}).fprint(f1)
321318
if err != nil {
322319
t.Fatal(err)
323320
}
324321

325322
// parse pretty printed original
326323
// (//line comments must be interpreted even w/o syntax.ParseComments set)
327-
f2, err := parser.ParseFile("", buf.Bytes(),
328-
parser.AllErrors, parser.ParseComments)
324+
f2, err := parser.ParseFile("", b, parser.AllErrors, parser.ParseComments)
329325
if err != nil {
330-
t.Fatalf("%s\n%s", err, buf.Bytes())
326+
t.Fatalf("%s\n%s", err, b)
331327
}
332328

333329
// At this point the position information of identifiers in f2 should
@@ -363,7 +359,7 @@ e2: c*t.z
363359
}
364360

365361
if t.Failed() {
366-
t.Logf("\n%s", buf.Bytes())
362+
t.Logf("\n%s", b)
367363
}
368364
}
369365

@@ -379,13 +375,12 @@ func TestDeclLists(t *testing.T) {
379375
panic(err) // error in test
380376
}
381377

382-
var buf bytes.Buffer
383-
err = Fprint(&buf, file.Decls) // only print declarations
378+
b, err := Fprint(file.Decls) // only print declarations
384379
if err != nil {
385380
panic(err) // error in test
386381
}
387382

388-
out := buf.String()
383+
out := string(b)
389384

390385
if out != src {
391386
t.Errorf("\ngot : %q\nwant: %q\n", out, src)

encoding/protobuf/examples_test.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
package protobuf_test
1616

1717
import (
18+
"fmt"
1819
"log"
1920
"os"
2021
"path/filepath"
@@ -37,7 +38,8 @@ func ExampleParse() {
3738
log.Fatal(err, "")
3839
}
3940

40-
format.Node(os.Stdout, f)
41+
b, _ := format.Node(f)
42+
fmt.Println(string(b))
4143

4244
// Output:
4345
// // Package basic is just that: basic.

encoding/protobuf/protobuf_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,8 @@ func TestParseDefinitions(t *testing.T) {
4646
if f, err := Parse(filename, nil, c); err != nil {
4747
fmt.Fprintln(out, err)
4848
} else {
49-
format.Node(out, f, format.Simplify())
49+
b, _ := format.Node(f, format.Simplify())
50+
out.Write(b)
5051
}
5152

5253
wantFile := filepath.Join("testdata", filepath.Base(file)+".out.cue")

internal/third_party/yaml/decode_test.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package yaml_test
22

33
import (
4-
"bytes"
54
"errors"
65
"flag"
76
"fmt"
@@ -647,9 +646,8 @@ func cueStr(node ast.Node) string {
647646
Decls: s.Elts,
648647
}
649648
}
650-
buf := bytes.Buffer{}
651-
format.Node(&buf, node)
652-
return strings.TrimSpace(buf.String())
649+
b, _ := format.Node(node)
650+
return strings.TrimSpace(string(b))
653651
}
654652

655653
func newDecoder(t *testing.T, data string) *yaml.Decoder {

0 commit comments

Comments
 (0)