-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_operations.go
664 lines (538 loc) · 14.6 KB
/
file_operations.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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
// This file contains file operations such as refresh, cd, move, copy, trash,
// open (os default app), remove, edit (EDITOR), rename, bulk rename, duplicate, mkdir,
package main
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"strings"
"path/filepath"
tea "github.com/charmbracelet/bubbletea"
)
type cdMsg string
type runFinishedMsg struct{ errok bool; cmd string; args []string; err error; stderr bytes.Buffer}
type runPluginFinishedMsg struct{ pluginpath string; statepath, cmdpath string; err error }
type refreshMsg int
type renameFinishedMsg string
type bulkRenameFinishedMsg struct { tmppath string; src_names []string }
type duplicateFinishedMsg string
type mkdirFinishedMsg string
func refresh() tea.Cmd {
return func () tea.Msg {
return refreshMsg(0)
}
}
func cd(path string) tea.Cmd {
return func () tea.Msg {
return cdMsg(path)
}
}
func (m *model) handleRefresh() (model, tea.Cmd) {
if m.mode == selectedMode {
m.viewport.SetContent(m.generateContent())
return *m, nil
}
// If files were moved or removed, the cursor needs to still be in range
ct := m.CurrentTab
var err error
ct.files, err = getDirEntries(ct.directory)
if (err != nil) {
if ct.directory == "/" {
log.Fatal("Cannot get contents of the root folder")
} else {
parent := filepath.Dir(ct.directory)
m.appendError("Error getting contents of "+ct.directory+". Folder may have been removed. Changing directory to "+parent+".")
return *m, cd(parent)
}
}
log.Printf("Read dir %s for tab %d", ct.directory, m.CurrentTabIndex)
ct.ReRunFilter()
log.Printf("Re-ran filter for tab %d", m.CurrentTabIndex)
// Don't change the cursor unless it's no longer valid
if ct.cursor == -1 {
if len(ct.filteredFiles) > 0 {
ct.cursor = 0;
}
} else {
ct.cursor = Min(len(ct.filteredFiles)-1, ct.cursor)
log.Printf("cursor: %d", ct.cursor)
}
//m.viewport.GotoTop()
m.viewport.SetContent(m.generateContent())
//m.checkScrollDown()
return *m, nil
}
// Most of the time a call to ChangeDirectory should be followed by a call to AddHistory
func (td *tabData) ChangeDirectory(path string) (error) {
log.Printf("ChangeDirectory %s", path)
path, err := filepath.Abs(path)
if err != nil {
return err
}
file_info, err := os.Stat(path)
if err != nil {
return err
}
if ! file_info.IsDir() {
return errors.New("Not a directory")
}
td.directory = path
td.absdir, _ = filepath.Abs(path)
td.files, err = getDirEntries(td.directory)
if (err != nil) {
log.Fatal("Cannot get contents of "+td.directory)
}
td.cursor = 0
// Maybe this should be an option SORT=keep or SORT=reset
//td.sort = modifiedSort
td.SetFilter("")
return nil
}
func (m *model) MoveFiles() tea.Cmd {
if len(m.selectedFiles) == 0 {
m.appendError("No files selected to move")
return nil
}
dst := m.CurrentTab.absdir
var paths []string
var errors []string
for _, sf := range(m.selectedFiles) {
if (sf.directory == m.CurrentTab.absdir) {
errors = append(errors, fmt.Sprintf("%s is already in %s", sf.file.Name(), dst))
} else {
src := fmt.Sprintf("%s/%s", sf.directory, sf.file.Name())
log.Printf("Moving %s to %s", src, dst)
paths = append(paths, src)
}
}
if len(errors) > 0 {
m.appendError(strings.Join(errors, "\n"))
return nil
} else {
args := append(paths, dst)
info := RunBlock("mv", args...)
if info.err != nil {
m.appendRunError("Error moving file(s)", info)
}
m.ClearSelections()
return refresh()
}
}
func (m *model) CopyFiles() tea.Cmd {
if len(m.selectedFiles) == 0 {
log.Println("No files selected to move")
return nil
}
dst := m.CurrentTab.absdir
var paths []string
var errors []string
for _, sf := range(m.selectedFiles) {
if (sf.directory == dst) {
errors = append(errors, fmt.Sprintf("%s is already in %s", sf.file.Name(), dst))
} else {
src := fmt.Sprintf("%s/%s", sf.directory, sf.file.Name())
log.Printf("Copying %s to %s", src, dst)
paths = append(paths, src)
}
}
if len(errors) > 0 {
m.appendError(strings.Join(errors, "\n"))
return nil
} else {
args := []string{"-r"}
args = append(args, paths...)
args = append(args, dst)
info := RunBlock("cp", args...)
if info.err != nil {
m.appendRunError("Error copying file(s)", info)
}
m.ClearSelections()
return refresh()
}
}
func (m *model) TrashFiles() tea.Cmd {
var paths []string
if len(m.selectedFiles) == 0 {
ct := m.CurrentTab
file := ct.filteredFiles[ct.cursor]
path := filepath.Join(ct.absdir, file.Name())
log.Printf("Trashing %s", path)
paths = append(paths, path)
} else {
for _, sf := range(m.selectedFiles) {
path := filepath.Join(sf.directory, sf.file.Name())
log.Printf("Trashing %s", path)
paths = append(paths, path)
}
}
info := RunBlock("trash", paths...)
if info.err != nil {
m.appendRunError("Error trashing file", info)
}
m.ClearSelections()
return refresh()
}
func (m *model) OpenFiles() tea.Cmd {
var paths []string
if len(m.selectedFiles) == 0 {
ct := m.CurrentTab
file := ct.filteredFiles[ct.cursor]
path := filepath.Join(ct.absdir, file.Name())
paths = append(paths, path)
} else {
for _, sf := range(m.selectedFiles) {
path := filepath.Join(sf.directory, sf.file.Name())
paths = append(paths, path)
}
}
args := append([]string{"--"}, paths...)
info := RunBlock("open", args...)
if info.err != nil {
m.appendRunError("Error opening file", info)
}
m.ClearSelections()
return refresh()
}
func (m *model) RemoveFiles() tea.Cmd {
var paths []string
if len(m.selectedFiles) == 0 {
ct := m.CurrentTab
file := ct.filteredFiles[ct.cursor]
path := filepath.Join(ct.absdir, file.Name())
log.Printf("Removing %s", path)
paths = append(paths, path)
} else {
for _, sf := range(m.selectedFiles) {
path := filepath.Join(sf.directory, sf.file.Name())
log.Printf("Removing %s", path)
paths = append(paths, path)
}
}
args := append([]string{"-rf", "--"}, paths...)
info := RunBlock("rm", args...)
if info.err != nil {
m.appendRunError("Error removing file", info)
}
m.ClearSelections()
return refresh()
}
// Allows user to specify name of new directory in EDITOR
func (m *model) MkDir() tea.Cmd {
ct := m.CurrentTab
tmpdir := os.Getenv("TMPDIR")
t, err := os.CreateTemp(tmpdir, "M-RENAME")
if err != nil {
log.Fatal(err)
}
if _, err := t.Write([]byte("NewDirectory\n")); err != nil {
log.Fatal(err)
}
if _, err := t.Write([]byte("; CWD: "+ct.directory+"\n")); err != nil {
log.Fatal(err)
}
for _, f := range ct.files {
if _, err := t.Write([]byte("; "+f.Name()+"\n")); err != nil {
log.Fatal(err)
}
}
if err := t.Close(); err != nil {
log.Fatal(err)
}
c := exec.Command(Editor(), t.Name()) //nolint:gosec
return tea.ExecProcess(c, func(err error) tea.Msg {
if (err == nil) {
return mkdirFinishedMsg(t.Name())
} else {
log.Printf("User cancelled rename with cq")
return refresh()
}
})
}
func (m *model) FinishMkDir(f string) tea.Cmd {
file, err := os.Open(f)
if err != nil {
m.appendError("Error opening temporary file "+f+":"+err.Error())
return nil
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
dir_name := scanner.Text()
i := strings.Index(dir_name, ";")
if i != -1 {
dir_name = dir_name[0:i]
}
dir_name = strings.TrimSpace(dir_name)
if dir_name != "" {
dst := filepath.Join(m.CurrentTab.absdir, dir_name)
err = os.Mkdir(dst, 0755)
if err != nil {
log.Printf(err.Error())
m.appendError("Error creating directory "+dir_name+":"+err.Error())
}
log.Printf("Made directory %s", dst)
}
}
os.Remove(f)
// when scanner.Scan returns false, check for error
if err := scanner.Err(); err != nil {
m.appendError("Error opening temporary file "+f+":"+err.Error())
return nil
}
return refresh()
}
// Allows user to specify new name of file in EDITOR
func (m *model) RenameFile() tea.Cmd {
ct := m.CurrentTab
hoveredFile := ct.filteredFiles[ct.cursor]
tmpdir := os.Getenv("TMPDIR")
t, err := os.CreateTemp(tmpdir, "M-RENAME")
if err != nil {
log.Fatal(err)
}
log.Printf("Created TMP File: %s", t.Name())
if _, err := t.Write([]byte(hoveredFile.Name()+"\n")); err != nil {
log.Fatal(err)
}
if _, err := t.Write([]byte("; CWD: "+ct.directory+"\n")); err != nil {
log.Fatal(err)
}
for _, f := range ct.files {
if f.Name() != hoveredFile.Name() {
if _, err := t.Write([]byte("; "+f.Name()+"\n")); err != nil {
log.Fatal(err)
}
}
}
if err := t.Close(); err != nil {
log.Fatal(err)
}
c := exec.Command(Editor(), t.Name()) //nolint:gosec
return tea.ExecProcess(c, func(err error) tea.Msg {
if (err == nil) {
return renameFinishedMsg(t.Name())
} else {
log.Printf("User cancelled rename with cq")
return refresh()
}
})
}
func (m *model) FinishRename(f string) tea.Cmd {
file, err := os.Open(f)
if err != nil {
m.appendError("Error opening temporary file "+f+":"+err.Error())
return nil
}
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Scan()
if err := scanner.Err(); err != nil {
m.appendError("Error opening temporary file "+f+":"+err.Error())
return nil
}
dst_name := scanner.Text()
os.Remove(f)
ct := m.CurrentTab
hoveredFile := ct.filteredFiles[ct.cursor]
src := filepath.Join(m.CurrentTab.absdir, hoveredFile.Name())
dst := filepath.Join(m.CurrentTab.absdir, dst_name)
os.Rename(src, dst)
log.Printf("Renamed %s to %s", hoveredFile.Name(), dst_name)
return refresh()
}
// Opens text document with EDITOR to allow for quick bulk renaming
func (m *model) BulkRename() tea.Cmd {
ct := m.CurrentTab
tmpdir := os.Getenv("TMPDIR")
t, err := os.CreateTemp(tmpdir, "M-BRENAME")
if err != nil {
log.Fatal(err)
}
log.Printf("Created TMP File: %s", t.Name())
src_names := []string{}
for _, f := range(ct.filteredFiles) {
if _, err := t.Write([]byte(f.Name()+"\n")); err != nil {
log.Fatal(err)
}
src_names = append(src_names, f.Name())
}
if _, err := t.Write([]byte("; CWD: "+ct.directory+"\n")); err != nil {
log.Fatal(err)
}
if err := t.Close(); err != nil {
log.Fatal(err)
}
c := exec.Command(Editor(), t.Name()) //nolint:gosec
return tea.ExecProcess(c, func(err error) tea.Msg {
if (err == nil) {
return bulkRenameFinishedMsg{t.Name(), src_names}
} else {
log.Printf("User cancelled rename with cq")
return refresh()
}
})
}
// TODO: Detect when a destination name is the same as a source name
func (m *model) FinishBulkRename(f string, src_names []string) tea.Cmd {
file, err := os.Open(f)
if err != nil {
m.appendError("Error opening temporary file "+f+":"+err.Error())
return nil
}
defer file.Close()
var dst_names []string
var issues []string
scanner := bufio.NewScanner(file)
for i := 0; scanner.Scan(); i++ {
if err := scanner.Err(); err != nil {
issues = append(issues, "Error reading temporary file "+f+":"+err.Error())
}
dst_name := scanner.Text()
commentPos := strings.Index(dst_name, ";")
if commentPos == -1 {
fmt.Printf("Testing dst_name: %s\n", dst_name)
if i < len(src_names) {
if src_names[i] != dst_name {
if Contains(src_names, dst_name) {
issues = append(issues, fmt.Sprintf("Destination %s is a source. Possible Loop.", dst_name))
}
}
}
dst_names = append(dst_names, dst_name)
}
}
if len(issues) > 0 {
m.appendError(strings.Join(issues, "\n"))
} else {
// Only perform the rename if there were no errors
for i, dst_name := range dst_names {
var errors []string
if i >= len(src_names) {
errors = append(errors, fmt.Sprintf("no src file name for line %d",i))
} else {
src_name := src_names[i]
if src_name != dst_name {
src := filepath.Join(m.CurrentTab.absdir, src_name)
dst := filepath.Join(m.CurrentTab.absdir, dst_name)
os.Rename(src, dst)
log.Printf("Renamed %s to %s", src_name, dst_name)
} else {
log.Printf("DEBUG: %s not renamed", src_name)
}
}
if len(errors) > 0 {
m.appendError(strings.Join(errors, "\n"))
}
}
return refresh()
}
return nil
}
func isFile(src string) bool {
stat, err := os.Stat(src)
if err != nil {
log.Fatal(err)
}
return stat.Mode().IsRegular()
}
func isDir(src string) bool {
stat, err := os.Stat(src)
if err != nil {
log.Fatal(err)
}
return stat.Mode().IsDir()
}
// Duplicates the hovered file after user specifies name with EDITOR
func (m *model) DuplicateFile() tea.Cmd {
ct := m.CurrentTab
hoveredFile := ct.filteredFiles[ct.cursor]
tmpdir := os.Getenv("TMPDIR")
t, err := os.CreateTemp(tmpdir, "M-DUP")
if err != nil {
log.Fatal(err)
}
log.Printf("Created TMP File: %s", t.Name())
if _, err := t.Write([]byte(hoveredFile.Name()+"\n")); err != nil {
log.Fatal(err)
}
if _, err := t.Write([]byte("; CWD: "+ct.directory+"\n")); err != nil {
log.Fatal(err)
}
for _, f := range ct.files {
if f.Name() != hoveredFile.Name() {
if _, err := t.Write([]byte("; "+f.Name()+"\n")); err != nil {
log.Fatal(err)
}
}
}
if err := t.Close(); err != nil {
log.Fatal(err)
}
c := exec.Command(Editor(), t.Name()) //nolint:gosec
return tea.ExecProcess(c, func(err error) tea.Msg {
if (err == nil) {
return duplicateFinishedMsg(t.Name())
} else {
log.Printf("User cancelled duplicate with cq")
return refresh()
}
})
}
func (m *model) FinishDuplicate(f string) tea.Cmd {
file, err := os.Open(f)
if err != nil {
m.appendError("Error opening temporary file "+f+":"+err.Error())
return nil
}
defer file.Close()
scanner := bufio.NewScanner(file)
scanner.Scan()
if err := scanner.Err(); err != nil {
m.appendError("Error reading temporary file "+f+":"+err.Error())
return nil
}
dst_name := scanner.Text()
os.Remove(f)
ct := m.CurrentTab
hoveredFile := ct.filteredFiles[ct.cursor]
src := filepath.Join(m.CurrentTab.absdir, hoveredFile.Name())
dst := filepath.Join(m.CurrentTab.absdir, dst_name)
if isFile(src) {
srcf, err := os.Open(src)
if err != nil {
m.appendError(fmt.Sprintf("Error opening %s", src))
return nil
}
defer srcf.Close()
dstf, err := os.Create(dst)
if err != nil {
m.appendError(fmt.Sprintf("Error opening %s", src))
return nil
}
defer dstf.Close()
_, err = io.Copy(dstf, srcf)
if err != nil {
m.appendError(fmt.Sprintf("Error copying %s to %s", src, dst))
return nil
}
log.Printf("Duplicated %s to %s", hoveredFile.Name(), dst_name)
return refresh()
} else if isDir(src) {
var args []string
args = append(args, "-r", src, dst)
info := RunBlock("cp", args...)
if info.err != nil {
m.appendRunError("Error duplicating file", info)
}
log.Printf("Duplicated %s to %s", src, dst)
return refresh()
} else {
m.appendError("Do not know how to duplicate file of this type")
return nil
}
}