internal/cuetxtar: add WriteFile method

WriteFile formats and writes a single CUE file. The idea is that
eventually it will put this into a separate entry in the archive,
perhaps collated after the original file (if any).

By introducing this API we can at least already enforce consistency
and figure out if this API works, and then move all users over
to the new format at once.

Change-Id: I50b1aa8a5b14b0df4257bf3f6cf7003d2b1ee6c3
Reviewed-on: https://cue-review.googlesource.com/c/cue/+/6643
Reviewed-by: Marcel van Lohuizen <mpvl@golang.org>
diff --git a/internal/cuetxtar/txtar.go b/internal/cuetxtar/txtar.go
index b24f43a..e2b8a07 100644
--- a/internal/cuetxtar/txtar.go
+++ b/internal/cuetxtar/txtar.go
@@ -17,6 +17,7 @@
 import (
 	"bufio"
 	"bytes"
+	"fmt"
 	"io/ioutil"
 	"os"
 	"path"
@@ -24,8 +25,10 @@
 	"strings"
 	"testing"
 
+	"cuelang.org/go/cue/ast"
 	"cuelang.org/go/cue/build"
 	"cuelang.org/go/cue/errors"
+	"cuelang.org/go/cue/format"
 	"cuelang.org/go/cue/load"
 	"github.com/google/go-cmp/cmp"
 	"github.com/rogpeppe/go-internal/txtar"
@@ -132,6 +135,22 @@
 	}
 }
 
+// Write file in a directory.
+func (t *Test) WriteFile(f *ast.File) {
+	fmt.Fprintln(t, "==", filepath.Base(f.Filename))
+	t.Write(formatNode(t.T, f))
+}
+
+func formatNode(t *testing.T, n ast.Node) []byte {
+	t.Helper()
+
+	b, err := format.Node(n)
+	if err != nil {
+		t.Fatal(err)
+	}
+	return b
+}
+
 // ValidInstances returns the valid instances for this .txtar file or skips the
 // test if there is an error loading the instances.
 func (t *Test) ValidInstances(args ...string) []*build.Instance {