-
Notifications
You must be signed in to change notification settings - Fork 278
/
writer.go
99 lines (82 loc) · 2.03 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
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
97
98
99
package filewriter
import (
"errors"
"fmt"
"io"
"io/fs"
"io/ioutil"
"os"
"path/filepath"
)
type writer struct {
dir string
tempDir string
}
func NewWriter(dir string) (FileWriter, error) {
newFolder := filepath.Join(dir, DefaultTmpFolder)
if _, err := os.Stat(newFolder); errors.Is(err, os.ErrNotExist) {
err := os.MkdirAll(newFolder, os.ModePerm)
if err != nil {
return nil, fmt.Errorf("creating directory [%s]: %v", dir, err)
}
}
return &writer{dir: dir, tempDir: newFolder}, nil
}
func (w *writer) Write(fileName string, content []byte, opts ...FileOptionsFunc) (string, error) {
o := buildOptions(w, opts)
filePath := filepath.Join(o.BasePath, fileName)
err := ioutil.WriteFile(filePath, content, o.Permissions)
if err != nil {
return "", fmt.Errorf("writing to file [%s]: %v", filePath, err)
}
return filePath, nil
}
func (w *writer) WithDir(dir string) (FileWriter, error) {
return NewWriter(filepath.Join(w.dir, dir))
}
func (w *writer) Dir() string {
return w.dir
}
func (w *writer) TempDir() string {
return w.tempDir
}
func (w *writer) CleanUp() {
_, err := os.Stat(w.dir)
if err == nil {
os.RemoveAll(w.dir)
}
}
func (w *writer) CleanUpTemp() {
_, err := os.Stat(w.tempDir)
if err == nil {
os.RemoveAll(w.tempDir)
}
}
// Create creates a file with the given name rooted at w's base directory.
func (w *writer) Create(name string, opts ...FileOptionsFunc) (_ io.WriteCloser, path string, _ error) {
o := buildOptions(w, opts)
path = filepath.Join(o.BasePath, name)
fh, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, o.Permissions)
return fh, path, err
}
type options struct {
BasePath string
Permissions fs.FileMode
}
// buildOptions converts a set of FileOptionsFunc's to a single options struct.
func buildOptions(w *writer, opts []FileOptionsFunc) options {
op := defaultFileOptions()
for _, fn := range opts {
fn(op)
}
var basePath string
if op.IsTemp {
basePath = w.tempDir
} else {
basePath = w.dir
}
return options{
BasePath: basePath,
Permissions: op.Permissions,
}
}