From d15c8fd3e612106e769bbb83b19536a1838e430b Mon Sep 17 00:00:00 2001 From: Aneurin Barker Snook Date: Tue, 1 Dec 2026 18:30:19 +0000 Subject: [PATCH] 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 --- document.go | 9 ++++-- write.go | 65 ++++++++++++++++++++++++-------------- write_test.go | 86 +++++++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 131 insertions(+), 29 deletions(-) diff --git a/document.go b/document.go index 5c10aba..b20adb2 100644 --- a/document.go +++ b/document.go @@ -11,6 +11,7 @@ package sfz import ( "errors" + "fmt" "io" "strings" ) @@ -120,9 +121,13 @@ type Document struct { problems []Problem } -// WriteTo writes the main file's text to w. An included file is a separate -// [File] with its own text, which stays in the document as an #include. +// WriteTo writes the main file's text to w, or returns [ErrInvalid] if the +// 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) { + 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()) return int64(n), err } diff --git a/write.go b/write.go index 9962cda..a0488ae 100644 --- a/write.go +++ b/write.go @@ -41,29 +41,37 @@ type WriteOptions struct { // forward slashes, in the folder of the main file. type FileWriter func(path string, data []byte) error -// Write writes the main file to w. With ExpandVariables and not -// InlineIncludes, the files it includes would need the variables it no longer -// defines, so it is an error unless no include was read; use [Document.WriteFiles] -// then. +// Write writes the document as one file to w. A document that has includes +// that were read can be written as one file only with InlineIncludes, or else +// the files they hold would be dropped; Write returns [ErrInvalid] then. With +// 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 { + 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{}} - text := 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)) + _, err := io.WriteString(w, r.lineEndings(r.file(d.Root))) 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 // 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 // folder. 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) if r.err != nil { return r.err @@ -94,6 +102,9 @@ func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) err type renderer struct { opts WriteOptions 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 map[string]string 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 // followed is. dropBreak := false + // gap is whether an inlined file ended without whitespace, so that what + // follows needs some. + gap := false for _, n := range f.Nodes { raw := n.Raw + if gap && raw != "" && !isSpace(raw[0]) { + b.WriteByte(' ') + } + gap = false switch n.Kind { case KindDefine: if r.opts.ExpandVariables { @@ -126,13 +144,19 @@ func (r *renderer) file(f *File) string { dropBreak = false if r.opts.InlineIncludes && n.File != nil { 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 } if r.opts.ExpandVariables { raw = `#include "` + n.Resolved + `"` } - if n.File != nil { + if n.File != nil && r.collect { r.output(n, r.file(n.File)) } case KindSpace: @@ -140,6 +164,8 @@ func (r *renderer) file(f *File) string { raw = strings.TrimPrefix(strings.TrimPrefix(raw, "\r"), "\n") } dropBreak = false + case KindComment: + dropBreak = false default: dropBreak = false if r.opts.ExpandVariables { @@ -151,15 +177,6 @@ func (r *renderer) file(f *File) 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 // differently each time it is included. func (r *renderer) output(n *Node, text string) { diff --git a/write_test.go b/write_test.go index 1cf199d..d60d746 100644 --- a/write_test.go +++ b/write_test.go @@ -1,6 +1,7 @@ package sfz import ( + "errors" "strings" "testing" ) @@ -22,15 +23,70 @@ const writeMain = "#define $S kick\n#include \"x.sfz\"\n#define $S snare\n sample=$A.wav\n", nil) + if got := write(t, plain, WriteOptions{}); got != plain.String() { 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 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, "") != 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 */ sample=$A.wav // $A\n", nil) + want := "// uses $A\n/* $A */ 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) { doc := mustParse(t, writeMain, writeFiles) got := write(t, doc, WriteOptions{InlineIncludes: true}) - want := "#define $S kick\n// kit\n sample=$S.wav\n \n#define $S snare\n sample=$S.wav\n" + want := "#define $S kick\n// kit\n sample=$S.wav\n#define $S snare\n sample=$S.wav\n" if got != want { t.Errorf("got %q want %q", got, want) } @@ -44,7 +100,7 @@ func TestInlineIncludes(t *testing.T) { func TestExpandVariables(t *testing.T) { doc := mustParse(t, writeMain, writeFiles) got := write(t, doc, WriteOptions{InlineIncludes: true, ExpandVariables: true}) - want := "// kit\n sample=kick.wav\n \n sample=snare.wav\n" + want := "// kit\n sample=kick.wav\n sample=snare.wav\n" if got != want { t.Errorf("got %q want %q", got, want) } @@ -83,3 +139,27 @@ func TestLineEndings(t *testing.T) { 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": " b=2\n"} + doc := mustParse(t, "c=0 #include \"x\"#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 +}