-
Notifications
You must be signed in to change notification settings - Fork 216
/
writer.go
61 lines (53 loc) · 1004 Bytes
/
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
// Package writer provides a writer that can be used to write to a file or stdout. (fleetapply)
package writer
import (
"io"
"os"
"path/filepath"
)
type nopCloser struct {
io.Writer
}
func (nopCloser) Close() error { return nil }
func NewDefaultNone(output string) io.WriteCloser {
if output == "" {
return nil
}
return New(output)
}
func New(output string) io.WriteCloser {
switch output {
case "":
return nopCloser{Writer: io.Discard}
case "-":
return os.Stdout
default:
return &lazyFileWriter{
path: output,
}
}
}
type lazyFileWriter struct {
path string
file *os.File
}
func (l *lazyFileWriter) Write(data []byte) (int, error) {
if l.file == nil {
dir := filepath.Dir(l.path)
if err := os.MkdirAll(dir, 0755); err != nil {
return 0, err
}
f, err := os.Create(l.path)
if err != nil {
return 0, err
}
l.file = f
}
return l.file.Write(data)
}
func (l *lazyFileWriter) Close() error {
if l.file == nil {
return nil
}
return l.file.Close()
}