Debian Codegraph @

parsing/writer.go

raw symbols SCIP
1 package parsing
2
3 import (
4 "bytes"
5 "fmt"
6
7 "github.com/tomwright/dasel/v3/model"
8 )
9
10 var writers = map[Format]NewWriterFn{}
11
12 type WriterOptions struct {
13 Compact bool
14 Indent string
15 Ext map[string]string
16 }
17
18 // DefaultWriterOptions returns the default writer options.
19 func DefaultWriterOptions() WriterOptions {
20 return WriterOptions{
21 Compact: false,
22 Indent: " ",
23 Ext: make(map[string]string),
24 }
25 }
26
27 // Writer writes a value to a byte slice.
28 type Writer interface {
29 // Write writes a value to a byte slice.
30 Write(*model.Value) ([]byte, error)
31 }
32
33 // NewWriterFn is a function that creates a new writer.
34 type NewWriterFn func(options WriterOptions) (Writer, error)
35
36 // RegisterWriter registers a new writer for the format.
37 func RegisterWriter(format Format, fn NewWriterFn) {
38 writers[format] = fn
39 }
40
41 // DocumentSeparator is an interface that can be implemented by writers to allow for custom document separators.
42 type DocumentSeparator interface {
43 // Separator returns the document separator.
44 Separator() []byte
45 }
46
47 // MultiDocumentWriter is a writer that can write multiple documents.
48 func MultiDocumentWriter(w Writer) Writer {
49 return &multiDocumentWriter{w: w}
50 }
51
52 type multiDocumentWriter struct {
53 w Writer
54 }
55
56 // Write writes a value to a byte slice.
57 func (w *multiDocumentWriter) Write(value *model.Value) ([]byte, error) {
58 if value.IsBranch() || value.IsSpread() {
59 buf := new(bytes.Buffer)
60
61 documentSeparator := []byte("\n")
62 if ds, ok := w.w.(DocumentSeparator); ok {
63 documentSeparator = ds.Separator()
64 }
65
66 totalDocuments, err := value.SliceLen()
67 if err != nil {
68 return nil, fmt.Errorf("failed to get document length: %w", err)
69 }
70
71 if err := value.RangeSlice(func(i int, v *model.Value) error {
72 docBytes, err := w.w.Write(v)
73 if err != nil {
74 return fmt.Errorf("failed to write document %d: %w", i, err)
75 }
76 buf.Write(docBytes)
77
78 if i < totalDocuments-1 {
79 buf.Write(documentSeparator)
80 }
81
82 return nil
83 }); err != nil {
84 return nil, err
85 }
86
87 return buf.Bytes(), nil
88 }
89 return w.w.Write(value)
90 }