forked from uetchy/gst
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command_remove.go
81 lines (69 loc) · 1.42 KB
/
command_remove.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
package main
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/Songmu/prompter"
"github.com/urfave/cli"
)
var commandRemove = cli.Command{
Name: "remove",
Action: doRemove,
Flags: []cli.Flag{
cli.BoolFlag{
Name: "f, force",
Usage: "Remove without prompt",
},
},
}
// IsEmpty checks if directory is empty
func IsEmpty(name string) (bool, error) {
f, err := os.Open(name)
if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdir(1)
if err == io.EOF {
return true, nil
}
return false, err // Either not empty or error, suits both cases
}
func doRemove(c *cli.Context) error {
forceRemove := c.Bool("force")
for _, arg := range c.Args() {
target := compileTargetPath(arg)
if _, err := os.Stat(target); err == nil {
if !forceRemove && !prompter.YN("Remove? "+target, true) {
os.Exit(0)
}
// Remove specified directory
err := os.RemoveAll(target)
if err == nil {
fmt.Println("Removed: " + target)
} else {
fmt.Println(err)
}
// Remove parent dirs if empty
ghqPath, _ := getGhqPath()
target = filepath.Dir(target)
for target != ghqPath {
if e, _ := IsEmpty(target); !e {
break
}
err := os.RemoveAll(target)
if err == nil {
fmt.Println("Removed: " + target)
} else {
fmt.Println(err)
break
}
target = filepath.Dir(target)
}
} else {
fmt.Println("Doesn't exist: " + target)
}
}
return nil
}