-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlazy_file.go
More file actions
62 lines (49 loc) · 1017 Bytes
/
Copy pathlazy_file.go
File metadata and controls
62 lines (49 loc) · 1017 Bytes
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
package cmdchain
import (
"os"
)
// lazyFile is a wrapper around os.File that lazily opens the file when the first write operation is performed.
type lazyFile struct {
name string
flag int
perm os.FileMode
file *os.File
fileErr error
}
func newLazyFile(name string, flag int, perm os.FileMode) *lazyFile {
return &lazyFile{
name: name,
flag: flag,
perm: perm,
}
}
func (l *lazyFile) Write(p []byte) (n int, err error) {
l.BeforeRun()
if l.fileErr != nil {
return 0, l.fileErr
}
return l.file.Write(p)
}
func (l *lazyFile) BeforeRun() {
if l.file == nil {
l.file, l.fileErr = os.OpenFile(l.name, l.flag, l.perm)
}
}
func (l *lazyFile) AfterRun() {
l.Close()
}
func (l *lazyFile) Close() (err error) {
if l.file != nil {
err = l.file.Close()
// reset to nil to ensure it is reopened on next write operation
l.file = nil
l.fileErr = nil
}
return
}
func (l *lazyFile) String() string {
if l.flag&os.O_APPEND != 0 {
return l.name + " (appending)"
}
return l.name
}