Refuse to write a document's includes into one file by accident

- Write and WriteTo return an error for a document with includes unless the
  includes are inlined, instead of dropping the files they hold. Only
  WriteFiles collects included files and checks them for conflicts.
- ExpandVariables leaves comments as they are.
- An inlined file no longer leaves a line of its own for the include's line
  break.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 18:30:19 +00:00
co-authored by Claude Sonnet 5.5
parent ec4b27c005
commit d15c8fd3e6
3 changed files with 131 additions and 29 deletions
+7 -2
View File
@@ -11,6 +11,7 @@ package sfz
import ( import (
"errors" "errors"
"fmt"
"io" "io"
"strings" "strings"
) )
@@ -120,9 +121,13 @@ type Document struct {
problems []Problem problems []Problem
} }
// WriteTo writes the main file's text to w. An included file is a separate // WriteTo writes the main file's text to w, or returns [ErrInvalid] if the
// [File] with its own text, which stays in the document as an #include. // document has includes that were read, as the text would not hold the files
// they read. Use [Document.Write] or [Document.WriteFiles] for those.
func (d *Document) WriteTo(w io.Writer) (int64, error) { func (d *Document) WriteTo(w io.Writer) (int64, error) {
if d.hasIncludes() {
return 0, fmt.Errorf("%w: the document has includes, which need Write with InlineIncludes, or WriteFiles", ErrInvalid)
}
n, err := io.WriteString(w, d.Root.String()) n, err := io.WriteString(w, d.Root.String())
return int64(n), err return int64(n), err
} }
+41 -24
View File
@@ -41,29 +41,37 @@ type WriteOptions struct {
// forward slashes, in the folder of the main file. // forward slashes, in the folder of the main file.
type FileWriter func(path string, data []byte) error type FileWriter func(path string, data []byte) error
// Write writes the main file to w. With ExpandVariables and not // Write writes the document as one file to w. A document that has includes
// InlineIncludes, the files it includes would need the variables it no longer // that were read can be written as one file only with InlineIncludes, or else
// defines, so it is an error unless no include was read; use [Document.WriteFiles] // the files they hold would be dropped; Write returns [ErrInvalid] then. With
// then. // ExpandVariables, the included files would also need variables that the main
// file no longer defines, so it needs InlineIncludes as well. Use
// [Document.WriteFiles] to write the files separately.
func (d *Document) Write(w io.Writer, opts WriteOptions) error { func (d *Document) Write(w io.Writer, opts WriteOptions) error {
if d.hasIncludes() && !opts.InlineIncludes {
return fmt.Errorf("%w: the document has includes, which need InlineIncludes, or WriteFiles", ErrInvalid)
}
r := &renderer{opts: opts, defines: defines{}, outputs: map[string]string{}} r := &renderer{opts: opts, defines: defines{}, outputs: map[string]string{}}
text := r.file(d.Root) _, err := io.WriteString(w, r.lineEndings(r.file(d.Root)))
if r.err != nil {
return r.err
}
if opts.ExpandVariables && !opts.InlineIncludes && len(r.outputs) > 0 {
return fmt.Errorf("%w: ExpandVariables needs InlineIncludes, or WriteFiles, when includes were read", ErrInvalid)
}
_, err := io.WriteString(w, r.lineEndings(text))
return err return err
} }
// hasIncludes reports whether the document read any include.
func (d *Document) hasIncludes() bool {
for _, n := range d.Root.Nodes {
if n.Kind == KindInclude && n.File != nil {
return true
}
}
return false
}
// WriteFiles writes the main file with the path root, and each file it // WriteFiles writes the main file with the path root, and each file it
// includes at its own path, in the folder of root, using fw. It writes nothing // includes at its own path, in the folder of root, using fw. It writes nothing
// and returns [ErrInvalid] if an include's path is absolute or leaves the // and returns [ErrInvalid] if an include's path is absolute or leaves the
// folder. // folder.
func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) error { func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) error {
r := &renderer{opts: opts, defines: defines{}, outputs: map[string]string{}} r := &renderer{opts: opts, defines: defines{}, outputs: map[string]string{}, collect: true}
text := r.file(d.Root) text := r.file(d.Root)
if r.err != nil { if r.err != nil {
return r.err return r.err
@@ -94,6 +102,9 @@ func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) err
type renderer struct { type renderer struct {
opts WriteOptions opts WriteOptions
defines defines defines defines
// collect is whether the included files that stand apart are kept in
// outputs, as WriteFiles writes them.
collect bool
// outputs are the included files that stand apart, by path. // outputs are the included files that stand apart, by path.
outputs map[string]string outputs map[string]string
err error err error
@@ -113,8 +124,15 @@ func (r *renderer) file(f *File) string {
// dropBreak is whether the next line break is cut, as the directive it // dropBreak is whether the next line break is cut, as the directive it
// followed is. // followed is.
dropBreak := false dropBreak := false
// gap is whether an inlined file ended without whitespace, so that what
// follows needs some.
gap := false
for _, n := range f.Nodes { for _, n := range f.Nodes {
raw := n.Raw raw := n.Raw
if gap && raw != "" && !isSpace(raw[0]) {
b.WriteByte(' ')
}
gap = false
switch n.Kind { switch n.Kind {
case KindDefine: case KindDefine:
if r.opts.ExpandVariables { if r.opts.ExpandVariables {
@@ -126,13 +144,19 @@ func (r *renderer) file(f *File) string {
dropBreak = false dropBreak = false
if r.opts.InlineIncludes && n.File != nil { if r.opts.InlineIncludes && n.File != nil {
inner := r.file(n.File) inner := r.file(n.File)
b.WriteString(spaced(b.String(), inner)) if s := b.String(); s != "" && !isSpace(s[len(s)-1]) && inner != "" && !isSpace(inner[0]) {
b.WriteByte(' ')
}
b.WriteString(inner)
// The include's own line break would leave an empty line.
dropBreak = strings.HasSuffix(inner, "\n")
gap = inner != "" && !isSpace(inner[len(inner)-1])
continue continue
} }
if r.opts.ExpandVariables { if r.opts.ExpandVariables {
raw = `#include "` + n.Resolved + `"` raw = `#include "` + n.Resolved + `"`
} }
if n.File != nil { if n.File != nil && r.collect {
r.output(n, r.file(n.File)) r.output(n, r.file(n.File))
} }
case KindSpace: case KindSpace:
@@ -140,6 +164,8 @@ func (r *renderer) file(f *File) string {
raw = strings.TrimPrefix(strings.TrimPrefix(raw, "\r"), "\n") raw = strings.TrimPrefix(strings.TrimPrefix(raw, "\r"), "\n")
} }
dropBreak = false dropBreak = false
case KindComment:
dropBreak = false
default: default:
dropBreak = false dropBreak = false
if r.opts.ExpandVariables { if r.opts.ExpandVariables {
@@ -151,15 +177,6 @@ func (r *renderer) file(f *File) string {
return b.String() return b.String()
} }
// spaced returns the text of an included file, with a space on each side that
// would otherwise join it to the text around it.
func spaced(before, inner string) string {
if before != "" && !isSpace(before[len(before)-1]) && inner != "" && !isSpace(inner[0]) {
inner = " " + inner
}
return inner + " "
}
// output keeps the text of an included file, and reports a file that comes out // output keeps the text of an included file, and reports a file that comes out
// differently each time it is included. // differently each time it is included.
func (r *renderer) output(n *Node, text string) { func (r *renderer) output(n *Node, text string) {
+83 -3
View File
@@ -1,6 +1,7 @@
package sfz package sfz
import ( import (
"errors"
"strings" "strings"
"testing" "testing"
) )
@@ -22,15 +23,70 @@ const writeMain = "#define $S kick\n#include \"x.sfz\"\n#define $S snare\n<regio
func TestWriteZeroValue(t *testing.T) { func TestWriteZeroValue(t *testing.T) {
doc := mustParse(t, writeMain, writeFiles) doc := mustParse(t, writeMain, writeFiles)
if got := write(t, doc, WriteOptions{}); got != writeMain { // Written to files, each file is as it was read.
out := map[string]string{}
err := doc.WriteFiles("m.sfz", func(p string, d []byte) error { out[p] = string(d); return nil }, WriteOptions{})
if err != nil || out["m.sfz"] != writeMain || out["x.sfz"] != writeFiles["x.sfz"] || len(out) != 2 {
t.Errorf("err %v, files %q", err, out)
}
// As one file, the include would be dropped.
var b strings.Builder
if err := doc.Write(&b, WriteOptions{}); !errors.Is(err, ErrInvalid) || b.Len() != 0 {
t.Errorf("Write: %v %q", err, b.String())
}
if n, err := doc.WriteTo(&b); !errors.Is(err, ErrInvalid) || n != 0 || b.Len() != 0 {
t.Errorf("WriteTo: %v %q", err, b.String())
}
// A document without includes is written as it was read.
plain := mustParse(t, "#define $A 1\n<region> sample=$A.wav\n", nil)
if got := write(t, plain, WriteOptions{}); got != plain.String() {
t.Errorf("got %q", got) t.Errorf("got %q", got)
} }
} }
// TestWriteEditedInclude checks that an edit to an included file isn't lost.
func TestWriteEditedInclude(t *testing.T) {
doc := mustParse(t, writeMain, writeFiles)
set(t, headerIn(t, doc, "x.sfz"), "lokey", "5")
out := map[string]string{}
if err := doc.WriteFiles("m.sfz", func(p string, d []byte) error { out[p] = string(d); return nil }, WriteOptions{}); err != nil {
t.Fatal(err)
}
if got, want := out["x.sfz"], "// kit\n<region> sample=$S.wav lokey=5\n"; got != want {
t.Errorf("x.sfz %q, want %q", got, want)
}
if got := write(t, doc, WriteOptions{InlineIncludes: true}); !strings.Contains(got, "lokey=5") {
t.Errorf("inlined %q", got)
}
}
// TestIncludedTwiceEdited checks that a file included twice and edited in one
// place conflicts when written to files, but is fine inlined.
func TestIncludedTwiceEdited(t *testing.T) {
doc := mustParse(t, "#include \"x.sfz\"\n#include \"x.sfz\"\n", writeFiles)
set(t, doc.Headers()[0], "lokey", "5")
err := doc.WriteFiles("m.sfz", func(string, []byte) error { return nil }, WriteOptions{})
if !errors.Is(err, ErrInvalid) {
t.Errorf("WriteFiles: %v", err)
}
got := write(t, doc, WriteOptions{InlineIncludes: true})
if strings.Count(got, "<region>") != 2 || strings.Count(got, "lokey=5") != 1 {
t.Errorf("inlined %q", got)
}
}
func TestExpandVariablesKeepsComments(t *testing.T) {
doc := mustParse(t, "#define $A 1\n// uses $A\n/* $A */<region> sample=$A.wav // $A\n", nil)
want := "// uses $A\n/* $A */<region> sample=1.wav // $A\n"
if got := write(t, doc, WriteOptions{ExpandVariables: true}); got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestInlineIncludes(t *testing.T) { func TestInlineIncludes(t *testing.T) {
doc := mustParse(t, writeMain, writeFiles) doc := mustParse(t, writeMain, writeFiles)
got := write(t, doc, WriteOptions{InlineIncludes: true}) got := write(t, doc, WriteOptions{InlineIncludes: true})
want := "#define $S kick\n// kit\n<region> sample=$S.wav\n \n#define $S snare\n<region> sample=$S.wav\n" want := "#define $S kick\n// kit\n<region> sample=$S.wav\n#define $S snare\n<region> sample=$S.wav\n"
if got != want { if got != want {
t.Errorf("got %q want %q", got, want) t.Errorf("got %q want %q", got, want)
} }
@@ -44,7 +100,7 @@ func TestInlineIncludes(t *testing.T) {
func TestExpandVariables(t *testing.T) { func TestExpandVariables(t *testing.T) {
doc := mustParse(t, writeMain, writeFiles) doc := mustParse(t, writeMain, writeFiles)
got := write(t, doc, WriteOptions{InlineIncludes: true, ExpandVariables: true}) got := write(t, doc, WriteOptions{InlineIncludes: true, ExpandVariables: true})
want := "// kit\n<region> sample=kick.wav\n \n<region> sample=snare.wav\n" want := "// kit\n<region> sample=kick.wav\n<region> sample=snare.wav\n"
if got != want { if got != want {
t.Errorf("got %q want %q", got, want) t.Errorf("got %q want %q", got, want)
} }
@@ -83,3 +139,27 @@ func TestLineEndings(t *testing.T) {
t.Errorf("kept %q", got) t.Errorf("kept %q", got)
} }
} }
// TestInlineKeepsSeparation checks that an inlined file doesn't run into the
// text around it.
func TestInlineKeepsSeparation(t *testing.T) {
m := map[string]string{"x": "a=1", "y": "<region> b=2\n"}
doc := mustParse(t, "<group>c=0 #include \"x\"<region>#include \"x\"d=4 #include \"y\"\ne=5\n", m)
got := write(t, doc, WriteOptions{InlineIncludes: true})
flat := mustParse(t, got, nil).Flatten()
if len(flat.Regions) != 2 || flat.Regions[0].Opcodes["a"] != "1" || flat.Regions[0].Opcodes["d"] != "4" || flat.Regions[1].Opcodes["b"] != "2" {
t.Errorf("%q reads as %+v", got, flat.Regions)
}
}
// headerIn returns the first header of the file with the path.
func headerIn(t *testing.T, doc *Document, path string) *Header {
t.Helper()
for _, h := range doc.Headers() {
if h.File.Path == path {
return h
}
}
t.Fatalf("no header in %s", path)
return nil
}