-
Notifications
You must be signed in to change notification settings - Fork 2
/
writer.go
66 lines (56 loc) · 1.43 KB
/
writer.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
package build
import (
"fmt"
"io"
"io/fs"
"io/ioutil"
"os"
"path/filepath"
xapiextv1 "github.com/crossplane/crossplane/apis/apiextensions/v1"
"sigs.k8s.io/yaml"
)
// CompositionWriter specifies the interface for a delegate that writes the
// generated composition to the target destination.
type CompositionWriter interface {
// Write writes the given composition to the destintation output.
Write(c xapiextv1.Composition) error
}
// NewWriterWriter creates a CompositionWriter that writes to the given
// io.Writer.
func NewWriterWriter(w io.Writer) CompositionWriter {
return &writerWriter{
writer: w,
}
}
type writerWriter struct {
writer io.Writer
}
func (w *writerWriter) Write(c xapiextv1.Composition) error {
b, err := yaml.Marshal(c)
if err != nil {
return err
}
_, err = w.writer.Write(b)
return err
}
// NewDirectoryWriter creates a new CompositionWriter that writes each
// composition to the given directory using the objects name as filename.
func NewDirectoryWriter(dir string) CompositionWriter {
return &directoryWriter{
dir: dir,
}
}
type directoryWriter struct {
dir string
}
func (w *directoryWriter) Write(c xapiextv1.Composition) error {
b, err := yaml.Marshal(c)
if err != nil {
return err
}
if err := os.MkdirAll(w.dir, fs.FileMode(0777)); err != nil {
return err
}
filename := fmt.Sprintf("%s.yaml", c.GetName())
return ioutil.WriteFile(filepath.Join(w.dir, filename), b, fs.FileMode(0664))
}