Files

217 lines
7.2 KiB
Go
Raw Permalink Normal View History

2026-12-01 17:41:34 +00:00
package sfz
import (
"fmt"
"io"
"io/fs"
2026-12-01 17:41:34 +00:00
"path"
"sort"
"strings"
)
// LineEnding is the line break that a written document uses.
2026-12-01 17:41:34 +00:00
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, with the line breaks it had.
2026-12-01 17:41:34 +00:00
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. A file that is included more
// than once, with its variables set differently each time, can't be written
// as a file of its own, as it would need to be written differently each
// time, and [Document.WriteFiles] returns an error for it.
2026-12-01 17:41:34 +00:00
ExpandVariables bool
// AllowParentPaths lets [Document.WriteFiles] write an included file whose
// path leaves the folder of the main file with "..", as the DrumGizmo kits'
// "../Data" layout does. Absolute paths are refused either way. The writer
// is then trusted with files outside the folder, so set it only for
// documents whose includes are known to be safe.
AllowParentPaths bool
// LineEnding is the line break of the text written. The zero value is
// [KeepLineEndings].
2026-12-01 17:41:34 +00:00
LineEnding LineEnding
}
// FileWriter writes the data of a file of a document. The path is that of the
// file, with forward slashes, in the folder of the path given to
// [Document.WriteFiles].
2026-12-01 17:41:34 +00:00
type FileWriter func(path string, data []byte) error
// Write writes the document as one file to w. A document with includes that
// were read can be written as one file only with InlineIncludes, as the files
// they hold would be lost otherwise, and Write returns an error wrapping
// [ErrInvalid] for it. Use [Document.WriteFiles] to write the files
// separately, with ExpandVariables or not.
2026-12-01 17:41:34 +00:00
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{}}
_, err := io.WriteString(w, r.lineEndings(r.file(d.Root)))
2026-12-01 17:41:34 +00:00
return err
}
// hasIncludes reports whether the main file has an include that was read.
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 an error wrapping [ErrInvalid], for an include whose path is absolute
// or leaves the folder (unless AllowParentPaths is set, which permits leaving
// it with ".."), and for a file that is included more than once and
// would be written differently each time.
2026-12-01 17:41:34 +00:00
func (d *Document) WriteFiles(root string, fw FileWriter, opts WriteOptions) error {
r := &renderer{opts: opts, defines: defines{}, outputs: map[string]string{}, collect: true}
2026-12-01 17:41:34 +00:00
text := r.file(d.Root)
if r.err != nil {
return r.err
}
paths := make([]string, 0, len(r.outputs))
for p := range r.outputs {
// An include path comes from the text, so it can't be trusted to stay in
// the folder.
if !fs.ValidPath(p) && !(opts.AllowParentPaths && isParentPath(p)) {
return fmt.Errorf("%w: the include %q is outside the folder of the main file", ErrInvalid, p)
}
2026-12-01 17:41:34 +00:00
paths = append(paths, p)
}
sort.Strings(paths)
if err := fw(root, []byte(r.lineEndings(text))); err != nil {
return err
}
2026-12-01 17:41:34 +00:00
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
}
// isParentPath reports whether p is a relative, clean path that leaves its
// folder with "..", and otherwise has no empty, "." or ".." elements after the
// leading ones.
func isParentPath(p string) bool {
if p == "" || strings.Contains(p, "\\") || path.Clean(p) != p || path.IsAbs(p) {
return false
}
rest := p
for strings.HasPrefix(rest, "../") {
rest = rest[3:]
}
return rest == ".." || fs.ValidPath(rest)
}
// renderer writes the files of a document as the options say.
2026-12-01 17:41:34 +00:00
type renderer struct {
opts WriteOptions
// defines are the variables defined so far, when variables are expanded.
defines defines
// collect is whether the included files that stand apart are kept in
// outputs, as WriteFiles writes them.
collect bool
2026-12-01 17:41:34 +00:00
// outputs are the included files that stand apart, by path.
outputs map[string]string
// err is the first error found.
err error
2026-12-01 17:41:34 +00:00
}
// lineEndings returns text with the line breaks that the options give it.
2026-12-01 17:41:34 +00:00
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, with the files it includes
// written into it or kept for [Document.WriteFiles], as the options say.
2026-12-01 17:41:34 +00:00
func (r *renderer) file(f *File) string {
var b strings.Builder
// dropBreak is whether the next line break is cut, as the directive that it
// ends is cut, or its text has been written in its place.
2026-12-01 17:41:34 +00:00
dropBreak := false
// gap is whether an inlined file ended without whitespace, so that what
// follows needs some to stay apart from it.
gap := false
2026-12-01 17:41:34 +00:00
for _, n := range f.Nodes {
raw := n.Raw
if gap && raw != "" && !isSpace(raw[0]) {
b.WriteByte(' ')
}
gap = false
2026-12-01 17:41:34 +00:00
switch n.Kind {
case KindDefine:
if r.opts.ExpandVariables {
r.defines.define(n)
2026-12-01 17:41:34 +00:00
dropBreak = true
continue
}
case KindInclude:
dropBreak = false
if r.opts.InlineIncludes && n.File != nil {
inner := r.file(n.File)
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 after a file
// that ends with one.
dropBreak = strings.HasSuffix(inner, "\n")
gap = inner != "" && !isSpace(inner[len(inner)-1])
2026-12-01 17:41:34 +00:00
continue
}
if r.opts.ExpandVariables {
raw = `#include "` + n.Resolved + `"`
}
if n.File != nil && r.collect {
2026-12-01 17:41:34 +00:00
r.output(n, r.file(n.File))
}
case KindSpace:
if dropBreak {
raw = strings.TrimPrefix(strings.TrimPrefix(raw, "\r"), "\n")
}
dropBreak = false
case KindComment:
dropBreak = false
2026-12-01 17:41:34 +00:00
default:
dropBreak = false
if r.opts.ExpandVariables {
raw = substitute(r.defines, raw)
}
}
b.WriteString(raw)
}
return b.String()
}
// output keeps the text of an included file, and sets err if the file has
// already been kept with other text.
2026-12-01 17:41:34 +00:00
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
}