-
Notifications
You must be signed in to change notification settings - Fork 1
/
part_file.go
96 lines (81 loc) · 2.24 KB
/
part_file.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
86
87
88
89
90
91
92
93
94
95
96
package mc
import (
"github.com/pkg/errors"
"io"
"os"
)
type OpenOrCreateOptions struct {
Template string
TemplatePath string
}
type OpenOrCreateOptionFunc func(o *OpenOrCreateOptions) error
func OpenOrCreateWithTemplate(template string) OpenOrCreateOptionFunc {
return func(o *OpenOrCreateOptions) error {
o.Template = template
return nil
}
}
func OpenOrCreateWithTemplatePath(templatePath string) OpenOrCreateOptionFunc {
return func(o *OpenOrCreateOptions) error {
o.TemplatePath = templatePath
return nil
}
}
// EnsureFileExists ensures the file exist, creates it with a template if not.
func EnsureFileExists(filePath string, optionFuncs ...OpenOrCreateOptionFunc) error {
options := &OpenOrCreateOptions{}
for _, optionFunc := range optionFuncs {
if err := optionFunc(options); err != nil {
return errors.Wrap(err, "apply option error")
}
}
_, err := os.Stat(filePath)
if err == nil {
return nil // already exist
}
if !os.IsNotExist(err) {
return errors.Wrapf(err, "os.Stat: %s error", filePath)
}
// not exist, create it
file, err := os.Create(filePath)
if err != nil {
return errors.Wrapf(err, "os.Open: %s error", filePath)
}
defer func() {
Must(file.Close())
}()
if options.Template != "" {
if _, err := file.WriteString(options.Template); err != nil {
return errors.Wrap(err, "file.WriteString error")
}
return nil
}
if options.TemplatePath != "" {
if _, err := os.Stat(options.TemplatePath); err != nil {
if os.IsNotExist(err) {
return errors.Errorf("template not exist: %s", options.TemplatePath)
}
return errors.Wrapf(err, "os.Stat: %s error", options.TemplatePath)
}
tmpl, err := os.Open(options.TemplatePath)
if err != nil {
return errors.Wrapf(err, "os.Open: %s error", options.TemplatePath)
}
defer func() {
Must(tmpl.Close())
}()
_, err = io.Copy(file, tmpl)
if err != nil {
return errors.Wrap(err, "io.Copy error")
}
}
// no template, just create an empty file
return nil
}
// OpenOrCreate opens the file, creates it with a template if not.
func OpenOrCreate(filePath string, optionFuncs ...OpenOrCreateOptionFunc) (*os.File, error) {
if err := EnsureFileExists(filePath, optionFuncs...); err != nil {
return nil, err
}
return os.Open(filePath)
}