-
Notifications
You must be signed in to change notification settings - Fork 8
/
simple_tree_mkdirer.go
91 lines (75 loc) · 1.91 KB
/
simple_tree_mkdirer.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
//go:build !tinywasm
package gtree
import (
"errors"
"os"
"path/filepath"
"strings"
)
var (
// ErrExistPath is returned if the argument *gtree.Node of MkdirProgrammably function is path already exists.
ErrExistPath = errors.New("path already exists")
)
func newMkdirerSimple(dir string, fileExtensions []string) mkdirerSimple {
targetDir := "."
if len(dir) != 0 {
targetDir = dir
}
return &defaultMkdirerSimple{
targetDir: targetDir,
fileConsiderer: newFileConsiderer(fileExtensions),
}
}
type defaultMkdirerSimple struct {
targetDir string
fileConsiderer *fileConsiderer
}
func (dm *defaultMkdirerSimple) mkdir(roots []*Node) error {
if dm.isExistRoot(roots) {
return ErrExistPath
}
for _, root := range roots {
if err := dm.makeDirectoriesAndFiles(root); err != nil {
return err
}
}
return nil
}
func (dm *defaultMkdirerSimple) isExistRoot(roots []*Node) bool {
for _, root := range roots {
if _, err := os.Stat(filepath.Join(dm.targetDir, root.path())); !os.IsNotExist(err) {
return true
}
}
return false
}
func (dm *defaultMkdirerSimple) makeDirectoriesAndFiles(current *Node) error {
if dm.fileConsiderer.isFile(current) {
dir := strings.TrimSuffix(current.path(), current.name)
if err := dm.mkdirAll(filepath.Join(dm.targetDir, dir)); err != nil {
return err
}
return dm.mkfile(filepath.Join(dm.targetDir, current.path()))
}
if !current.hasChild() {
return dm.mkdirAll(filepath.Join(dm.targetDir, current.path()))
}
for _, child := range current.children {
if err := dm.makeDirectoriesAndFiles(child); err != nil {
return err
}
}
return nil
}
const permission = 0o755
func (*defaultMkdirerSimple) mkdirAll(dir string) error {
return os.MkdirAll(dir, permission)
}
func (*defaultMkdirerSimple) mkfile(path string) error {
f, err := os.Create(path)
if err != nil {
return err
}
return f.Close()
}
var _ mkdirerSimple = (*defaultMkdirerSimple)(nil)