-
Notifications
You must be signed in to change notification settings - Fork 65
/
filesystem_writer.go
72 lines (57 loc) · 1.76 KB
/
filesystem_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
package artifacts
import (
"fmt"
"io"
"path/filepath"
"github.com/spf13/afero"
)
// FilesystemWriter is an ArtifactWriter that targets a particular directory on
// the underlying filesystem.
type FilesystemWriter struct {
dir string
fs afero.Fs
}
// NewFilesystemWriter creates an artifact writer which writes to the filesystem.
func NewFilesystemWriter(opts ...FilesystemWriterOption) (*FilesystemWriter, error) {
w := FilesystemWriter{
dir: resolveFullPath(DefaultArtifactsDir),
fs: afero.NewOsFs(),
}
for _, opt := range opts {
opt(&w)
}
return &w, nil
}
// WithDirectory sets the artifacts directory to dir unless it's empty, in which case
// this option is ignored.
func WithDirectory(dir string) FilesystemWriterOption {
return func(w *FilesystemWriter) {
if dir == "" {
return
}
w.dir = resolveFullPath(dir)
}
}
type FilesystemWriterOption = func(*FilesystemWriter)
// WriteFile places contents into dir at filename.
func (w *FilesystemWriter) WriteFile(filename string, contents io.Reader) (string, error) {
fullFilePath := filepath.Join(w.Path(), filename)
if err := afero.WriteReader(w.fs, fullFilePath, contents); err != nil {
return fullFilePath, fmt.Errorf("could not write file to artifacts directory: %v", err)
}
return fullFilePath, nil
}
// Exists checks if a file exists with a filename
func (w *FilesystemWriter) Exists(filename string) (bool, error) {
fullFilePath := filepath.Join(w.Path(), filename)
return afero.Exists(w.fs, fullFilePath)
}
// Remove removes contents from dir at filename.
func (w *FilesystemWriter) Remove(filename string) error {
fullFilePath := filepath.Join(w.Path(), filename)
return w.fs.Remove(fullFilePath)
}
// Path is the full artifacts path.
func (w *FilesystemWriter) Path() string {
return w.dir
}