-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
executable file
·135 lines (102 loc) · 2.27 KB
/
main.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package main
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"strings"
color "github.com/logrusorgru/aurora/v3"
"github.com/prajaraksh/sanitize"
"github.com/xlab/treeprint"
)
var (
recursive bool
change bool
rootDir string
treeMap map[string]treeprint.Tree
)
var separator = string(filepath.Separator)
var arrow = "━━▶ "
func init() {
flag.BoolVar(&recursive, "r", false, "recursive")
flag.BoolVar(&change, "c", false, "change fileNames, used in conjunction")
}
var s *sanitize.Sanitize
func main() {
flag.Parse()
s = sanitize.New()
args := flag.Args()
if len(args) > 0 {
for _, n := range os.Args[1:] {
nn := s.Clean(n)
fmt.Println(nn)
}
} else {
rootDir, _ = os.Getwd()
if rootDir != "/" {
rootDir += string(filepath.Separator)
}
treeMap = make(map[string]treeprint.Tree)
treeMap[rootDir] = treeprint.New()
filepath.Walk(rootDir, rename)
fmt.Print(treeMap[rootDir].String())
}
}
func rename(old string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
var new string
dir, file := filepath.Split(old)
if !recursive {
// End, when trying to walk another directory
if dir != rootDir {
return filepath.SkipDir
}
}
if file != "" {
new = s.Clean(file)
if file != new {
if change {
filePath := filepath.Join(dir, file)
newPath := filepath.Join(dir, new)
if err = os.Rename(filePath, newPath); err != nil {
log.Println(file, err)
}
}
if treeMap[dir] == nil {
createLink(dir)
}
if info.IsDir() {
treeMap[old+separator] = treeMap[dir].AddBranch(
fileChange(file, new),
)
} else {
treeMap[dir].AddNode(
fileChange(file, new),
)
}
}
}
return nil
}
func createLink(dir string) {
roots := strings.SplitAfter(rootDir, separator)
dirs := strings.SplitAfter(dir, separator)
rootLen := len(roots) - 1
roots = roots[:rootLen]
dirs = dirs[:len(dirs)-1]
prevDir := rootDir
for i := range dirs[rootLen:] {
curDir := prevDir + dirs[rootLen+i]
if treeMap[curDir] == nil {
_, file := filepath.Split(curDir[:len(curDir)-1])
treeMap[curDir] = treeMap[prevDir].AddBranch(color.Cyan(file))
}
prevDir = curDir
}
}
func fileChange(file, new string) string {
return fmt.Sprint(color.Red(file), arrow, color.Green(new))
}