-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
456 lines (378 loc) · 10.3 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
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
package main
// See notes/file-manager-requirements
import (
"errors"
"fmt"
"log"
"os"
"os/user"
"path/filepath"
"strings"
//"runtime/debug"
"github.com/charmbracelet/bubbles/progress"
tea "github.com/charmbracelet/bubbletea"
)
var version = "undefined"
type panicMsg error
var helpPath string
var home string
// This will return a tea command that when run will log an error and gracefully exit the bubbletea application
func panic(err error) tea.Cmd {
return func () tea.Msg {
return panicMsg(err)
}
}
func ClearLastd() {
lastdpath := filepath.Join(home,".local", "state", "bfm.lastd")
if _, err := os.Stat(lastdpath); errors.Is(err, os.ErrNotExist) {
return
}
err := os.Remove(lastdpath)
if err != nil {
log.Printf("Error removing bfm.lastd: "+err.Error())
}
}
func (m *model) writeLastd() {
ct := m.CurrentTab
d1 := []byte(ct.directory)
err := os.WriteFile(filepath.Join(home,".local", "state", "bfm.lastd"), d1, 0644)
if err != nil {
log.Fatal(err)
}
}
func (m model) Update(message tea.Msg) (tea.Model, tea.Cmd) {
log.Printf("DEBUG: Proccessing message %T", message)
ct := m.CurrentTab
switch msg := message.(type) {
case tea.WindowSizeMsg:
m.handleResize(msg)
case cdMsg:
dir := string(msg)
err := ct.ChangeDirectory(dir)
if err != nil {
m.appendError("Error cding to "+dir+". Folder may have been removed. Changing directory to root.")
return m, cd("/")
} else {
ct.AddHistory(dir)
m.viewport.SetContent(m.generateContent())
m.viewport.GotoTop()
}
case selectFileMsg:
ct.JumpToFile(string(msg))
m.viewport.SetContent(m.generateContent())
m.checkScrollDown()
case tabMsg:
wasActive := m.SelectTab(int(msg) - 1)
if !wasActive {
// cd will read files, reset filter and viewport
return m, cd(ct.directory)
} else {
return m, refresh()
}
case panicMsg:
log.Printf("Fatal Error: %s", msg)
return m, tea.Quit
case runFinishedMsg:
if !msg.errok && msg.err != nil {
return m, m.HandleRunError(msg)
}
return m.handleRefresh()
case runPluginFinishedMsg:
if msg.err != nil {
log.Printf("error running %s: %s", msg.pluginpath, msg.err)
return m, tea.Quit
}
return m, m.runPluginCommands(msg.cmdpath)
case renameFinishedMsg:
return m, m.FinishRename(string(msg))
case bulkRenameFinishedMsg:
return m, m.FinishBulkRename(msg.tmppath, msg.src_names)
case duplicateFinishedMsg:
return m, m.FinishDuplicate(string(msg))
case mkdirFinishedMsg:
return m, m.FinishMkDir(string(msg))
case refreshMsg:
return m.handleRefresh()
case tea.KeyMsg:
// Having errors is like it's own mode
// Any key will clear one error
if len(m.errors) > 0 {
// trash first error
m.errors = m.errors[1:]
return m, refresh()
}
if m.mode == commandMode {
log.Printf("DEBUG: Key %s", msg.String())
switch msg.String() {
//Application
case "q", "ctrl+c":
return m, m.CloseTab()
case "?":
// -I Case-Insensitive Searching
// -R Raw characters (for color support in terminals)
return m, Run(false, ct.directory, "bash", "-c", fmt.Sprintf("LESS=IR less '%s'", helpPath))
case "1":
return m, tab(1)
case "2":
return m, tab(2)
case "3":
return m, tab(3)
case "4":
return m, tab(4)
case "5":
return m, tab(5)
case "6":
return m, tab(6)
case "ctrl+s": // View selected files
m.mode = selectedMode
return m, refresh()
// Filterning
case "/":
m.mode = filterMode
return m, nil
case "ctrl+l":
// Don't use SetFilter, because we don't need to re-sort before we refresh
ct.filter = ""
//m.viewport.GotoTop()
return m.handleRefresh()
//Cursor Movement
case "j", "down":
m.MoveCursor(1)
case "k", "up":
m.MoveCursor(-1)
case "g":
m.MoveCursorTop()
case "G":
m.MoveCursorBottom()
case "ctrl+d":
m.MoveCursor(m.viewportHeight / 2)
case "ctrl+u":
m.MoveCursor(-(m.viewportHeight / 2))
case "]":
m.MoveNextSelected()
case "[":
m.MovePrevSelected()
// Navigation
case "h", "-", "backspace":
// Go up a directory
return m, cd(filepath.Dir(ct.directory))
case "l", "enter":
if m.isHoveredDir() {
return m, cd(m.getHoveredPath())
}
case "~":
usr, _ := user.Current()
return m, cd(usr.HomeDir)
case "ctrl+o":
return m, m.GoHistoryBack()
case "tab": // "ctrl+i" issues tab
return m, m.GoHistoryForward()
case "a":
home := os.Getenv("HOME")
return m, m.RunPlugin(filepath.Join(home, ".config/bfm/plugins/fzcd"))
// Pressing ctrl+/ sends ctrl+_ on VT102 compatible terminals such as iTerm2 and alacritty
case "ctrl+_": // Jump to sub file/dir by FZF selection
home := os.Getenv("HOME")
return m, m.RunPlugin(filepath.Join(home, ".config/bfm/plugins/fzjump"))
case "J": // autojump (I'm feeling lucky)
home := os.Getenv("HOME")
return m, m.RunPlugin(filepath.Join(home, ".config/bfm/plugins/autojump"))
case "ctrl+j": // fzf on autojump results
home := os.Getenv("HOME")
return m, m.RunPlugin(filepath.Join(home, ".config/bfm/plugins/autojump"), "FZF")
// Sorting
case "n":
ct.SetSort(nameSort)
m.viewport.GotoTop()
case "m":
ct.SetSort(modifiedSort)
m.viewport.GotoTop()
case "z":
ct.SetSort(sizeSort)
m.viewport.GotoTop()
// Selection
case "s": // Select
m.ToggleSelected()
m.MoveCursor(1)
case "A":
return m, m.SelectAll()
case "d":
return m, m.DeselectAll()
// Operations
case "v":
return m, m.MoveFiles()
case "p":
return m, m.CopyFiles()
case "o": // Open
return m, m.OpenFiles()
case "P": // Open with Preview.app
home := os.Getenv("HOME")
return m, m.RunPlugin(filepath.Join(home, ".config/bfm/plugins/preview"))
case "e": // Edit
if os.Getenv("TMUX") != "" {
tmuxcmd := Editor()+" \""+ct.filteredFiles[ct.cursor].Name()+"\""
return m, Run(false, ct.directory, "tmux", "new-window", "-n", Editor(), tmuxcmd)
} else {
return m, Run(false, ct.directory, Editor(), ct.filteredFiles[ct.cursor].Name())
}
case "N":
return m, m.MkDir()
case "D":
return m, m.DuplicateFile()
case "R":
return m, m.RenameFile()
case "ctrl+r":
return m, m.BulkRename()
case "T":
// https://github.com/morgant/tools-osx
return m, m.TrashFiles()
case "X":
return m, m.RemoveFiles()
case "F": // Finder
// User may need to define an alias open for linux
return m, Run(false, ct.directory, "open", ct.directory)
case "S": // Shell
if os.Getenv("TMUX") != "" {
return m, Run(false, ct.directory, "tmux", "new-window", "-n", "BASH", "bash")
} else {
home := os.Getenv("HOME")
return m, m.RunPlugin(filepath.Join(home, ".config/bfm/plugins/shell"))
}
case "V": // Vim
return m, Run(false, ct.directory, "nvim")
// This may be used to force OneDrive to download a file so that it can be opened without error (like in Acrobat)
case "ctrl+n": // Cat to Null
return m, Run(false, ct.directory, "bash", "-c", fmt.Sprintf("cat '%s' > /dev/null", ct.filteredFiles[ct.cursor].Name()))
}
m.viewport.SetContent(m.generateContent())
}
if m.mode == filterMode {
if (msg.String() == "esc") {
ct.SetFilter("")
m.mode = commandMode
} else if (msg.String() == "backspace") {
if len(ct.filter) > 0 {
ct.SetFilter(ct.filter[:len(ct.filter)-1])
}
} else if (msg.String() == "enter") {
m.mode = commandMode
} else if (msg.String() == "ctrl+l") {
ct.SetFilter("")
} else if (msg.String() == "ctrl+w") {
filter := strings.TrimRight(ct.filter, " ")
i := strings.LastIndex(filter, " ")
if i == -1 {
ct.SetFilter("")
} else {
ct.SetFilter(ct.filter[:i+1])
}
} else {
ct.SetFilter(ct.filter+msg.String())
}
m.viewport.GotoTop()
m.viewport.SetContent(m.generateContent())
}
if m.mode == selectedMode {
//log.Printf("DEBUG: Key %s", msg.String())
switch msg.String() {
case "esc", "q":
m.mode = commandMode
return m, refresh()
case "d":
return m, m.DeselectAll()
case "j":
m.viewport.LineDown(1)
case "k":
m.viewport.LineUp(1)
case "ctrl+d":
m.viewport.HalfViewDown()
case "ctrl+u":
m.viewport.HalfViewUp()
case "g":
m.viewport.GotoTop()
case "G":
m.viewport.GotoBottom()
case "1":
m.mode = commandMode
return m, tab(1)
case "2":
m.mode = commandMode
return m, tab(2)
case "3":
m.mode = commandMode
return m, tab(3)
case "4":
m.mode = commandMode
return m, tab(4)
case "5":
m.mode = commandMode
return m, tab(5)
case "6":
m.mode = commandMode
return m, tab(6)
}
}
}
return m, nil
}
func getStartDir(args []string) string {
curDir, err := filepath.Abs(".")
if err != nil {
log.Fatalln(err.Error())
}
if len(args) > 1 {
specifiedDir := os.Args[1]
absdir, err := filepath.Abs(specifiedDir)
if err != nil {
log.Print("Error getting absolute path of "+specifiedDir+" "+err.Error())
return curDir
}
realpath, err := resolveSymLink(absdir)
if err != nil {
log.Printf("error getting real path for "+absdir)
return curDir
}
stat, err := os.Stat(realpath)
if (stat.IsDir()) {
return realpath
}
}
return curDir
}
func main() {
home = os.Getenv("HOME")
logpath := filepath.Join(home,".local/log/bfm.log")
helpPath = filepath.Join(home,".local/share/bfm/help-"+version+".txt")
// we only want the lastd file to be valid if we exit cleanly
ClearLastd()
LoadConfig()
os.MkdirAll(filepath.Dir(logpath), 0755)
f, err := os.OpenFile(logpath, os.O_RDWR | os.O_CREATE | os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
log.SetOutput(f)
writeHelp(generateHelp())
startDir := getStartDir(os.Args)
if err != nil {
log.Fatalln(err.Error())
}
// Create the TeaModel, which contains application state
m := model{}
for i := 0; i < 6; i++ {
m.tabs = append(m.tabs, tabData{active: false})
}
m.SelectTab(0)
err = m.tabs[0].ChangeDirectory(startDir)
if err != nil {
log.Fatalln("Error changing directory to "+startDir)
}
m.tabs[0].AddHistory(startDir)
m.scrollProgress = progress.New(progress.WithScaledGradient("#FF7CCB", "#FDFF8C"))
// Create a new tea program and run it.
p := tea.NewProgram(m, tea.WithAltScreen())
if _, err := p.Run(); err != nil {
log.Fatal(err)
}
}