-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
238 lines (212 loc) · 8.71 KB
/
Copy pathmain.go
File metadata and controls
238 lines (212 loc) · 8.71 KB
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/charmbracelet/lipgloss"
)
var (
colMethod = lipgloss.Color("#FFFFFF") // White as requested
colOption = lipgloss.Color("#FFFFFF")
colBG = lipgloss.Color("#874BFD")
colHeaderText = lipgloss.Color("#000000") // Dark text on Purple
colErrorBG = lipgloss.Color("#F205B3")
colSuccess = lipgloss.Color("#B5FFD9")
colSuccessText = lipgloss.Color("#004422")
colTitle = lipgloss.Color("#FFFFFF")
colDim = lipgloss.Color("#666666")
colLight = lipgloss.Color("#999999")
styleTitle = lipgloss.NewStyle().Background(colBG).Foreground(colHeaderText).Bold(true).Padding(0, 1)
styleHeader = lipgloss.NewStyle().Background(colBG).Foreground(colHeaderText).Bold(true).Padding(0, 1).MarginTop(1)
styleOops = lipgloss.NewStyle().Background(colErrorBG).Foreground(colTitle).Bold(true).Padding(0, 1)
styleRenamed = lipgloss.NewStyle().Background(colSuccess).Foreground(colSuccessText).Bold(true).Padding(0, 1)
styleConfirm = lipgloss.NewStyle().Background(colBG).Foreground(colHeaderText).Padding(0, 1)
styleMethod = lipgloss.NewStyle().Foreground(colMethod).Bold(true)
styleOption = lipgloss.NewStyle().Foreground(colOption).Bold(true)
styleDim = lipgloss.NewStyle().Foreground(colDim)
styleLight = lipgloss.NewStyle().Foreground(colLight)
styleWhite = lipgloss.NewStyle().Foreground(lipgloss.Color("#FFFFFF"))
)
func main() {
if len(os.Args) < 3 {
printHelp("")
return
}
methodArg := strings.ToLower(os.Args[1])
rawTargets := os.Args[2:]
var targets []string
var formatFlag string
for i := 0; i < len(rawTargets); i++ {
arg := rawTargets[i]
if arg == "-f" && i+1 < len(rawTargets) {
formatFlag = rawTargets[i+1]
i++
} else {
targets = append(targets, arg)
}
}
var allFiles []string
for _, t := range targets {
cleanT := filepath.Clean(t)
if cleanT == "." {
matches, _ := filepath.Glob("./*")
allFiles = append(allFiles, matches...)
continue
}
info, err := os.Stat(cleanT)
if err == nil && info.IsDir() {
displayDir := cleanT
if !strings.HasSuffix(displayDir, string(os.PathSeparator)) {
displayDir += string(os.PathSeparator)
}
fmt.Printf("%s Did you mean to target %s*? %s ", styleLight.Render("Directory detected:"), displayDir, styleConfirm.Render("[y/N]"))
reader := bufio.NewReader(os.Stdin)
char, _, _ := reader.ReadRune()
if char == 'y' || char == 'Y' {
matches, _ := filepath.Glob(filepath.Join(cleanT, "*"))
allFiles = append(allFiles, matches...)
} else {
fmt.Println(styleDim.Render("Skipped directory."))
return
}
continue
}
matches, _ := filepath.Glob(cleanT)
if len(matches) > 0 {
allFiles = append(allFiles, matches...)
} else {
allFiles = append(allFiles, cleanT)
}
}
if len(allFiles) == 0 {
fmt.Println(styleDim.Render("No files matched the pattern."))
return
}
type renameResult struct {
old, new string
}
treeResults := make(map[string][]renameResult)
counter := 1
for _, oldPath := range allFiles {
fInfo, err := os.Stat(oldPath)
if err != nil || fInfo.IsDir() {
continue
}
dir := filepath.Dir(oldPath)
oldName := filepath.Base(oldPath)
ext := filepath.Ext(oldName)
base := strings.TrimSuffix(oldName, ext)
lowerExt := strings.ToLower(ext)
var newName string
switch methodArg {
case "num", "number":
if formatFlag == "" {
printError("'number' requires a common rename format.")
fmt.Println(styleLight.Render(fmt.Sprintf(" ./nom num %s -f common-name%s", strings.Join(targets, " "), lowerExt)))
return
}
if strings.Contains(formatFlag, "%") {
newName = fmt.Sprintf(formatFlag, counter)
} else {
tExt := filepath.Ext(formatFlag)
tBase := strings.TrimSuffix(formatFlag, tExt)
newName = fmt.Sprintf("%s-%d%s", tBase, counter, tExt)
}
counter++
case "dash", "dasherize":
newName = transform(base, "-", true) + lowerExt
case "lc", "lower":
newName = strings.ToLower(base) + lowerExt
case "sn", "snakeify":
newName = transform(base, "_", true) + lowerExt
case "sp", "spacify":
newName = transform(base, " ", true) + lowerExt
case "ucw", "ucwords":
newName = toUcWords(base) + lowerExt
case "uc", "uppercase":
newName = strings.ToUpper(base) + lowerExt
default:
printHelp(fmt.Sprintf("Unknown method: %s", methodArg))
return
}
newPath := filepath.Join(dir, newName)
if oldName != newName {
err := os.Rename(oldPath, newPath)
if err == nil {
treeResults[dir] = append(treeResults[dir], renameResult{oldName, newName})
}
}
}
total := 0
for _, res := range treeResults {
total += len(res)
}
if total > 0 {
fmt.Println(styleRenamed.Render(fmt.Sprintf("Renamed %d Files", total)))
for dir, res := range treeResults {
fmt.Printf("%s %s/\n", styleDim.Render("└──"), styleWhite.Render(dir))
for i, r := range res {
connector := "├──"
if i == len(res)-1 {
connector = "└──"
}
fmt.Printf(" %s %s %s %s\n", styleDim.Render(connector), styleLight.Render(r.old), styleDim.Render("->"), styleWhite.Render(r.new))
}
}
fmt.Println("")
} else {
fmt.Println(styleDim.Render("No changes were made."))
}
}
func printError(msg string) {
fmt.Printf("%s %s\n", styleOops.Render("Oops!"), styleWhite.Render(msg))
}
func transform(s, sep string, lower bool) string {
re := regexp.MustCompile(`[ \-_]+`)
res := re.ReplaceAllString(s, sep)
if lower {
return strings.ToLower(res)
}
return res
}
func toUcWords(s string) string {
re := regexp.MustCompile(`[ \-_]+`)
words := re.Split(s, -1)
for i, w := range words {
if len(w) > 0 {
words[i] = strings.ToUpper(w[:1]) + strings.ToLower(w[1:])
}
}
return strings.Join(words, " ")
}
func printHelp(errStr string) {
if errStr != "" {
printError(errStr)
}
fmt.Println(styleTitle.Render(" NOM "))
fmt.Println(styleLight.Render(" Minimalist bulk renamer. Extensions are always lowercased."))
fmt.Printf("\n Usage: nom <method> <path>\n")
fmt.Printf(" nom <method> <path> [options]\n")
fmt.Println(styleHeader.Render(" METHODS "))
fmt.Printf(" %-16s - Convert to dash (-) and lowercase\n", styleMethod.Render("dasherize (dash)"))
fmt.Printf(" %-16s - Convert filename to lowercase\n", styleMethod.Render("lower (lc) "))
fmt.Printf(" %-16s - Rename with sequential numbering\n", styleMethod.Render("number (num) "))
fmt.Printf(" %-16s - Convert to underscores (_) and lowercase\n", styleMethod.Render("snakeify (sn) "))
fmt.Printf(" %-16s - Convert to spaces and lowercase\n", styleMethod.Render("spacify (sp) "))
fmt.Printf(" %-16s - Uppercase the first letter of each word\n", styleMethod.Render("ucwords (ucw) "))
fmt.Printf(" %-16s - Convert filename to uppercase\n", styleMethod.Render("uppercase (uc) "))
fmt.Println(styleHeader.Render(" OPTIONS "))
fmt.Printf(" %-16s - Format Name, %%d-shared-name.jpg for 1-shared-name.jpg\n", styleOption.Render("-f <format>"))
fmt.Printf(" %-16s %s\n", "", styleDim.Render("Default: name-1.jpg (name-%d.jpg)"))
fmt.Printf(" %-16s %s\n", "", styleDim.Render("Advanced: %02d-name.jpg for 01-name.jpg"))
fmt.Printf(" %-16s %s\n", "", styleDim.Render(" %03d-name.jpg for 001-name.jpg, etc."))
fmt.Println(styleHeader.Render(" EXAMPLES "))
fmt.Println(styleWhite.Render(" nom lc pictures/*.jpg # Lowercase all .jpg files"))
fmt.Println(styleWhite.Render(" nom uc . # Uppercase all files (not extensions)"))
fmt.Println(styleWhite.Render(" nom num vacation/*.jpg # Batch number vacation photos"))
fmt.Println(styleWhite.Render(" nom num out/* -f img.png # img-1.png, img-2.png, etc."))
fmt.Println("")
}