forked from gobuffalo/genny
-
Notifications
You must be signed in to change notification settings - Fork 2
/
force.go
84 lines (79 loc) · 1.82 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
package genny
import (
"fmt"
"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
})
}
// 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
}
}