Add editing, writing and building documents

Header.Get, Set and Delete edit opcodes in place and keep the text around
them. Write and WriteFiles take WriteOptions to inline includes, expand
variables and set line endings. Build makes a document from a typed
Instrument, with options to split regions into included files and to
hoist repeated values into #define directives.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 17:41:34 +00:00
co-authored by Claude Sonnet 5.5
parent d124690ecf
commit 3d2ab78a32
7 changed files with 1154 additions and 1 deletions
+8 -1
View File
@@ -25,13 +25,20 @@ The library knows every opcode and header in the format, from the data behind [s
The registry is generated: replace `internal/gen/syntax.yml` and run `go generate ./...`, then `go test -update`.
## Editing and writing
- `Document.Headers` returns the headers of every file. `Header.Get`, `Set` and `Delete` change an opcode and keep the comments and spacing around it; a new opcode goes after the header's last and is laid out like it. `Document.AddHeader` adds a header.
- `Header.Set` on an opcode that uses a variable writes the value in its place. `Document.SetDefine` changes the variable, and so each opcode that uses it.
- `Document.Write` and `WriteFiles` take `WriteOptions`: `InlineIncludes` makes one file, `ExpandVariables` replaces variables with their values, and `LineEnding` sets the line break. The zero value writes each file as it was read.
- `Build` makes a document from an `Instrument`, with `BuildOptions`: `SplitFiles` puts regions in included files, `Variables` hoists repeated values into `#define`s and the samples' folder into `default_path`, and `Indent` sets the indent. Reading the result gives the instrument back, except for opcodes the typed model doesn't hold.
## Includes
`Parse` reads includes with the resolver from `WithResolver`; `ParseFile` reads them from the folder of the main file. An include that can't be read is a `Problem` from `Validate`, and `WithIncludes(sfz.IncludesFail)` makes it an error. Includes nest at most 16 deep, and an instrument may hold 16 MB of text; `WithLimits` changes both.
## Status
The document, flattening, typed model, opcode registry and validation are in. Not yet in: editing a document, and building one from the typed model.
The document, flattening, typed model, opcode registry, validation, editing, writing and building are in.
## Licence
+429
View File
@@ -0,0 +1,429 @@
package sfz
import (
"fmt"
"math"
"path"
"sort"
"strconv"
"strings"
)
// BuildOptions change how [Build] lays out a document. The zero value makes one
// file, with the values written literally and two spaces of indent.
type BuildOptions struct {
// Indent is what an opcode's line starts with. The default is two spaces.
Indent string
// SplitFiles puts the regions into included files, RegionsPerFile at a
// time, and leaves the controls and variables in the main file.
SplitFiles bool
// RegionsPerFile is how many regions each included file holds. The default
// is 64.
RegionsPerFile int
// FileNamer returns the path of an included file, given its number from 0,
// relative to the main file's folder. The default is regions/001.sfz,
// regions/002.sfz and so on.
FileNamer func(index int) string
// Variables writes a #define for each value that more than MinRepeat
// regions share, and uses default_path for the folder that all samples are
// in.
Variables bool
// MinRepeat is how many regions must share an opcode's value to make it a
// variable. The default is 8.
MinRepeat int
}
func (o *BuildOptions) defaults() {
if o.Indent == "" {
o.Indent = " "
}
if o.RegionsPerFile <= 0 {
o.RegionsPerFile = 64
}
if o.FileNamer == nil {
o.FileNamer = func(i int) string { return fmt.Sprintf("regions/%03d.sfz", i+1) }
}
if o.MinRepeat <= 0 {
o.MinRepeat = 8
}
}
// defaultRegion is a region that sets nothing: the format's defaults.
func defaultRegion() Region {
return Region{
HighKey: 127, RootKey: defaultRootKey, LowVelocity: defaultLowVelocity, HighVelocity: 127,
KeyTrack: 100, VelocityTracking: 100, Envelope: DefaultEnvelope, Trigger: defaultTrigger,
SequenceLength: 1, SequencePosition: 1, HighRandom: 1, OffMode: defaultOffMode, OffTime: defaultOffTime,
}
}
// opcodeLine is an opcode to write.
type opcodeLine struct{ name, value string }
// num writes a number with the digits it needs to read back as it was.
func num(v float64) string { return strconv.FormatFloat(v, 'f', -1, 64) }
// scaled writes a condition's limit in the unit of its opcode, which is the
// limit times scale, rounded so that a limit that was a whole number stays
// one.
func scaled(v, scale float64) string { return num(math.Round(v*scale*1e9) / 1e9) }
// Build makes a document that describes the instrument. Reading it with
// [Document.Flatten] and [Flat.Instrument] gives the instrument back, except
// for what the model doesn't hold: unread opcodes, and which headers regions
// were under.
func Build(inst *Instrument, opts ...BuildOptions) (*Document, error) {
var o BuildOptions
if len(opts) > 0 {
o = opts[0]
}
o.defaults()
regions := make([][]opcodeLine, len(inst.Regions))
for i := range inst.Regions {
regions[i] = regionOpcodes(inst.Regions[i])
}
var control []opcodeLine
var defines []opcodeLine
if o.Variables {
prefix := samplePrefix(inst.Regions)
if prefix != "" {
control = append(control, opcodeLine{"default_path", prefix})
for i := range regions {
regions[i][0].value = strings.TrimPrefix(regions[i][0].value, prefix)
}
}
defines = hoist(regions, o.MinRepeat)
}
for _, c := range inst.Controls {
if c.Label != "" {
control = append(control, opcodeLine{fmt.Sprintf("label_cc%d", c.Controller), c.Label})
}
control = append(control, opcodeLine{fmt.Sprintf("set_hdcc%d", c.Controller), num(c.Value)})
}
var global []opcodeLine
if k := inst.Keyswitches; k != nil {
global = append(global, opcodeLine{"sw_lokey", strconv.Itoa(k.Low)}, opcodeLine{"sw_hikey", strconv.Itoa(k.High)})
if k.Default != nil {
global = append(global, opcodeLine{"sw_default", strconv.Itoa(*k.Default)})
}
}
b := &builder{indent: o.Indent}
for _, d := range defines {
b.line("#define " + d.name + " " + d.value)
}
if len(control) > 0 {
b.header("control", control)
}
b.curves(inst)
if len(global) > 0 {
b.header("global", global)
}
if !o.SplitFiles {
for _, ops := range regions {
b.header("region", ops)
}
return &Document{Root: b.file("")}, nil
}
// The main file includes a file for each run of regions.
main := b.file("")
for i := 0; i*o.RegionsPerFile < len(regions); i++ {
chunk := regions[i*o.RegionsPerFile : min(len(regions), (i+1)*o.RegionsPerFile)]
cb := &builder{indent: o.Indent}
for _, ops := range chunk {
cb.header("region", ops)
}
name := path.Clean(o.FileNamer(i))
child := cb.file(name)
main.Nodes = append(main.Nodes,
&Node{Kind: KindInclude, Raw: `#include "` + name + `"`, Value: name, Resolved: name, File: child},
&Node{Kind: KindSpace, Raw: "\n"})
}
main.reposition()
return &Document{Root: main}, nil
}
// builder writes text and lexes it into files.
type builder struct {
indent string
text strings.Builder
}
func (b *builder) line(s string) {
b.text.WriteString(s)
b.text.WriteString("\n")
}
func (b *builder) header(name string, ops []opcodeLine) {
b.line("<" + name + ">")
for _, op := range ops {
b.line(b.indent + op.name + "=" + op.value)
}
}
// file returns what the builder has written as a file with the path.
func (b *builder) file(p string) *File {
f := &File{Path: p, Nodes: lex(b.text.String())}
return f
}
// curves writes a <curve> header for each custom curve that a region's
// modulation uses.
func (b *builder) curves(inst *Instrument) {
seen := map[int]bool{}
var indexes []int
points := map[int][]CurveStop{}
for _, r := range inst.Regions {
for _, m := range r.Modulations {
if len(m.Points) > 0 && !seen[m.Curve] {
seen[m.Curve] = true
indexes = append(indexes, m.Curve)
points[m.Curve] = m.Points
}
}
}
sort.Ints(indexes)
for _, i := range indexes {
ops := []opcodeLine{{"curve_index", strconv.Itoa(i)}}
for _, p := range points[i] {
ops = append(ops, opcodeLine{fmt.Sprintf("v%03d", p.At), num(p.Value)})
}
b.header("curve", ops)
}
}
// samplePrefix returns the folder, with its slash, that every sample is in, or
// "" if there is none.
func samplePrefix(regions []Region) string {
if len(regions) == 0 {
return ""
}
prefix := path.Dir(regions[0].Sample)
for _, r := range regions {
for prefix != "." && !strings.HasPrefix(r.Sample, prefix+"/") {
prefix = path.Dir(prefix)
}
}
if prefix == "." || prefix == "/" {
return ""
}
return prefix + "/"
}
// hoist replaces values that at least min regions share with variables, and
// returns their definitions. The sample is the first opcode of a region and is
// left alone. The names end in a run of three letters, so that none is the
// start of another.
func hoist(regions [][]opcodeLine, min int) []opcodeLine {
type key struct{ name, value string }
counts := map[key]int{}
for _, ops := range regions {
seen := map[key]bool{}
for _, op := range ops[1:] {
k := key{op.name, op.value}
if !seen[k] && !strings.Contains(op.value, "$") && !strings.ContainsAny(op.value, " \t") {
seen[k] = true
counts[k]++
}
}
}
var shared []key
for k, n := range counts {
if n >= min {
shared = append(shared, k)
}
}
sort.Slice(shared, func(i, j int) bool {
if shared[i].name != shared[j].name {
return shared[i].name < shared[j].name
}
return shared[i].value < shared[j].value
})
names := map[key]string{}
var defines []opcodeLine
for i, k := range shared {
suffix := string([]byte{byte('A' + i/676%26), byte('A' + i/26%26), byte('A' + i%26)})
name := "$" + strings.ToUpper(k.name) + "_" + suffix
names[k] = name
defines = append(defines, opcodeLine{name, k.value})
}
for _, ops := range regions {
for i := 1; i < len(ops); i++ {
if name, ok := names[key{ops[i].name, ops[i].value}]; ok {
ops[i].value = name
}
}
}
return defines
}
// regionOpcodes returns the opcodes that make a region, starting with its
// sample, with those that are the format's defaults left out.
func regionOpcodes(r Region) []opcodeLine {
d := defaultRegion()
ops := []opcodeLine{{"sample", r.Sample}}
add := func(name, value string) { ops = append(ops, opcodeLine{name, value}) }
if r.LowKey != d.LowKey {
add("lokey", strconv.Itoa(r.LowKey))
}
if r.HighKey != d.HighKey {
add("hikey", strconv.Itoa(r.HighKey))
}
if r.RootFromSample {
add("pitch_keycenter", "sample")
} else if r.RootKey != d.RootKey {
add("pitch_keycenter", strconv.Itoa(r.RootKey))
}
if r.LowVelocity != d.LowVelocity {
add("lovel", strconv.Itoa(r.LowVelocity))
}
if r.HighVelocity != d.HighVelocity {
add("hivel", strconv.Itoa(r.HighVelocity))
}
if r.KeyTrack != d.KeyTrack {
add("pitch_keytrack", num(r.KeyTrack))
}
if r.Tune != 0 {
add("tune", num(r.Tune))
}
if r.Volume != 0 {
add("volume", num(r.Volume))
}
if r.Pan != 0 {
add("pan", num(r.Pan))
}
if r.Width != nil {
add("width", num(*r.Width))
}
if r.Offset != 0 {
add("offset", strconv.FormatInt(r.Offset, 10))
}
if r.VelocityTracking != d.VelocityTracking {
add("amp_veltrack", num(r.VelocityTracking))
}
for _, p := range r.VelocityCurve {
add(fmt.Sprintf("amp_velcurve_%d", p.Velocity), num(p.Gain))
}
crossfade := func(c *Crossfade, which string) {
if c == nil {
return
}
add("xfin_lo"+which, strconv.Itoa(c.FadeInLow))
add("xfin_hi"+which, strconv.Itoa(c.FadeInHigh))
add("xfout_lo"+which, strconv.Itoa(c.FadeOutLow))
add("xfout_hi"+which, strconv.Itoa(c.FadeOutHigh))
if c.Curve == CrossfadeGain {
add("xf_"+which+"curve", "gain")
}
}
crossfade(r.KeyCrossfade, "key")
crossfade(r.VelocityCrossfade, "vel")
e, de := r.Envelope, d.Envelope
for _, s := range []struct {
name string
v, d float64
}{
{"ampeg_delay", e.Delay, de.Delay}, {"ampeg_attack", e.Attack, de.Attack}, {"ampeg_hold", e.Hold, de.Hold},
{"ampeg_decay", e.Decay, de.Decay}, {"ampeg_sustain", e.Sustain, de.Sustain}, {"ampeg_release", e.Release, de.Release},
} {
if s.v != s.d {
add(s.name, num(s.v))
}
}
if r.Trigger != d.Trigger {
add("trigger", r.Trigger)
}
if r.LoopMode != "" {
add("loop_mode", r.LoopMode)
}
if r.LoopStart != nil {
add("loop_start", strconv.FormatInt(*r.LoopStart, 10))
}
if r.LoopEnd != nil {
add("loop_end", strconv.FormatInt(*r.LoopEnd, 10))
}
if r.ReleaseDecay != 0 {
add("rt_decay", num(r.ReleaseDecay))
}
if r.SequenceLength != d.SequenceLength {
add("seq_length", strconv.Itoa(r.SequenceLength))
}
if r.SequencePosition != d.SequencePosition {
add("seq_position", strconv.Itoa(r.SequencePosition))
}
if r.LowRandom != 0 {
add("lorand", num(r.LowRandom))
}
if r.HighRandom != d.HighRandom {
add("hirand", num(r.HighRandom))
}
if r.Group != 0 {
add("group", strconv.Itoa(r.Group))
}
if r.OffBy != nil {
add("off_by", strconv.Itoa(*r.OffBy))
}
if r.Polyphony != nil {
add("polyphony", strconv.Itoa(*r.Polyphony))
}
if r.NotePolyphony != nil {
add("note_polyphony", strconv.Itoa(*r.NotePolyphony))
}
if r.OffMode != d.OffMode {
add("off_mode", r.OffMode)
}
if r.OffTime != d.OffTime {
add("off_time", num(r.OffTime))
}
for _, p := range []struct {
name string
v *float64
}{{"bend_up", r.BendUp}, {"bend_down", r.BendDown}, {"bend_step", r.BendStep}} {
if p.v != nil {
add(p.name, num(*p.v))
}
}
for _, c := range r.Conditions {
scale, lo, hi := conditionOpcodes(c)
if lo == "" {
add(fmt.Sprintf("lohdcc%d", c.Controller), num(c.Low))
add(fmt.Sprintf("hihdcc%d", c.Controller), num(c.High))
continue
}
add(lo, scaled(c.Low, scale))
add(hi, scaled(c.High, scale))
}
if k := r.Keyswitch; k != nil {
for _, s := range []struct {
name string
v *int
}{{"sw_last", k.Last}, {"sw_previous", k.Previous}, {"sw_down", k.Down}, {"sw_up", k.Up}} {
if s.v != nil {
add(s.name, strconv.Itoa(*s.v))
}
}
}
for _, m := range r.Modulations {
add(fmt.Sprintf("%s_oncc%d", m.Target, m.Controller), num(m.Depth))
if m.Curve != 0 {
add(fmt.Sprintf("%s_curvecc%d", m.Target, m.Controller), strconv.Itoa(m.Curve))
}
}
return ops
}
// conditionOpcodes returns the opcodes that limit a source that isn't a
// numbered controller, and the number their values are the range's times. A
// controller has none, and is written as lohdcc and hihdcc.
func conditionOpcodes(c Condition) (scale float64, lo, hi string) {
for _, b := range controllerBounds {
if b.source == c.Source {
return b.scale, b.low, b.high
}
}
return 0, "", ""
}
+135
View File
@@ -0,0 +1,135 @@
package sfz
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"testing/fstest"
)
// instruments are typed instruments to build documents from, from the
// fixtures and from text that sets what the typed model holds.
func instruments(t *testing.T) map[string]*Instrument {
t.Helper()
doc, err := ParseFile(os.DirFS(filepath.Join("testdata", "splendid")), "Splendid Grand Piano.sfz")
if err != nil {
t.Fatal(err)
}
return map[string]*Instrument{
"splendid": doc.Flatten().Instrument(),
"everything": parseText(t, `
<control> default_path=S/ label_cc20=Mic set_hdcc20=0.25
<curve> curve_index=8 v000=0 v064=0.9 v127=1
<global> sw_lokey=36 sw_hikey=40 sw_default=37
<region> sample=a.wav lokey=c3 hikey=e3 pitch_keycenter=sample lovel=20 hivel=100 tune=12 volume=-3 pan=-30
width=50 offset=100 amp_veltrack=60 amp_velcurve_30=0.5 amp_velcurve_100=0.9
xfin_lokey=40 xfin_hikey=50 xfout_lokey=60 xfout_hikey=70 xf_keycurve=gain
xfin_lovel=1 xfin_hivel=10
ampeg_attack=0.1 ampeg_decay=0.2 ampeg_sustain=70 ampeg_release=1.5 ampeg_hold=0.05 ampeg_delay=0.01
trigger=release rt_decay=3 loop_mode=loop_sustain loop_start=10 loop_end=2000
seq_length=4 seq_position=2 lorand=0.25 hirand=0.5 group=3 off_by=4 polyphony=2 note_polyphony=1
off_mode=time off_time=0.5 bend_up=200 bend_down=-200 bend_step=10
locc20=10 hicc20=100 lochan=2 hichan=5 lobend=-4096 hibend=4096 lochanaft=10 hichanaft=100
sw_last=37 sw_previous=36 sw_down=38 sw_up=39
volume_oncc7=-6 volume_curvecc7=8 pan_oncc10=40 tune_oncc1=100 amplitude_oncc11=50 width_oncc2=5
<region> sample=b.wav key=60
`),
}
}
func TestBuildRoundTrip(t *testing.T) {
for name, inst := range instruments(t) {
for label, opts := range map[string]BuildOptions{
"plain": {},
"variables": {Variables: true, MinRepeat: 2},
"split": {SplitFiles: true, RegionsPerFile: 7},
"both": {SplitFiles: true, Variables: true, RegionsPerFile: 50, Indent: "\t"},
} {
doc, err := Build(inst, opts)
if err != nil {
t.Fatal(err)
}
got := rebuilt(t, doc)
if !reflect.DeepEqual(got.Regions, inst.Regions) {
for i := range inst.Regions {
if i < len(got.Regions) && !reflect.DeepEqual(got.Regions[i], inst.Regions[i]) {
t.Fatalf("%s/%s: region %d\n got %+v\nwant %+v", name, label, i, got.Regions[i], inst.Regions[i])
}
}
t.Fatalf("%s/%s: %d regions, want %d", name, label, len(got.Regions), len(inst.Regions))
}
if !reflect.DeepEqual(got.Controls, inst.Controls) || !reflect.DeepEqual(got.Keyswitches, inst.Keyswitches) {
t.Errorf("%s/%s: controls %+v keyswitches %+v, want %+v %+v", name, label, got.Controls, got.Keyswitches, inst.Controls, inst.Keyswitches)
}
if problems := doc.Validate(); name == "everything" && len(problems) != 0 {
t.Errorf("%s/%s: problems %+v", name, label, problems)
}
}
}
}
// rebuilt writes a document to files and reads them back.
func rebuilt(t *testing.T, doc *Document) *Instrument {
t.Helper()
files := fstest.MapFS{}
err := doc.WriteFiles("out.sfz", func(p string, data []byte) error {
files[p] = &fstest.MapFile{Data: data}
return nil
}, WriteOptions{})
if err != nil {
t.Fatal(err)
}
back, err := ParseFile(files, "out.sfz")
if err != nil {
t.Fatal(err)
}
if len(back.Files()) != len(doc.Files()) {
t.Errorf("%d files, want %d", len(back.Files()), len(doc.Files()))
}
return back.Flatten().Instrument()
}
func TestBuildLayout(t *testing.T) {
inst := parseText(t, "<region> sample=Dir/a.wav lokey=40\n<region> sample=Dir/b.wav lokey=40\n<region> sample=Dir/c.wav lokey=41\n")
doc, err := Build(inst)
if err != nil {
t.Fatal(err)
}
want := "<region>\n sample=Dir/a.wav\n lokey=40\n<region>\n sample=Dir/b.wav\n lokey=40\n<region>\n sample=Dir/c.wav\n lokey=41\n"
if got := doc.String(); got != want {
t.Errorf("got\n%s\nwant\n%s", got, want)
}
doc, err = Build(inst, BuildOptions{Variables: true, MinRepeat: 2})
if err != nil {
t.Fatal(err)
}
if got := doc.String(); !strings.HasPrefix(got, "#define $LOKEY_AAA 40\n<control>\n default_path=Dir/\n") ||
strings.Count(got, "lokey=$LOKEY_AAA") != 2 || !strings.Contains(got, "sample=a.wav") {
t.Errorf("variables:\n%s", got)
}
doc, err = Build(inst, BuildOptions{SplitFiles: true, RegionsPerFile: 2, FileNamer: func(i int) string { return "part" + string(rune('a'+i)) + ".sfz" }})
if err != nil {
t.Fatal(err)
}
if got := doc.String(); got != "#include \"parta.sfz\"\n#include \"partb.sfz\"\n" || len(doc.Files()) != 3 {
t.Errorf("split:\n%s", got)
}
}
func TestWriteFilesPaths(t *testing.T) {
doc, err := Build(parseText(t, "<region> sample=a.wav\n"), BuildOptions{SplitFiles: true})
if err != nil {
t.Fatal(err)
}
var paths []string
if err := doc.WriteFiles("Piano/main.sfz", func(p string, _ []byte) error { paths = append(paths, p); return nil }, WriteOptions{}); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(paths, []string{"Piano/main.sfz", "Piano/regions/001.sfz"}) {
t.Errorf("paths %q", paths)
}
}
+230
View File
@@ -0,0 +1,230 @@
package sfz
import "strings"
// Header is a header of a file, with the opcodes that follow it up to the
// next header in the same file. Opcodes that an #include after it brings in
// belong to the included file's own headers.
type Header struct {
// File is the file the header is in.
File *File
// Node is the header's own node.
Node *Node
}
// Name returns the header's name without brackets, as written.
func (h *Header) Name() string { return h.Node.Name }
// index returns where the header's node is in its file.
func (h *Header) index() int {
for i, n := range h.File.Nodes {
if n == h.Node {
return i
}
}
return -1
}
// span returns the range of the file's nodes after the header's own, up to the
// next header.
func (h *Header) span() (start, end int) {
start = h.index() + 1
end = start
for end < len(h.File.Nodes) && h.File.Nodes[end].Kind != KindHeader {
end++
}
return start, end
}
// Opcodes returns the header's opcode nodes, in order.
func (h *Header) Opcodes() []*Node {
start, end := h.span()
var out []*Node
for _, n := range h.File.Nodes[start:end] {
if n.Kind == KindOpcode {
out = append(out, n)
}
}
return out
}
// Get returns the header's last node for an opcode, which is the one that
// takes effect.
func (h *Header) Get(name string) (*Node, bool) {
ops := h.Opcodes()
for i := len(ops) - 1; i >= 0; i-- {
if ops[i].Name == name {
return ops[i], true
}
}
return nil, false
}
// Set gives the opcode a value. An opcode the header already has keeps its
// place and the text around it, and takes the value as written even if it was a
// variable. A new one goes after the header's last opcode, laid out as that
// one is.
func (h *Header) Set(name, value string) {
if n, ok := h.Get(name); ok {
n.Raw = name + "=" + value
n.Value = strings.TrimSpace(value)
h.File.reposition()
return
}
start, end := h.span()
at := start
sep := ""
for i := start; i < end; i++ {
if h.File.Nodes[i].Kind == KindOpcode {
at = i + 1
}
}
if at == start {
// With no opcode to follow, the new one goes after the header, on its
// own line if the header is.
sep = " "
if start < len(h.File.Nodes) && h.File.Nodes[start].Kind == KindSpace && strings.Contains(h.File.Nodes[start].Raw, "\n") {
sep = h.File.Nodes[start].Raw
} else if start >= len(h.File.Nodes) {
sep = "\n"
}
} else {
sep = " "
if i := at - 2; i >= start && h.File.Nodes[i].Kind == KindSpace {
sep = h.File.Nodes[i].Raw
} else if strings.Contains(h.File.String(), "\n") {
sep = "\n"
}
}
nodes := []*Node{
{Kind: KindSpace, Raw: sep},
{Kind: KindOpcode, Raw: name + "=" + value, Name: name, Value: strings.TrimSpace(value)},
}
h.File.insert(at, nodes...)
}
// Delete removes the opcode, every time the header has it, with the space
// before it.
func (h *Header) Delete(name string) {
for {
n, ok := h.Get(name)
if !ok {
return
}
i := indexOf(h.File.Nodes, n)
from := i
if i > 0 && h.File.Nodes[i-1].Kind == KindSpace {
from = i - 1
}
h.File.Nodes = append(h.File.Nodes[:from], h.File.Nodes[i+1:]...)
h.File.reposition()
}
}
func indexOf(nodes []*Node, n *Node) int {
for i, m := range nodes {
if m == n {
return i
}
}
return -1
}
// insert adds nodes at an index.
func (f *File) insert(at int, nodes ...*Node) {
f.Nodes = append(f.Nodes[:at], append(nodes, f.Nodes[at:]...)...)
f.reposition()
}
// reposition sets the line and column of each node from the text before it.
func (f *File) reposition() {
line, col := 1, 1
for _, n := range f.Nodes {
n.Line, n.Col = line, col
for i := 0; i < len(n.Raw); i++ {
if n.Raw[i] == '\n' {
line++
col = 1
} else {
col++
}
}
}
}
// Headers returns the headers of every file of the document, in the order the
// files are read.
func (d *Document) Headers() []*Header {
var out []*Header
for _, f := range d.Files() {
for _, n := range f.Nodes {
if n.Kind == KindHeader {
out = append(out, &Header{File: f, Node: n})
}
}
}
return out
}
// AddHeader adds an empty header on a line of its own after another header and
// its opcodes, or at the end of the main file if after is nil, and returns it.
func (d *Document) AddHeader(name string, after *Header) *Header {
f := d.Root
at := len(f.Nodes)
if after != nil {
f = after.File
_, at = after.span()
}
var nodes []*Node
if at > 0 && !strings.HasSuffix(f.Nodes[at-1].Raw, "\n") {
nodes = append(nodes, &Node{Kind: KindSpace, Raw: "\n"})
}
h := &Node{Kind: KindHeader, Raw: "<" + name + ">", Name: name}
nodes = append(nodes, h, &Node{Kind: KindSpace, Raw: "\n"})
f.insert(at, nodes...)
return &Header{File: f, Node: h}
}
// Defines returns the #define nodes of every file, in order.
func (d *Document) Defines() []*Node { return d.nodes(KindDefine) }
// Includes returns the #include nodes of every file, in order.
func (d *Document) Includes() []*Node { return d.nodes(KindInclude) }
func (d *Document) nodes(kind NodeKind) []*Node {
var out []*Node
for _, f := range d.Files() {
for _, n := range f.Nodes {
if n.Kind == kind {
out = append(out, n)
}
}
}
return out
}
// SetDefine gives a variable a new value, by changing its first #define, so
// that each opcode that uses it changes with it. Setting an opcode that uses
// the variable with [Header.Set] replaces the variable there instead. A
// variable with no #define gets one at the start of the main file. The name
// includes its $.
func (d *Document) SetDefine(name, value string) {
for _, n := range d.Defines() {
if n.Name == name {
n.Raw = "#define " + name + " " + value
n.Value = value
d.reposition()
return
}
}
d.Root.insert(0,
&Node{Kind: KindDefine, Raw: "#define " + name + " " + value, Name: name, Value: value},
&Node{Kind: KindSpace, Raw: "\n"})
}
// reposition sets the positions of every file's nodes.
func (d *Document) reposition() {
for _, f := range d.Files() {
f.reposition()
}
}
+105
View File
@@ -0,0 +1,105 @@
package sfz
import (
"strings"
"testing"
)
func mustParse(t *testing.T, text string, m map[string]string) *Document {
t.Helper()
if m == nil {
m = map[string]string{}
}
doc, err := Parse(strings.NewReader(text), WithResolver(files(m)))
if err != nil {
t.Fatal(err)
}
return doc
}
func TestSetKeepsLayout(t *testing.T) {
doc := mustParse(t, "// piano\n<group>\n\tvolume=-1 // quiet\n\tpan=5\n<region> sample=a.wav\n", nil)
hs := doc.Headers()
if len(hs) != 2 || hs[0].Name() != "group" {
t.Fatalf("headers %v", hs)
}
// An existing opcode keeps its place and the comment after it, a new one
// goes after the last and is laid out as it is.
hs[0].Set("volume", "-2")
hs[0].Set("tune", "10")
hs[1].Set("lokey", "c4")
want := "// piano\n<group>\n\tvolume=-2 // quiet\n\tpan=5\n\ttune=10\n<region> sample=a.wav lokey=c4\n"
if got := doc.String(); got != want {
t.Errorf("got %q\nwant %q", got, want)
}
if n, ok := hs[0].Get("tune"); !ok || n.Value != "10" || n.Line != 5 {
t.Errorf("tune %+v", n)
}
// What was written reads back.
if v, _ := GetAs[int](doc.Flatten().Regions[0].Opcodes, "lokey"); v != 60 {
t.Errorf("lokey %d", v)
}
}
func TestDelete(t *testing.T) {
doc := mustParse(t, "<region>\n sample=a.wav\n lokey=1\n hikey=2\n lokey=3\n", nil)
h := doc.Headers()[0]
h.Delete("lokey")
h.Delete("missing")
if got, want := doc.String(), "<region>\n sample=a.wav\n hikey=2\n"; got != want {
t.Errorf("got %q want %q", got, want)
}
}
func TestAddHeader(t *testing.T) {
doc := mustParse(t, "<group> volume=1\n<region> sample=a.wav", nil)
hs := doc.Headers()
h := doc.AddHeader("region", hs[0])
h.Set("sample", "b.wav")
h2 := doc.AddHeader("region", nil)
h2.Set("sample", "c.wav")
want := "<group> volume=1\n<region>\nsample=b.wav\n<region> sample=a.wav\n<region>\nsample=c.wav\n"
if got := doc.String(); got != want {
t.Errorf("got %q\nwant %q", got, want)
}
if n := len(doc.Flatten().Regions); n != 3 {
t.Errorf("%d regions", n)
}
}
// TestEditVariables checks the difference between changing an opcode that
// uses a variable and changing the variable.
func TestEditVariables(t *testing.T) {
text := "#define $V 5\n<region> sample=a.wav lokey=$V\n<region> sample=b.wav hikey=$V\n"
doc := mustParse(t, text, nil)
doc.Headers()[0].Set("lokey", "7")
if got, want := doc.String(), "#define $V 5\n<region> sample=a.wav lokey=7\n<region> sample=b.wav hikey=$V\n"; got != want {
t.Errorf("Set: %q", got)
}
doc.SetDefine("$V", "9")
regions := doc.Flatten().Regions
if regions[0].Opcodes["lokey"] != "7" || regions[1].Opcodes["hikey"] != "9" {
t.Errorf("SetDefine: %v %v", regions[0].Opcodes, regions[1].Opcodes)
}
doc.SetDefine("$NEW", "1")
if !strings.HasPrefix(doc.String(), "#define $NEW 1\n#define $V 9\n") || len(doc.Defines()) != 2 {
t.Errorf("new define: %q", doc.String())
}
}
// TestEditIncluded checks that an opcode of an included file is edited in that
// file.
func TestEditIncluded(t *testing.T) {
doc := mustParse(t, "#include \"x.sfz\"\n", map[string]string{"x.sfz": "<region> sample=a.wav\n"})
hs := doc.Headers()
if len(hs) != 1 || hs[0].File.Path != "x.sfz" {
t.Fatalf("headers %+v", hs)
}
hs[0].Set("lokey", "3")
if doc.String() != "#include \"x.sfz\"\n" || doc.Files()[1].String() != "<region> sample=a.wav lokey=3\n" {
t.Errorf("%q %q", doc.String(), doc.Files()[1].String())
}
if len(doc.Includes()) != 1 {
t.Error("includes")
}
}
+162
View File
@@ -0,0 +1,162 @@
package sfz
import (
"fmt"
"io"
"path"
"sort"
"strings"
)
// LineEnding is the line break a written document uses.
type LineEnding string
// The line endings.
const (
// KeepLineEndings leaves each line break as it was read.
KeepLineEndings LineEnding = ""
// LF is \n.
LF LineEnding = "\n"
// CRLF is \r\n.
CRLF LineEnding = "\r\n"
)
// WriteOptions change how a document is written. The zero value writes each
// file as it was read.
type WriteOptions struct {
// InlineIncludes replaces each #include that was read with the text of its
// file, so the main file stands alone.
InlineIncludes bool
// ExpandVariables replaces each variable with its value, as of where it is
// used, and leaves out the #define directives. Written to several files,
// a file that is included more than once, and so would be expanded
// differently each time, is an error.
ExpandVariables bool
// LineEnding sets the line break of the text written.
LineEnding LineEnding
}
// FileWriter writes a file of a document. The path is that of the file, with
// 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.
func (d *Document) Write(w io.Writer, opts WriteOptions) error {
r := &renderer{opts: opts, defines: map[string]string{}, 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))
return err
}
// 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.
func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) error {
r := &renderer{opts: opts, defines: map[string]string{}, outputs: map[string]string{}}
text := r.file(d.Root)
if r.err != nil {
return r.err
}
if err := fw(root, []byte(r.lineEndings(text))); err != nil {
return err
}
paths := make([]string, 0, len(r.outputs))
for p := range r.outputs {
paths = append(paths, p)
}
sort.Strings(paths)
dir := path.Dir(root)
for _, p := range paths {
if err := fw(path.Join(dir, p), []byte(r.lineEndings(r.outputs[p]))); err != nil {
return err
}
}
return nil
}
// renderer writes files as the options say.
type renderer struct {
opts WriteOptions
defines map[string]string
// outputs are the included files that stand apart, by path.
outputs map[string]string
err error
}
func (r *renderer) lineEndings(text string) string {
if r.opts.LineEnding == KeepLineEndings {
return text
}
text = strings.ReplaceAll(text, "\r\n", "\n")
return strings.ReplaceAll(text, "\n", string(r.opts.LineEnding))
}
// file returns the text of a file as it is written.
func (r *renderer) file(f *File) string {
var b strings.Builder
// dropBreak is whether the next line break is cut, as the directive it
// followed is.
dropBreak := false
for _, n := range f.Nodes {
raw := n.Raw
switch n.Kind {
case KindDefine:
if r.opts.ExpandVariables {
r.defines[n.Name] = strings.TrimSpace(substitute(r.defines, n.Value))
dropBreak = true
continue
}
case KindInclude:
dropBreak = false
if r.opts.InlineIncludes && n.File != nil {
inner := r.file(n.File)
b.WriteString(spaced(b.String(), inner))
continue
}
if r.opts.ExpandVariables {
raw = `#include "` + n.Resolved + `"`
}
if n.File != nil {
r.output(n, r.file(n.File))
}
case KindSpace:
if dropBreak {
raw = strings.TrimPrefix(strings.TrimPrefix(raw, "\r"), "\n")
}
dropBreak = false
default:
dropBreak = false
if r.opts.ExpandVariables {
raw = substitute(r.defines, raw)
}
}
b.WriteString(raw)
}
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) {
if prev, ok := r.outputs[n.Resolved]; ok && prev != text && r.err == nil {
r.err = fmt.Errorf("%w: %s is included more than once and is written differently each time", ErrInvalid, n.Resolved)
}
r.outputs[n.Resolved] = text
}
+85
View File
@@ -0,0 +1,85 @@
package sfz
import (
"strings"
"testing"
)
func write(t *testing.T, doc *Document, opts WriteOptions) string {
t.Helper()
var b strings.Builder
if err := doc.Write(&b, opts); err != nil {
t.Fatal(err)
}
return b.String()
}
var writeFiles = map[string]string{
"x.sfz": "// kit\n<region> sample=$S.wav\n",
}
const writeMain = "#define $S kick\n#include \"x.sfz\"\n#define $S snare\n<region> sample=$S.wav\n"
func TestWriteZeroValue(t *testing.T) {
doc := mustParse(t, writeMain, writeFiles)
if got := write(t, doc, WriteOptions{}); got != writeMain {
t.Errorf("got %q", got)
}
}
func TestInlineIncludes(t *testing.T) {
doc := mustParse(t, writeMain, writeFiles)
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"
if got != want {
t.Errorf("got %q want %q", got, want)
}
// The single file reads as the document did.
flat := mustParse(t, got, nil).Flatten()
if len(flat.Regions) != 2 || flat.Regions[0].Opcodes["sample"] != "kick.wav" || flat.Regions[1].Opcodes["sample"] != "snare.wav" {
t.Errorf("regions %+v", flat.Regions)
}
}
func TestExpandVariables(t *testing.T) {
doc := mustParse(t, writeMain, writeFiles)
got := write(t, doc, WriteOptions{InlineIncludes: true, ExpandVariables: true})
want := "// kit\n<region> sample=kick.wav\n \n<region> sample=snare.wav\n"
if got != want {
t.Errorf("got %q want %q", got, want)
}
// Without inlining, the included file needs the variable, so only the files
// written together are expanded.
if err := doc.Write(new(strings.Builder), WriteOptions{ExpandVariables: true}); err == nil {
t.Error("expanding variables beside includes didn't fail")
}
out := map[string]string{}
err := doc.WriteFiles("m.sfz", func(p string, d []byte) error { out[p] = string(d); return nil }, WriteOptions{ExpandVariables: true})
if err != nil {
t.Fatal(err)
}
if out["m.sfz"] != "#include \"x.sfz\"\n<region> sample=snare.wav\n" || out["x.sfz"] != "// kit\n<region> sample=kick.wav\n" {
t.Errorf("files %q", out)
}
// A file included twice with different values can't be written once.
twice := mustParse(t, "#define $S a\n#include \"x.sfz\"\n#define $S b\n#include \"x.sfz\"\n", writeFiles)
err = twice.WriteFiles("m.sfz", func(string, []byte) error { return nil }, WriteOptions{ExpandVariables: true})
if err == nil {
t.Error("a file written two ways didn't fail")
}
}
func TestLineEndings(t *testing.T) {
doc := mustParse(t, "<region>\r\nsample=a.wav\n", nil)
if got := write(t, doc, WriteOptions{LineEnding: LF}); got != "<region>\nsample=a.wav\n" {
t.Errorf("LF %q", got)
}
if got := write(t, doc, WriteOptions{LineEnding: CRLF}); got != "<region>\r\nsample=a.wav\r\n" {
t.Errorf("CRLF %q", got)
}
if got := write(t, doc, WriteOptions{}); got != "<region>\r\nsample=a.wav\n" {
t.Errorf("kept %q", got)
}
}