package sfz import ( "fmt" "io" "io/fs" "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 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{}} _, 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{}, collect: true} 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) { return fmt.Errorf("%w: the include %q is outside the folder of the main file", ErrInvalid, p) } paths = append(paths, p) } sort.Strings(paths) if err := fw(root, []byte(r.lineEndings(text))); err != nil { return err } 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 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 } 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 // 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 { r.defines.define(n) 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. 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 && r.collect { 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 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 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 }