-
Notifications
You must be signed in to change notification settings - Fork 0
/
actions.go
615 lines (537 loc) · 13.1 KB
/
actions.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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
package main
import (
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"path/filepath"
"slices"
"strconv"
"strings"
"unicode/utf8"
)
func (ts *terminalSession) quit() {
close(ts.done)
}
// For now the only thing that happens is clearing of the copy and cutFiles
func (ts *terminalSession) clearActions() {
ts.copyFile = ""
ts.cutFile = ""
ts.queueBottomBar()
}
func (ts *terminalSession) copy() {
fullPath := filepath.Join(ts.cwd, ts.cwdFiles[ts.selectionPos].Name())
ts.copyFile = fullPath
ts.cutFile = ""
ts.queueBottomBar()
}
func (ts *terminalSession) cut() {
fullPath := filepath.Join(ts.cwd, ts.cwdFiles[ts.selectionPos].Name())
ts.cutFile = fullPath
ts.copyFile = ""
ts.queueBottomBar()
}
func (ts *terminalSession) insertFile() {
ts.inputMode = true
defer func() { ts.inputMode = false }()
runeSlice := []rune{}
for {
ts.queueInputLine("Create new file: " + string(runeSlice))
ru := <-ts.inCh
if ru == inputMap["escape"] {
// Redraw the original bottomBar
ts.queueBottomBar()
return
}
if ru == inputMap["enter"] {
break
}
if ru == inputMap["backspace"] {
if len(runeSlice) == 0 {
continue
}
runeSlice = runeSlice[:len(runeSlice)-1]
} else {
runeSlice = append(runeSlice, ru)
}
}
name := string(runeSlice)
filename := filepath.Join(ts.cwd, name)
file, err := os.Create(filename)
if err != nil {
return
}
// Everyone can read, only owner can write
_ = file.Chmod(0o644)
ts.refreshFiles(name)
}
func (ts *terminalSession) insertDir() {
ts.inputMode = true
defer func() { ts.inputMode = false }()
runeSlice := []rune{}
for {
ts.queueInputLine("Create new directory: " + string(runeSlice))
ru := <-ts.inCh
if ru == inputMap["escape"] {
// Redraw the original bottomBar
ts.queueBottomBar()
return
}
if ru == inputMap["enter"] {
break
}
if ru == inputMap["backspace"] {
if len(runeSlice) == 0 {
continue
}
runeSlice = runeSlice[:len(runeSlice)-1]
} else {
runeSlice = append(runeSlice, ru)
}
}
name := string(runeSlice)
filename := filepath.Join(ts.cwd, name)
// Only owner can write, read and execute for everyone
err := os.Mkdir(filename, 0o755)
if err != nil {
ts.queueBottomBar()
return
}
ts.refreshFiles(name)
}
func (ts *terminalSession) paste() {
// If both are empty we do nothing
if ts.cutFile == "" && ts.copyFile == "" {
return
}
source := ts.cutFile + ts.copyFile
destination := ts.cwd
// Copy the file(s) here
sourceInfo, err := os.Stat(source)
if err != nil {
return
}
name := filepath.Base(source)
fileName := filepath.Join(destination, name)
// Only actually copy or paste if the source and destination differ
if source != fileName {
if sourceInfo.IsDir() {
copyDir(source, fileName)
} else {
copyFile(source, fileName)
}
// Only in the case of cutFile will we also remove the original
if ts.cutFile != "" {
err := os.RemoveAll(ts.cutFile)
if err != nil {
return
}
}
}
// Empty the copy and cutFiles
ts.cutFile = ""
ts.copyFile = ""
ts.refreshFiles(name)
}
// Recursive copying function
func copyDir(src, dst string) error {
return filepath.Walk(src, func(path string, info fs.FileInfo, err error) error {
if err != nil {
return err
}
// copy to this path
outpath := filepath.Join(dst, strings.TrimPrefix(path, src))
if info.IsDir() {
os.MkdirAll(outpath, info.Mode())
return nil // means recursive
}
return copyFile(path, outpath)
})
}
func copyFile(src, outpath string) error {
info, err := os.Stat(src)
if err != nil {
return err
}
// handle irregular files
if !info.Mode().IsRegular() {
switch info.Mode().Type() & os.ModeType {
case os.ModeSymlink:
link, err := os.Readlink(src)
if err != nil {
return err
}
return os.Symlink(link, outpath)
}
return nil
}
// copy contents of regular file efficiently
// open input
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
// create output
fh, err := os.Create(outpath)
if err != nil {
return err
}
defer fh.Close()
// make it the same
fh.Chmod(info.Mode())
// copy content
_, err = io.Copy(fh, in)
return err
}
func (ts *terminalSession) open() {
// This will open up a terminal session in a new terminal window
// This is not ideal, but it's impossible to change the cwd of a parent process
ts.mu.Lock()
defer ts.mu.Unlock()
selection, err := ts.cwdFiles[ts.selectionPos].Info()
if err != nil {
return
}
filePath := filepath.Join(ts.cwd, selection.Name())
// HACK:
// Get the current terminal
// Get parent PID of current process (the shell)
ppid := strconv.Itoa(os.Getppid())
// Get parent PID of the shell (the terminal)
statusPath := filepath.Join("/proc", ppid, "status")
dataBytes, err := os.ReadFile(statusPath)
if err != nil {
return
}
data := string(dataBytes)
gppidStart := strings.Index(data, "PPid: ") + len("PPid: ")
gppidEnd := strings.Index(data[gppidStart:], "\n")
gppid := data[gppidStart : gppidStart+gppidEnd]
// Get grandparent PID's name (name of the terminal)
statusPath = filepath.Join("/proc", gppid, "status")
dataBytes, err = os.ReadFile(statusPath)
if err != nil {
return
}
data = string(dataBytes)
termStart := strings.Index(data, "Name: ") + len("Name: ")
termEnd := strings.Index(data[termStart:], "\n")
term := data[termStart : termStart+termEnd]
fmt.Fprintln(os.Stderr, gppid)
if selection.Mode()&os.ModeSymlink != 0 {
link, err := filepath.EvalSymlinks(filePath)
if err == nil {
linkInfo, err := os.Stat(link)
if err == nil {
selection = linkInfo
filePath = link
}
}
}
// If selection is a directory open a new terminal window in that directory
if selection.IsDir() {
os.Chdir(filePath)
cmd := exec.Command(term)
cmd.Run()
return
}
// If selection is a valid utf8 encoded file open in default editor
b, _ := os.ReadFile(filePath)
fileContent := string(b)
if utf8.ValidString(fileContent) {
// Get the default editor
editor := os.Getenv("EDITOR")
if editor == "" {
editor = "vim"
}
cmd := exec.Command(term, "-e", editor, filePath)
cmd.Run()
return
}
// Code for executables:
cmd := exec.Command(term, "-e", filePath)
cmd.Run()
}
func (ts *terminalSession) delete() {
ts.inputMode = true
defer func() { ts.inputMode = false }()
runeSlice := []rune{}
selectionName := ts.cwdFiles[ts.selectionPos].Name()
confirmText := "Confirm deletion of \""
if ts.cwdFiles[ts.selectionPos].IsDir() {
confirmText = "Confirm recursive deletion of \""
}
keys := "\" [y(es), n(o)]: "
for {
for {
ts.queueInputLine(confirmText + selectionName + keys + string(runeSlice))
ru := <-ts.inCh
if ru == inputMap["escape"] {
// Redraw the original bottomBar
ts.queueBottomBar()
return
}
if ru == inputMap["enter"] {
break
}
if ru == inputMap["backspace"] {
if len(runeSlice) == 0 {
continue
}
runeSlice = runeSlice[:len(runeSlice)-1]
} else {
runeSlice = append(runeSlice, ru)
}
}
cmd := string(runeSlice)
// Stay in the loop until we say y/yes/n/no
if strings.ToLower(cmd) == "y" || strings.ToLower(cmd) == "yes" {
break
} else if strings.ToLower(cmd) == "n" || strings.ToLower(cmd) == "no" {
ts.queueBottomBar()
return
}
runeSlice = nil
}
selectionPath := filepath.Join(ts.cwd, selectionName)
err := os.RemoveAll(selectionPath)
if err != nil {
return
}
destFile := ""
if ts.selectionPos < len(ts.cwdFiles)-1 {
destFile = ts.cwdFiles[ts.selectionPos+1].Name()
}
ts.refreshFiles(destFile)
}
func (ts *terminalSession) rename() {
ts.inputMode = true
defer func() { ts.inputMode = false }()
runeSlice := []rune{}
for {
ts.queueInputLine("Rename: " + string(runeSlice))
ru := <-ts.inCh
if ru == inputMap["escape"] {
// Redraw the original bottomBar
ts.queueBottomBar()
return
}
if ru == inputMap["enter"] {
break
}
if ru == inputMap["backspace"] {
if len(runeSlice) == 0 {
continue
}
runeSlice = runeSlice[:len(runeSlice)-1]
} else {
runeSlice = append(runeSlice, ru)
}
}
name := string(runeSlice)
selectionName := ts.cwdFiles[ts.selectionPos].Name()
oldPath := filepath.Join(ts.cwd, selectionName)
newPath := filepath.Join(ts.cwd, name)
os.Rename(oldPath, newPath)
ts.refreshFiles(ts.cwdFiles[ts.selectionPos].Name())
}
func (ts *terminalSession) search() {
// TODO: Add regex to the search methods
ts.inputMode = true
defer func() { ts.inputMode = false }()
runeSlice := []rune{}
for {
ts.queueInputLine("Search: " + string(runeSlice))
ru := <-ts.inCh
if ru == inputMap["escape"] {
// Redraw the original bottomBar
ts.queueBottomBar()
// Reset the highlights
ts.queueMainFiles()
return
}
if ru == inputMap["enter"] {
break
}
if ru == inputMap["backspace"] {
if len(runeSlice) == 0 {
continue
}
runeSlice = runeSlice[:len(runeSlice)-1]
} else {
runeSlice = append(runeSlice, ru)
}
// Reset the highlights
ts.queueMainFiles()
// Add highlights to all matching strings
ts.searchStr = string(runeSlice)
for i, file := range ts.cwdFiles {
fileStr := strings.ToLower(file.Name())
searchStr := strings.ToLower(ts.searchStr)
if strI := strings.Index(fileStr, searchStr); strI >= 0 {
// Get the part of the string from the original filename to make cases match
line := file.Name()[strI : strI+len(searchStr)]
// Style the highlight
// TODO: Change the yellow background?
line = StyleBgYellow + StyleFgBlack + line + StyleReset
drawInstr := drawInstruction{
// +4 because of spaces + icons
x: strI + 4,
y: i - ts.mainOffset,
line: line,
}
ts.drawQueue = append(ts.drawQueue, drawInstr)
}
}
}
ts.searchN()
}
func (ts *terminalSession) searchN() {
if ts.searchStr == "" {
return
}
found := false
// first search after the current selection
for i := ts.selectionPos + 1; i < len(ts.cwdFiles); i++ {
// For now we ignore char casing
fileStr := strings.ToLower(ts.cwdFiles[i].Name())
searchStr := strings.ToLower(ts.searchStr)
if strings.Contains(fileStr, searchStr) {
ts.selectionPos = i
found = true
break
}
}
if !found {
// then search from beginning up to current selection
for i := 0; i <= ts.selectionPos; i++ {
// For now we ignore char casing
fileStr := strings.ToLower(ts.cwdFiles[i].Name())
searchStr := strings.ToLower(ts.searchStr)
if strings.Contains(fileStr, searchStr) {
ts.selectionPos = i
found = true
break
}
}
}
if !found {
line := StyleFgRed + "Pattern not found: " + ts.searchStr + StyleReset
ts.queueInputLine(line)
return
}
ts.refreshQueue()
ts.queueInputLine("Search: " + ts.searchStr)
}
func (ts *terminalSession) searchP() {
if ts.searchStr == "" {
return
}
found := false
for i := ts.selectionPos - 1; i >= 0; i-- {
// For now we ignore char casing
fileStr := strings.ToLower(ts.cwdFiles[i].Name())
searchStr := strings.ToLower(ts.searchStr)
if strings.Contains(fileStr, searchStr) {
ts.selectionPos = i
found = true
break
}
}
if !found {
for i := len(ts.cwdFiles) - 1; i >= ts.selectionPos; i-- {
// For now we ignore char casing
fileStr := strings.ToLower(ts.cwdFiles[i].Name())
searchStr := strings.ToLower(ts.searchStr)
if strings.Contains(fileStr, searchStr) {
ts.selectionPos = i
found = true
break
}
}
}
if !found {
line := StyleFgRed + "Pattern not found: " + ts.searchStr + StyleReset
ts.queueInputLine(line)
return
}
ts.refreshQueue()
ts.queueInputLine("Search: " + ts.searchStr)
}
func (ts *terminalSession) terminalCommand() {
ts.inputMode = true
defer func() { ts.inputMode = false }()
// Get the default terminal
terminal := os.Getenv("TERM")
if terminal == "" {
return
}
os.Chdir(ts.cwd)
cwd := ts.cwd
homeDir, err := os.UserHomeDir()
var cut bool
// Only try to cut prefix if a homeDir was found
if err == nil {
cwd, cut = strings.CutPrefix(cwd, homeDir)
// Only add tilde if a prefix was cut
if cut {
cwd = "~" + cwd
}
}
consoleString := StyleFgBlue + cwd + StyleFgGreen + " ❱ " + StyleReset
runeSlice := []rune{}
for {
ts.queueInputLine(consoleString + string(runeSlice))
ru := <-ts.inCh
if ru == inputMap["escape"] {
// Redraw the original bottomBar
ts.queueBottomBar()
// Reset the highlights
ts.queueMainFiles()
return
}
if ru == inputMap["enter"] {
break
}
if ru == inputMap["backspace"] {
if len(runeSlice) == 0 {
continue
}
runeSlice = runeSlice[:len(runeSlice)-1]
} else {
runeSlice = append(runeSlice, ru)
}
}
splitCmd := strings.Split(string(runeSlice), " ")
name := splitCmd[0]
args := []string{}
if len(splitCmd) > 1 {
args = splitCmd[1:]
}
cmd := exec.Command(name, args...)
err = cmd.Run()
if err != nil {
// If command fails only redraw bottom bar
ts.queueBottomBar()
fmt.Fprintf(os.Stderr, "Error executing command: %v", err)
return
}
ts.refreshFiles(ts.cwdFiles[ts.selectionPos].Name())
}
func (ts *terminalSession) refreshFiles(name string) {
cwdFiles, err := os.ReadDir(ts.cwd)
if err != nil {
return
}
ts.cwdFiles = ts.sortFunc(cwdFiles)
if name != "" {
ts.selectionPos = slices.IndexFunc(ts.cwdFiles, func(dir fs.DirEntry) bool {
return dir.Name() == name
})
} else {
ts.selectionPos = 0
}
ts.refreshQueue()
}