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 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. 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: map[string]string{}, outputs: map[string]string{}} 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 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 }