1package runtime
2
3import (
4	"fmt"
5	"io/ioutil"
6	"os"
7	"path/filepath"
8)
9
10//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . FileStore
11
12// FileStore is responsible for managing files associated with containers.
13//
14type FileStore interface {
15	// CreateFile creates a file with a particular content in the store.
16	//
17	Create(name string, content []byte) (absPath string, err error)
18
19	// DeleteFile removes a file previously created in the store.
20	//
21	Delete(name string) (err error)
22}
23
24type fileStore struct {
25	root string
26}
27
28var _ FileStore = (*fileStore)(nil)
29
30func NewFileStore(root string) *fileStore {
31	return &fileStore{
32		root: root,
33	}
34}
35
36func (f fileStore) Create(name string, content []byte) (string, error) {
37	absPath := filepath.Join(f.root, name)
38	dir := filepath.Dir(absPath)
39
40	err := os.MkdirAll(dir, 0755)
41	if err != nil {
42		return "", fmt.Errorf("mkdirall: %w", err)
43	}
44
45	err = ioutil.WriteFile(absPath, content, 0755)
46	if err != nil {
47		return "", fmt.Errorf("write file: %w", err)
48	}
49
50	return absPath, nil
51}
52
53func (f fileStore) Delete(path string) error {
54	absPath := filepath.Join(f.root, path)
55
56	err := os.RemoveAll(absPath)
57	if err != nil {
58		return fmt.Errorf("remove all: %w", err)
59	}
60
61	return nil
62}
63