-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
force.go
109 lines (103 loc) · 2.3 KB
/
force.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
100
101
102
103
104
105
106
107
108
109
package genny
import (
"fmt"
"io/fs"
"io/ioutil"
"os"
"path/filepath"
"github.com/gobuffalo/packd"
)
// ForceBox will mount each file in the box and wrap it with ForceFile
func ForceBox(g *Generator, box packd.Walker, force bool) error {
return box.Walk(func(path string, bf packd.File) error {
f := NewFile(path, bf)
ff := ForceFile(f, force)
f, err := ff(f)
if err != nil {
return err
}
g.File(f)
return nil
})
}
// ForceFS will mount each file in the fs.FS and wrap it with ForceFile
func ForceFS(g *Generator, fsys fs.FS, force bool) error {
return fs.WalkDir(fsys, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
r, err := fsys.Open(path)
if err != nil {
return err
}
f := NewFile(path, r)
ff := ForceFile(f, force)
f, err = ff(f)
if err != nil {
return err
}
g.File(f)
return nil
})
}
// ForceFile is a TransformerFn that will return an error if the path exists if `force` is false. If `force` is true it will delete the path.
func ForceFile(f File, force bool) TransformerFn {
return func(f File) (File, error) {
path := f.Name()
path, err := filepath.Abs(path)
if err != nil {
return f, err
}
_, err = os.Stat(path)
if err != nil {
// path doesn't exist. move on.
return f, nil
}
if !force {
return f, fmt.Errorf("path %s already exists", path)
}
if err := os.RemoveAll(path); err != nil {
return f, err
}
return f, nil
}
}
// Force is a RunFn that will return an error if the path exists if `force` is false. If `force` is true it will delete the path.
// Is is recommended to use ForceFile when you can.
func Force(path string, force bool) RunFn {
if path == "." || path == "" {
pwd, _ := os.Getwd()
path = pwd
}
return func(r *Runner) error {
path, err := filepath.Abs(path)
if err != nil {
return err
}
fi, err := os.Stat(path)
if err != nil {
// path doesn't exist. move on.
return nil
}
if !force {
if !fi.IsDir() {
return fmt.Errorf("path %s already exists", path)
}
files, err := ioutil.ReadDir(path)
if err != nil {
return err
}
if len(files) > 0 {
return fmt.Errorf("path %s already exists", path)
}
return nil
}
if err := os.RemoveAll(path); err != nil {
return err
}
return nil
}
}