-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopulate.go
68 lines (59 loc) · 1.28 KB
/
populate.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
package testx
import (
"os"
"path"
"path/filepath"
)
type FileEntry struct {
Path string
Type FileType
}
type Cleanup func() error
// PopulateFS создает указанные файлы и директории.
func PopulateFS(workdir string, entries ...FileEntry) (_ Cleanup, err error) {
paths := make([]string, 0, len(entries))
defer func() {
if err != nil {
removeAll(paths, workdir) //nolint:errcheck //no need to check error
}
}()
for _, entry := range entries {
fullPath := path.Join(workdir, entry.Path)
if err := entry.create(fullPath); err != nil {
return nil, err
}
paths = append(paths, entry.Path)
}
return func() error {
return removeAll(paths, workdir)
}, nil
}
func (e *FileEntry) create(fullPath string) error {
switch e.Type {
case TypeDir:
if err := os.MkdirAll(fullPath, 0o755); err != nil {
return err
}
case TypeFile:
if err := os.MkdirAll(filepath.Dir(fullPath), 0o755); err != nil {
return err
}
file, err := os.Create(fullPath)
if err != nil {
return err
}
file.Close()
}
return nil
}
func removeAll(paths []string, workdir string) error {
for _, p := range paths {
for p != "." {
if err := os.RemoveAll(path.Join(workdir, p)); err != nil {
return err
}
p = filepath.Dir(p)
}
}
return nil
}