forked from zyedidia/eget
-
Notifications
You must be signed in to change notification settings - Fork 0
/
targetfile.go
85 lines (64 loc) · 1.48 KB
/
targetfile.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package targetfile
import (
"errors"
"os"
"github.com/twpayne/go-vfs/v5"
)
var ErrInvalidated = errors.New("target file has been invalidated")
type TargetFile struct {
File *os.File
Filename *string
ShouldClose bool
Err error
Fs vfs.FS
}
// Cleanup closes the file if it should be closed and sets the file to nil.
// The TargetFile instance should be considered invalid after calling this method.
func (tf *TargetFile) Cleanup() error {
if !tf.ShouldClose || tf.IsInvalid() {
return nil
}
if err := tf.File.Close(); err != nil {
return err
}
tf.Invalidate()
return nil
}
// Write writes the given data to the target file. If cleanup is true, the file will be closed after
// writing the data and the TargetFile instance should be considered invalid.
func (tf *TargetFile) Write(data []byte, cleanup bool) error {
if tf.HasError() {
return tf.Err
}
if tf.IsInvalid() {
return ErrInvalidated
}
_, err := tf.File.Write(data)
if cleanup {
defer tf.Cleanup()
}
return err
}
func (tf *TargetFile) WithError(err error) *TargetFile {
tf.Err = err
return tf
}
func (tf *TargetFile) Invalidate() {
tf.File = nil
tf.ShouldClose = false
}
func (tf *TargetFile) IsInvalid() bool {
return tf.File == nil
}
func (tf *TargetFile) HasError() bool {
return tf.Err != nil
}
func (tf *TargetFile) HasFilename() bool {
return tf.Filename != nil
}
func (tf *TargetFile) Name() string {
if tf.Filename == nil {
return ""
}
return *tf.Filename
}