-
Notifications
You must be signed in to change notification settings - Fork 136
/
document_set.go
67 lines (54 loc) · 1.51 KB
/
document_set.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package yamlmeta
import (
"bytes"
"fmt"
"io"
"github.com/k14s/ytt/pkg/yamlmeta/internal/yaml.v2"
)
type DocSetOpts struct {
WithoutMeta bool
// associatedName is typically a file name where data came from
AssociatedName string
}
func NewDocumentSetFromBytesWithOpts(data []byte, opts DocSetOpts) (*DocumentSet, error) {
docSet, err := NewParser(opts.WithoutMeta).ParseBytes(data, opts.AssociatedName)
if err != nil {
return nil, err
}
docSet.originalBytes = &data
return docSet, nil
}
func NewDocumentSetFromBytes(data []byte, associatedName string) (*DocumentSet, error) {
return NewDocumentSetFromBytesWithOpts(data, DocSetOpts{AssociatedName: associatedName})
}
func (d *DocumentSet) Print(writer io.Writer) {
NewPrinter(writer).Print(d)
}
// AsSourceBytes() returns bytes used to make original DocumentSet.
// Any changes made to the DocumentSet are not reflected in any way
func (d *DocumentSet) AsSourceBytes() ([]byte, bool) {
if d.originalBytes != nil {
return *d.originalBytes, true
}
return nil, false
}
func (d *DocumentSet) AsBytes() ([]byte, error) {
buf := new(bytes.Buffer)
var writtenOnce bool
for i, item := range d.Items {
if item.injected || item.IsEmpty() {
continue
}
if writtenOnce {
buf.Write([]byte("---\n")) // TODO use encoder?
} else {
writtenOnce = true
}
bs, err := yaml.Marshal(item.AsInterface(InterfaceConvertOpts{OrderedMap: true}))
if err != nil {
return nil, fmt.Errorf("marshaling doc %d: %s", i, err)
}
buf.Write(bs)
}
return buf.Bytes(), nil
}