-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.go
540 lines (490 loc) · 14 KB
/
utils.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
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode/utf8"
)
var separator = string(filepath.Separator)
var gCommandHelp = map[string]interface{}{
"-help": struct{}{},
"-h": struct{}{},
}
var gCommandPlain = map[string]interface{}{
"-plain": struct{}{},
"-p": struct{}{},
}
var gCommandTime = map[string]interface{}{
"-time": struct{}{},
"-t": struct{}{},
}
var gCommandCount = map[string]interface{}{
"-count": struct{}{},
"-c": struct{}{},
}
var gCommands = map[string]interface{}{
"-help": struct{}{},
"-h": struct{}{},
"-plain": struct{}{},
"-p": struct{}{},
"-time": struct{}{},
"-t": struct{}{},
}
var gInstructions = []string{
"|------------------------ Instructions ------------------------|",
"| 1. Press ESC to quit. |",
"| 2. Press ↑ or ↓ to select a file. |",
"| 3. Press ← or → to switch screen. |",
"| 4. Press Enter to open the selected file. |",
"| 5. Press Space to open the selected file's Directory. |",
"| 6. Add -p to search the plain first layer Directory. |",
"| 7. Add -t to display files in update time order. |",
"| 8. Add -cx to search the first x files and stop. |",
"|--------------------------------------------------------------|"}
var gMenu = []string{
" +------------------------+ ",
" | Info [I] | ",
" | Rename [R] | ",
" | Delete [D] | ",
" | Parent Folder [P] | ",
" | Close [C] | ",
" +------------------------+ ",
}
func printHelpInstructions() {
for _, value := range gInstructions {
fmt.Println(value)
}
}
func isArgHelp(s string) bool {
_, exists := gCommandHelp[s]
if exists {
return true
}
return false
}
func isArgPlain(s string) bool {
_, exists := gCommandPlain[s]
if exists {
return true
}
return false
}
func isArgTime(s string) bool {
_, exists := gCommandTime[s]
if exists {
return true
}
return false
}
func getSearchCount(s string) int {
count := 0
for key, _ := range gCommandCount {
if strings.HasPrefix(s, key) {
count, _ = strconv.Atoi(s[len(key):])
if count > 0 {
return count
}
}
}
return count
}
func getTerminalColumns() (int, error) {
var cols int
cmd := exec.Command("tput", "cols")
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
out, err := cmd.Output()
if err == nil {
cols, err = strconv.Atoi(strings.TrimSpace(string(out)))
}
return cols, err
}
func getTerminalRows() (int, error) {
var cols int
cmd := exec.Command("tput", "lines")
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
out, err := cmd.Output()
if err == nil {
cols, err = strconv.Atoi(strings.TrimSpace(string(out)))
}
return cols, err
}
func getTerminalColumnsAndRows() {
cols, err := getTerminalColumns()
if err != nil {
cols = 0
}
rows, err := getTerminalRows()
if err != nil {
rows = 0
}
if cols == 0 {
cols = 80
}
if rows == 0 {
rows = 24
}
gTerminalState.TerminalColumnNumber = cols
gTerminalState.TerminalRowNumber = rows
}
func getCommandState() {
args := os.Args[1:]
argsLength := len(args)
if argsLength == 0 {
return
}
argsForSearchPattern := make([]string, 0, argsLength)
for _, arg := range args {
_, exists := gCommands[arg]
if exists {
switch {
case isArgPlain(arg):
gCommandState.Plain = true
case isArgHelp(arg):
gCommandState.Help = true
case isArgTime(arg):
gCommandState.Time = true
}
} else {
searchCount := getSearchCount(arg)
if searchCount > 0 {
gCommandState.Count.CountSwitch = true
gCommandState.Count.CountNumber = searchCount
} else {
argsForSearchPattern = append(argsForSearchPattern, arg)
}
}
}
var patternBuilder strings.Builder
length := len(argsForSearchPattern)
for index, value := range argsForSearchPattern {
patternBuilder.WriteString(strings.Replace(value, ".", "\\.", -1))
if index < length-1 {
patternBuilder.WriteString(".*")
}
}
gCommandState.SearchPattern = patternBuilder.String()
}
func getScreenLineNumber() {
if !gCommandState.Help {
// 命令不包含help
gTerminalState.SwitchScreenLines = gTerminalState.TerminalRowNumber - 2
} else {
// 命令包含help
gTerminalState.SwitchScreenLines = gTerminalState.TerminalRowNumber - 2 - len(gInstructions)
}
}
func truncateString(input string, maxLength int) string {
if len(input) <= maxLength {
return input
}
// 中间四个....
halfMaxLength := maxLength/2 - 2
runeSlice := []rune(input)
leftRuneByteLength := 0
rightRuneByteLength := 0
var leftRuneSlice []rune
var rightRuneSlice []rune
for i, r := range runeSlice {
byteLength := utf8.RuneLen(r)
leftRuneByteLength = leftRuneByteLength + byteLength
if leftRuneByteLength >= halfMaxLength {
leftRuneSlice = runeSlice[0:i]
break
}
}
for i := len(runeSlice) - 1; i >= 0; i-- {
r := runeSlice[i]
byteLength := utf8.RuneLen(r)
rightRuneByteLength = rightRuneByteLength + byteLength
if rightRuneByteLength >= halfMaxLength {
rightRuneSlice = runeSlice[i+1:]
break
}
}
return string(leftRuneSlice) + "...." + string(rightRuneSlice)
}
func ceil(numerator int, denominator int) int {
result := numerator / denominator
remainder := numerator % denominator
if remainder > 0 {
result++
}
return result
}
func moveCursorToPreviousNthLines(nth int) {
if nth > 0 {
fmt.Print("\033[")
fmt.Print(nth)
fmt.Print("F")
}
}
func jumpCursorToCertainLine(destLineIndex int) {
if destLineIndex < gTerminalState.SelectedLineIndex {
moveCursorToPreviousNthLines(gTerminalState.SelectedLineIndex - destLineIndex)
} else {
moveCursorToNextNthLines(destLineIndex - gTerminalState.SelectedLineIndex)
}
}
func moveCursorToNextNthLines(nth int) {
fmt.Print("\033[") // ANSI escape code to move the cursor down one line
fmt.Print(nth)
fmt.Print("B")
}
func clearPreviousNthLine(nth int) {
fmt.Print("\033[")
fmt.Print(nth)
fmt.Print("F") // ANSI escape code to move the cursor up
fmt.Print("\033[2K") // ANSI escape code to clear the line
}
func clearCurrentLine() {
fmt.Print("\033[2K") // ANSI escape code to clear the line
fmt.Print("\r")
}
func moveCursorToColumnIndex(columnIndex int) {
fmt.Print("\r")
fmt.Printf("\033[%dC", columnIndex)
}
func moveCursorToLeft() {
fmt.Print("\r")
}
func clearNextLine() {
fmt.Print("\033[1B") // ANSI escape code to move the cursor down one line
fmt.Print("\033[2K") // ANSI escape code to clear the line
}
func clearNextNthLine(nth int) {
fmt.Print("\033[") // ANSI escape code to move the cursor down one line
fmt.Print(nth)
fmt.Print("B")
fmt.Print("\033[2K") // ANSI escape code to clear the line
}
func printContentLineWithUnselectedDisplayName(selectedGroupIndex int, selectedLineIndex int) {
fmt.Print(getUnselectedDisplayFileNameByIndex(gSearchData.FileDataArr, selectedGroupIndex, selectedLineIndex))
}
func printSelectedMenuLevel1Line(selectedMenuIndex int) {
selectedMenuLine := addStringIntoAString(gMenu[selectedMenuIndex], 3, ">>")
fmt.Print(selectedMenuLine)
}
func printUnselectedMenuLevel1Line(selectedMenuIndex int) {
fmt.Print(gMenu[selectedMenuIndex])
}
func printContentLineWithSelectedDisplayName(selectedGroupIndex int, selectedLineIndex int) {
fmt.Print(getSelectedDisplayFileNameByIndex(gSearchData.FileDataArr, selectedGroupIndex, selectedLineIndex))
fmt.Print("\r")
}
func onlyPrintHelpInstructions() bool {
if len(gCommandState.SearchPattern) == 0 &&
gCommandState.Help &&
!gCommandState.Plain &&
!gCommandState.Time {
return true
}
return false
}
func printCurrentDirFiles(reg *regexp.Regexp) {
currentDir, err := os.Getwd()
if err != nil {
fmt.Println("Error:", err)
return
}
if gCommandState.Plain {
// 只搜索第一层
files, err := os.ReadDir(currentDir)
if err != nil {
fmt.Println("Error:", err)
return
}
printCurrentSearchingDirectory(currentDir)
for _, file := range files {
fileName := file.Name()
fileInfo, err := file.Info()
if err != nil {
fmt.Println("Error:", err)
return
}
prepareMatchedFileInfo(reg, fileName, &fileInfo)
if gCommandState.Count.CountSwitch {
if len(gSearchData.FileDataArr) >= gCommandState.Count.CountNumber {
break
}
}
}
clearCurrentLine()
} else {
// 搜索遍历所有层级
// path 有可能是文件夹,也有可能是文件
// currentDir、path 均为全路径
err = filepath.Walk(currentDir, func(path string, fileInfo os.FileInfo, err error) error {
if path == currentDir {
return nil
}
if err != nil {
fmt.Print("ERROR occurred:", err)
time.Sleep(time.Second)
clearCurrentLine()
return nil
}
filePath := path
if len(currentDir) == 1 {
filePath = path[1:]
} else if len(path) > len(currentDir)+1 {
filePath = path[len(currentDir)+1:]
}
prepareMatchedFileInfo(reg, filePath, &fileInfo)
splits := strings.Split(filePath, separator)
if fileInfo.IsDir() {
if len(splits[0]) > 0 {
printCurrentSearchingDirectory(currentDir + "/" + splits[0] + "/")
} else {
printCurrentSearchingDirectory(currentDir + "/")
}
} else {
if len(splits) > 1 {
printCurrentSearchingDirectory(currentDir + "/" + splits[1] + "/")
} else {
printCurrentSearchingDirectory(currentDir + "/")
}
}
if gCommandState.Count.CountSwitch {
if len(gSearchData.FileDataArr) >= gCommandState.Count.CountNumber {
return filepath.SkipDir
}
}
return nil
})
clearCurrentLine()
}
// 按照时间排序
if gCommandState.Time {
sort.Sort(FileDataSlice(gSearchData.FileDataArr))
}
prepareMatchedFileNameGroup()
displayCurrentFileNamesForFirstTime()
}
func displayCurrentFileNamesForFirstTime() {
// 获取一屏幕
gTerminalState.SelectedGroupIndex = 0
gTerminalState.SelectedLineIndex = 0
currentScreenFileNames := getSelectedGroupDisplayFileNames(gSearchData.DisplayFileNamesInGroup)
for _, value := range currentScreenFileNames {
fmt.Println(value)
}
}
func getSelectedGroupDisplayFileNamesLength(displayFileNamesInGroup [][]string) int {
if len(displayFileNamesInGroup) == 0 {
return 0
}
return len(displayFileNamesInGroup[gTerminalState.SelectedGroupIndex])
}
func getGroupLength(displayFileNamesInGroup [][]string) int {
return len(displayFileNamesInGroup)
}
func getSelectedGroupDisplayFileNames(displayFileNamesInGroup [][]string) []string {
if len(displayFileNamesInGroup) == 0 {
return nil
}
return displayFileNamesInGroup[gTerminalState.SelectedGroupIndex]
}
func prepareMatchedFileNameGroup() {
groupLength := ceil(len(gSearchData.FileDataArr), gTerminalState.SwitchScreenLines)
for i := 0; i < groupLength; i++ {
oneScreenContent := make([]string, 0, gTerminalState.SwitchScreenLines)
for j := 0; j < gTerminalState.SwitchScreenLines; j++ {
indexOfFileName := i*gTerminalState.SwitchScreenLines + j
if indexOfFileName < len(gSearchData.FileDataArr) {
oneScreenContent = append(oneScreenContent, gSearchData.FileDataArr[indexOfFileName].DisplayFileName)
} else {
break
}
}
gSearchData.DisplayFileNamesInGroup = append(gSearchData.DisplayFileNamesInGroup, oneScreenContent)
}
if groupLength == 0 {
gTerminalState.MaxLineLength = 0
} else if groupLength == 1 {
gTerminalState.MaxLineLength = len(gSearchData.FileDataArr)
} else {
gTerminalState.MaxLineLength = gTerminalState.SwitchScreenLines
}
}
func prepareMatchedFileInfo(reg *regexp.Regexp, filePath string, fileInfo *os.FileInfo) {
prefix := "[F]"
if (*fileInfo).IsDir() {
prefix = "[D]"
}
if reg == nil {
displayFileName := prefix + " " + getDisplayFileName(filePath)
fileData := FileData{
DisplayFileName: displayFileName,
FilePath: filePath,
Time: (*fileInfo).ModTime(),
}
gSearchData.FileDataArr = append(gSearchData.FileDataArr, fileData)
} else {
match := reg.MatchString((*fileInfo).Name())
if match {
displayFileName := prefix + " " + getDisplayFileName(filePath)
fileData := FileData{
DisplayFileName: displayFileName,
FilePath: filePath,
Time: (*fileInfo).ModTime(),
}
gSearchData.FileDataArr = append(gSearchData.FileDataArr, fileData)
}
}
}
func getDisplayFileName(fileName string) string {
return truncateString(fileName, (gTerminalState.TerminalColumnNumber-4)*9/10)
}
func addStringIntoAString(originalStr string, insertedIndex int, insertedString string) string {
return originalStr[0:insertedIndex] + insertedString + originalStr[insertedIndex+len(insertedString):]
}
func getSelectedDisplayFileNameByIndex(arr []FileData, selectedGroupIndex int, selectedLineIndex int) string {
return addStringIntoAString(arr[selectedGroupIndex*gTerminalState.SwitchScreenLines+selectedLineIndex].DisplayFileName, 4, ">")
}
func getUnselectedDisplayFileNameByIndex(arr []FileData, selectedGroupIndex int, selectedLineIndex int) string {
return arr[selectedGroupIndex*gTerminalState.SwitchScreenLines+selectedLineIndex].DisplayFileName
}
func openCurrentFile() int {
currentDir, err := os.Getwd()
if err != nil {
fmt.Println("Error:", err)
return 1
}
fileName := filepath.Join(currentDir, gSearchData.FileDataArr[gTerminalState.SelectedGroupIndex*gTerminalState.SwitchScreenLines+gTerminalState.SelectedLineIndex].FilePath)
cmd := exec.Command("open", fileName)
// 获取命令的输出
_, err = cmd.CombinedOutput()
if err != nil {
fmt.Println("Error occurred when executing command: open", fileName)
return 2
}
return 0
}
func openCurrentFilesParentDir() int {
currentDir, err := os.Getwd()
if err != nil {
fmt.Println("Error:", err)
return 1
}
fileName := filepath.Dir(filepath.Join(currentDir, gSearchData.FileDataArr[gTerminalState.SelectedGroupIndex*gTerminalState.SwitchScreenLines+gTerminalState.SelectedLineIndex].FilePath))
cmd := exec.Command("open", fileName)
// 获取命令的输出
_, err = cmd.CombinedOutput()
if err != nil {
fmt.Println("Error occurred when executing command: open", fileName)
return 2
}
return 0
}
func printCurrentSearchingDirectory(path string) {
clearCurrentLine()
fmt.Print(getDisplayFileName("Searching Folder: " + path))
}