-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1022 lines (900 loc) · 28 KB
/
main.go
File metadata and controls
1022 lines (900 loc) · 28 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
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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"github.com/alecthomas/chroma/v2"
"github.com/alecthomas/chroma/v2/formatters"
"github.com/alecthomas/chroma/v2/lexers"
"github.com/alecthomas/chroma/v2/styles"
"github.com/charmbracelet/bubbles/list"
"github.com/charmbracelet/bubbles/spinner"
"github.com/charmbracelet/bubbles/viewport"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
// Version is set via ldflags at build time
var Version = "0.9.0"
type focusedPane int
const (
focusRepo focusedPane = iota
focusFile
focusDiff
)
// fetchCompleteMsg is sent when remote fetching is complete
type fetchCompleteMsg struct{}
// repoFetchStartMsg is sent when a specific repo starts fetching
type repoFetchStartMsg struct {
repo string
}
// repoFetchCompleteMsg is sent when a specific repo completes fetching
type repoFetchCompleteMsg struct {
repo string
err error
}
// layoutGap is the horizontal gap subtracted when computing the right column width.
const layoutGap = 4
type model struct {
config *Config
focused focusedPane
width int
height int
repoList list.Model
fileList list.Model
diffView viewport.Model
selectedRepo int
selectedFile int
gitStatuses map[string]GitStatus
currentDiff string
launchLazyGit bool
lazyGitRepo string
isFetching bool
spinner spinner.Model
fetchingRepos map[string]bool // Track which repos are currently fetching
repoSpinners map[string]spinner.Model // Store spinners for each repo
}
// Icon represents the different icon types we use
type Icon struct {
Error string
Success string
Changed string
Pull string
}
// getIcons returns the appropriate icons based on the config setting
func getIcons(iconStyle string) Icon {
if iconStyle == "glyphs" {
// Nerd Font glyphs
return Icon{
Error: "", // nf-fa-times_circle
Success: "", // nf-fa-check_circle
Changed: "", // nf-fa-refresh
Pull: "", // nf-fa-download
}
}
// Default to emoji
return Icon{
Error: "❌",
Success: "✅",
Changed: "🔄",
Pull: "⬇️",
}
}
type repoItem struct {
path string
status GitStatus
iconStyle string
displayFullPath bool
isFetching bool
spinner spinner.Model
}
func (i repoItem) FilterValue() string { return i.path }
func (i repoItem) Title() string {
icons := getIcons(i.iconStyle)
pullIcon := ""
if i.status.HasRemote && i.status.NeedsPull {
pullIcon = icons.Pull + " "
}
displayName := i.path
if !i.displayFullPath {
displayName = filepath.Base(i.path)
}
title := ""
if i.status.HasError {
title = fmt.Sprintf("%s %s%s", icons.Error, pullIcon, displayName)
} else if len(i.status.Files) == 0 {
title = fmt.Sprintf("%s %s%s", icons.Success, pullIcon, displayName)
} else {
title = fmt.Sprintf("%s %s%s (%d)", icons.Changed, pullIcon, displayName, len(i.status.Files))
}
// Apply green color to repos with changes, yellow to repos behind remote
if len(i.status.Files) > 0 && !i.status.HasError {
return lipgloss.NewStyle().Foreground(lipgloss.Color("#a6d189")).Render(title)
}
if i.status.HasRemote && i.status.NeedsPull && !i.status.HasError {
return lipgloss.NewStyle().Foreground(lipgloss.Color("#ef9f76")).Render(title)
}
return title
}
func (i repoItem) Description() string {
if i.status.HasError {
return i.status.Error
}
branchPrefix := ""
if i.status.Branch != "" {
branchPrefix = i.status.Branch + " • "
}
baseDesc := ""
if len(i.status.Files) == 0 {
baseDesc = branchPrefix + "No changes"
} else if len(i.status.Files) == 1 {
baseDesc = branchPrefix + "1 changed file"
} else {
baseDesc = fmt.Sprintf("%s%d changed files", branchPrefix, len(i.status.Files))
}
// Show spinner and "Updating" when fetching
if i.isFetching {
return fmt.Sprintf("%s • %s Updating", baseDesc, i.spinner.View())
}
if i.status.HasRemote && i.status.RemoteStatus != "" {
return fmt.Sprintf("%s • %s", baseDesc, i.status.RemoteStatus)
}
return baseDesc
}
type fileItem struct {
gitFile GitFile
}
func (i fileItem) FilterValue() string { return i.gitFile.Path }
func (i fileItem) Title() string { return fmt.Sprintf("%s %s", i.gitFile.Status, i.gitFile.Path) }
func (i fileItem) Description() string { return getStatusDescription(i.gitFile.Status) }
func getStatusDescription(status string) string {
switch status {
case "M":
return "Modified"
case "A":
return "Added"
case "D":
return "Deleted"
case "R":
return "Renamed"
case "C":
return "Copied"
case "U":
return "Updated but unmerged"
case "??":
return "Untracked"
default:
return "Unknown"
}
}
// applySyntaxHighlighting applies syntax highlighting to diff content
func applySyntaxHighlighting(content, filePath string) string {
if content == "" {
return content
}
// Check if this is a git diff format
isDiff := strings.Contains(content, "diff --git") ||
strings.Contains(content, "@@") ||
strings.HasPrefix(content, "New file:")
var lexer chroma.Lexer
if isDiff {
// Use diff lexer for git diff output
lexer = lexers.Get("diff")
} else {
// For new files, try to detect lexer by file extension
lexer = lexers.Match(filePath)
}
// Fallback to plain text if no lexer found
if lexer == nil {
lexer = lexers.Fallback
}
// Use a terminal-friendly style
style := styles.Get("catppuccin-frappe")
if style == nil {
style = styles.Fallback
}
// Create a 16-color terminal formatter for better compatibility
formatter := formatters.Get("terminal16m")
if formatter == nil {
formatter = formatters.Fallback
}
// Apply syntax highlighting
var buf strings.Builder
iterator, err := lexer.Tokenise(nil, content)
if err != nil {
return content // Return original content if highlighting fails
}
err = formatter.Format(&buf, style, iterator)
if err != nil {
return content // Return original content if formatting fails
}
return buf.String()
}
func addRepositoryFromCommandLine(path string) error {
// Load config
config, err := loadConfig()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
// Expand path to absolute path
absPath, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("failed to resolve absolute path: %w", err)
}
// Check if directory exists
if _, err := os.Stat(absPath); os.IsNotExist(err) {
return fmt.Errorf("directory does not exist: %s", absPath)
}
// Check if it's a git repository
gitDir := filepath.Join(absPath, ".git")
if _, err := os.Stat(gitDir); os.IsNotExist(err) {
return fmt.Errorf("not a git repository: %s", absPath)
}
// Add repository with duplicate checking
if config.addRepositoryWithPath(absPath) {
// Save config
if err := config.saveConfig(); err != nil {
return fmt.Errorf("failed to save config: %w", err)
}
fmt.Printf("Added repository: %s\n", absPath)
} else {
fmt.Printf("Repository already exists: %s\n", absPath)
}
return nil
}
func listRepositoriesFromCommandLine() error {
// Load config
config, err := loadConfig()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
if len(config.Repositories) == 0 {
fmt.Println("No repositories configured")
return nil
}
fmt.Printf("Configured repositories (%d):\n", len(config.Repositories))
for i, repo := range config.Repositories {
fmt.Printf("%d. %s\n", i+1, repo)
}
return nil
}
func deleteRepositoryFromCommandLine(path string) error {
// Load config
config, err := loadConfig()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
// Expand path to absolute path for comparison
absPath, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("failed to resolve absolute path: %w", err)
}
// Remove repository
if config.removeRepository(absPath) {
// Save config
if err := config.saveConfig(); err != nil {
return fmt.Errorf("failed to save config: %w", err)
}
fmt.Printf("Removed repository: %s\n", absPath)
} else {
fmt.Printf("Repository not found: %s\n", absPath)
}
return nil
}
func initialModel() (model, error) {
config, err := loadConfig()
if err != nil {
return model{}, err
}
// Catppuccin Frappé palette
titleStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("#c6d0f5")). // Text
Bold(true)
selectedStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("#c6d0f5")). // Text
Border(lipgloss.NormalBorder(), false, false, false, true).
BorderForeground(lipgloss.Color("#ca9ee6")). // Mauve
Padding(0, 0, 0, 1)
selectedDescStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("#a5adce")). // Subtext0
Border(lipgloss.NormalBorder(), false, false, false, true).
BorderForeground(lipgloss.Color("#ca9ee6")). // Mauve
Padding(0, 0, 0, 1)
normalStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("#c6d0f5")). // Text
Padding(0, 0, 0, 2)
normalDescStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("#737994")). // Overlay0
Padding(0, 0, 0, 2)
repoDelegate := list.NewDefaultDelegate()
repoDelegate.Styles.SelectedTitle = selectedStyle
repoDelegate.Styles.SelectedDesc = selectedDescStyle
repoDelegate.Styles.NormalTitle = normalStyle
repoDelegate.Styles.NormalDesc = normalDescStyle
repoList := list.New([]list.Item{}, repoDelegate, 0, 0)
repoList.Title = "Repositories"
repoList.Styles.Title = titleStyle
repoList.SetShowStatusBar(false)
repoList.SetShowPagination(false)
fileDelegate := list.NewDefaultDelegate()
fileDelegate.Styles.SelectedTitle = selectedStyle
fileDelegate.Styles.SelectedDesc = selectedDescStyle
fileDelegate.Styles.NormalTitle = normalStyle
fileDelegate.Styles.NormalDesc = normalDescStyle
fileList := list.New([]list.Item{}, fileDelegate, 0, 0)
fileList.Title = "Changed Files"
fileList.Styles.Title = titleStyle
fileList.SetShowStatusBar(false)
fileList.SetShowPagination(false)
diffView := viewport.New(0, 0)
// Initialize spinner
s := spinner.New()
s.Spinner = spinner.Dot
s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("#babbf1")) // Bright blue color
m := model{
config: config,
focused: focusRepo,
repoList: repoList,
fileList: fileList,
diffView: diffView,
gitStatuses: make(map[string]GitStatus),
spinner: s,
isFetching: true, // Start in fetching state
fetchingRepos: make(map[string]bool),
repoSpinners: make(map[string]spinner.Model),
}
if len(config.Repositories) > 0 {
// Mark all repos as fetching before Init() runs (Init is a value receiver,
// so mutations there would be lost).
for _, repo := range config.Repositories {
m.fetchingRepos[repo] = true
}
// Do initial status check without fetching
m.updateGitStatuses()
m.updateRepoList()
m.selectRepo(0)
}
return m, nil
}
func (m *model) updateGitStatuses() {
for _, repo := range m.config.Repositories {
m.gitStatuses[repo] = checkGitStatus(repo)
}
}
func (m *model) updateRepoList() {
items := make([]list.Item, 0)
for _, repo := range m.config.Repositories {
status, exists := m.gitStatuses[repo]
if !exists {
status = GitStatus{Path: repo, HasError: true, Error: "Status not loaded"}
}
// Get or create spinner for this repo
s, exists := m.repoSpinners[repo]
if !exists {
s = spinner.New()
s.Spinner = spinner.Dot
s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("#babbf1"))
m.repoSpinners[repo] = s
}
items = append(items, repoItem{
path: repo,
status: status,
iconStyle: m.config.IconStyle,
displayFullPath: m.config.DisplayFullPath,
isFetching: m.fetchingRepos[repo],
spinner: s,
})
}
// Sort by path if alphabetical order is configured
if m.config.SortOrder == "alphabetical" {
slices.SortStableFunc(items, func(a, b list.Item) int {
return strings.Compare(a.(repoItem).path, b.(repoItem).path)
})
}
// Float changed/behind repos to top if configured, grouped by priority:
// 1. Both local changes and behind remote
// 2. Behind remote only
// 3. Local changes only
// 4. Clean repos
// Within each group, the primary sort_order is preserved (stable sort).
if m.config.SortChangedToTop {
slices.SortStableFunc(items, func(a, b list.Item) int {
return repoChangePriority(a.(repoItem)) - repoChangePriority(b.(repoItem))
})
}
m.repoList.SetItems(items)
}
// repoChangePriority returns a sort key for grouping repos by change state.
// Lower values sort first.
func repoChangePriority(item repoItem) int {
hasLocal := len(item.status.Files) > 0
hasRemote := item.status.HasRemote && item.status.NeedsPull
switch {
case hasLocal && hasRemote:
return 0
case hasRemote:
return 1
case hasLocal:
return 2
default:
return 3
}
}
// selectedRepoPath returns the path of the currently selected repo from the
// displayed (sorted) list, not from the config array.
func (m *model) selectedRepoPath() string {
item := m.repoList.SelectedItem()
if item == nil {
return ""
}
return item.(repoItem).path
}
func (m *model) updateFileList() {
repo := m.selectedRepoPath()
if repo == "" {
m.fileList.SetItems([]list.Item{})
return
}
status, exists := m.gitStatuses[repo]
if !exists || status.HasError {
m.fileList.SetItems([]list.Item{})
return
}
items := make([]list.Item, 0)
for _, file := range status.Files {
items = append(items, fileItem{gitFile: file})
}
m.fileList.SetItems(items)
}
func (m *model) selectRepo(index int) {
if index >= 0 && index < len(m.repoList.Items()) {
m.selectedRepo = index
m.selectedFile = 0
m.repoList.Select(index)
m.updateFileList()
if len(m.fileList.Items()) > 0 {
m.selectFile(0)
} else {
m.currentDiff = ""
m.diffView.SetContent("")
}
}
}
func (m *model) selectFile(index int) {
items := m.fileList.Items()
if index >= 0 && index < len(items) {
m.selectedFile = index
m.fileList.Select(index)
m.updateDiff()
}
}
func (m *model) updateDiff() {
items := m.fileList.Items()
if m.selectedFile >= 0 && m.selectedFile < len(items) {
fileItem, ok := items[m.selectedFile].(fileItem)
if !ok {
return
}
repo := m.selectedRepoPath()
diff, err := getFileDiff(repo, fileItem.gitFile.Path)
if err != nil {
m.currentDiff = fmt.Sprintf("Error getting diff: %s", err.Error())
} else if diff == "" {
m.currentDiff = fmt.Sprintf("No diff available for: %s\n\nThis could mean:\n- File is newly added (not tracked)\n- File is staged but no changes in working directory\n- Binary file", fileItem.gitFile.Path)
} else {
// Apply syntax highlighting to the diff content
highlightedDiff := applySyntaxHighlighting(diff, fileItem.gitFile.Path)
m.currentDiff = highlightedDiff
}
m.diffView.SetContent(m.currentDiff)
m.diffView.GotoTop()
}
}
// handleNavigation routes a key event to the currently focused pane and
// syncs selection state accordingly.
func (m *model) handleNavigation(msg tea.KeyMsg, cmds *[]tea.Cmd, cmd tea.Cmd) tea.Cmd {
switch m.focused {
case focusRepo:
m.repoList, cmd = m.repoList.Update(msg)
*cmds = append(*cmds, cmd)
if m.repoList.SelectedItem() != nil {
m.selectedRepo = m.repoList.Index()
m.updateFileList()
if len(m.fileList.Items()) > 0 {
m.selectFile(0)
} else {
m.currentDiff = ""
m.diffView.SetContent("")
}
}
case focusFile:
m.fileList, cmd = m.fileList.Update(msg)
*cmds = append(*cmds, cmd)
if m.fileList.SelectedItem() != nil {
m.selectedFile = m.fileList.Index()
m.updateDiff()
}
case focusDiff:
m.diffView, cmd = m.diffView.Update(msg)
*cmds = append(*cmds, cmd)
}
return tea.Batch(*cmds...)
}
// fetchRemotesCmd returns a command that fetches all remotes concurrently
func fetchRemotesCmd(repos []string) tea.Cmd {
var cmds []tea.Cmd
for _, repo := range repos {
r := repo // Capture for closure
cmds = append(cmds, func() tea.Msg {
err := fetchRemoteUpdates(r)
return repoFetchCompleteMsg{repo: r, err: err}
})
}
return tea.Batch(cmds...)
}
func (m model) Init() tea.Cmd {
// Start spinner and fetch remotes in background.
// Note: fetchingRepos is populated in initialModel() because Init() is a
// value receiver — mutations here would be lost.
if m.isFetching && len(m.config.Repositories) > 0 {
var cmds []tea.Cmd
// Start each repo's spinner tick
for _, repo := range m.config.Repositories {
if s, exists := m.repoSpinners[repo]; exists {
cmds = append(cmds, s.Tick)
}
}
// Add global spinner and fetch command
cmds = append(cmds, m.spinner.Tick)
cmds = append(cmds, fetchRemotesCmd(m.config.Repositories))
return tea.Batch(cmds...)
}
return nil
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
var cmd tea.Cmd
var cmds []tea.Cmd
switch msg := msg.(type) {
case repoFetchCompleteMsg:
// Mark repo as no longer fetching and update its status
delete(m.fetchingRepos, msg.repo)
// Update just this repo's status
status := checkGitStatus(msg.repo)
if msg.err != nil && !status.HasError {
status.RemoteStatus = fmt.Sprintf("Fetch failed: %s", msg.err)
}
m.gitStatuses[msg.repo] = status
m.updateRepoList()
// If this was the selected repo, update the file list
if m.selectedRepoPath() == msg.repo {
m.updateFileList()
if len(m.fileList.Items()) > 0 {
m.updateDiff()
}
}
// Check if all repos are done fetching
if len(m.fetchingRepos) == 0 {
m.isFetching = false
} else {
// Continue spinner updates for remaining repos
return m, m.spinner.Tick
}
return m, nil
case spinner.TickMsg:
// Update spinner if we're still fetching
if m.isFetching || len(m.fetchingRepos) > 0 {
var tickCmds []tea.Cmd
m.spinner, cmd = m.spinner.Update(msg)
if cmd != nil {
tickCmds = append(tickCmds, cmd)
}
// Update all fetching repo spinners and collect their commands
for repo := range m.fetchingRepos {
if s, exists := m.repoSpinners[repo]; exists {
updatedSpinner, spinnerCmd := s.Update(msg)
m.repoSpinners[repo] = updatedSpinner
if spinnerCmd != nil {
tickCmds = append(tickCmds, spinnerCmd)
}
}
}
// Update the repo list to show new spinner states
m.updateRepoList()
// Continue ticking all spinners
return m, tea.Batch(tickCmds...)
}
case tea.WindowSizeMsg:
m.width = msg.Width
m.height = msg.Height
// Create a style to calculate frame size including borders and padding
frameStyle := lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
Padding(0, 1)
// Calculate frame overhead (borders + padding)
frameWidth, frameHeight := frameStyle.GetFrameSize()
// 2-column layout: left column (40%) for repo and file lists, right column (60%) for diff
leftColumnWidth := int(float64(m.width) * 0.4)
rightColumnWidth := m.width - leftColumnWidth - layoutGap
// Help text takes up some vertical space
helpHeight := 2 // Help text + some padding
availableHeight := m.height - helpHeight
// Left column is split vertically: repositories (70%) and files (30%)
// Compute total content budget first to avoid rounding overflow, then split.
leftPaneContentWidth := leftColumnWidth - frameWidth
if leftPaneContentWidth < 0 {
leftPaneContentWidth = 0
}
rightPaneContentWidth := rightColumnWidth - frameWidth
if rightPaneContentWidth < 0 {
rightPaneContentWidth = 0
}
leftContentBudget := availableHeight - (2 * frameHeight)
if leftContentBudget < 0 {
leftContentBudget = 0
}
repoHeight := (leftContentBudget * 7) / 10
fileHeight := leftContentBudget - repoHeight
diffHeight := availableHeight - frameHeight
if diffHeight < 0 {
diffHeight = 0
}
m.repoList.SetSize(leftPaneContentWidth, repoHeight)
m.fileList.SetSize(leftPaneContentWidth, fileHeight)
m.diffView.Width = rightPaneContentWidth
m.diffView.Height = diffHeight
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c", "q":
return m, tea.Quit
case "enter":
if repo := m.selectedRepoPath(); repo != "" {
// Check if the command starts with "github" - if so, launch in background
if strings.HasPrefix(m.config.EnterCommandBinary, "github") {
// Launch GitHub Desktop in background and continue running TUI
commandTemplate := m.config.EnterCommandBinary
command := strings.ReplaceAll(commandTemplate, "$REPO", repo)
parts := strings.Fields(command)
if len(parts) > 0 {
var cmd *exec.Cmd
if len(parts) == 1 {
cmd = exec.Command(parts[0])
} else {
cmd = exec.Command(parts[0], parts[1:]...)
}
// Start the GUI in background
cmd.Start()
}
// Don't quit - return to TUI
return m, nil
} else {
// For TUI apps like lazygit, set flag to launch and quit
m.launchLazyGit = true
m.lazyGitRepo = repo
return m, tea.Quit
}
}
case "tab":
// Switch focus between repo, file, and diff panes
if m.focused == focusRepo {
m.focused = focusFile
} else if m.focused == focusFile {
m.focused = focusDiff
} else {
m.focused = focusRepo
}
case "shift+tab":
// Switch focus backwards between repo, file, and diff panes
if m.focused == focusRepo {
m.focused = focusDiff
} else if m.focused == focusFile {
m.focused = focusRepo
} else {
m.focused = focusFile
}
case "up", "k":
return m, m.handleNavigation(msg, &cmds, cmd)
case "down", "j":
return m, m.handleNavigation(msg, &cmds, cmd)
case "r":
// Refresh both local status and fetch remote updates
m.updateGitStatuses()
m.updateRepoList()
m.updateFileList()
// Also fetch remote updates for all repositories asynchronously
if !m.isFetching {
var fetchCmds []tea.Cmd
m.isFetching = true
// Mark all repos as fetching and start their spinners
for _, repo := range m.config.Repositories {
m.fetchingRepos[repo] = true
// Ensure spinner exists and start it
if _, exists := m.repoSpinners[repo]; !exists {
s := spinner.New()
s.Spinner = spinner.Dot
s.Style = lipgloss.NewStyle().Foreground(lipgloss.Color("#babbf1"))
m.repoSpinners[repo] = s
}
if s, exists := m.repoSpinners[repo]; exists {
fetchCmds = append(fetchCmds, s.Tick)
}
}
m.updateRepoList() // Update to show spinners
// Add global spinner and fetch command
fetchCmds = append(fetchCmds, m.spinner.Tick)
fetchCmds = append(fetchCmds, fetchRemotesCmd(m.config.Repositories))
return m, tea.Batch(fetchCmds...)
}
default:
// Forward all other key events (e.g. PgUp/PgDn) to the focused pane only
return m, m.handleNavigation(msg, &cmds, cmd)
}
}
// Only propagate non-key messages to other components to avoid duplicate key handling
if _, isKey := msg.(tea.KeyMsg); !isKey {
if m.focused != focusRepo {
m.repoList, cmd = m.repoList.Update(msg)
cmds = append(cmds, cmd)
}
if m.focused != focusFile {
m.fileList, cmd = m.fileList.Update(msg)
cmds = append(cmds, cmd)
}
if m.focused != focusDiff {
m.diffView, cmd = m.diffView.Update(msg)
cmds = append(cmds, cmd)
}
}
return m, tea.Batch(cmds...)
}
func (m model) View() string {
// Guard against rendering before the first WindowSizeMsg arrives.
// Without valid dimensions the layout math produces negative widths
// and misaligned borders.
if m.width == 0 || m.height == 0 {
return ""
}
// Calculate left column width for proper pane sizing
leftColumnWidth := int(float64(m.width) * 0.4)
rightColumnWidth := m.width - leftColumnWidth - layoutGap
paneStyle := lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
Padding(0, 1).
Width(leftColumnWidth)
focusedStyle := lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("#ca9ee6")).
Padding(0, 1).
Width(leftColumnWidth)
rightPaneStyle := lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
Padding(0, 1).
Width(rightColumnWidth)
// Apply focused styling to the current pane
var repoPane, filePane, diffPane string
if m.focused == focusRepo {
repoPane = focusedStyle.Render(m.repoList.View())
filePane = paneStyle.Render(m.fileList.View())
diffPane = rightPaneStyle.Render(m.diffView.View())
} else if m.focused == focusFile {
repoPane = paneStyle.Render(m.repoList.View())
filePane = focusedStyle.Render(m.fileList.View())
diffPane = rightPaneStyle.Render(m.diffView.View())
} else {
repoPane = paneStyle.Render(m.repoList.View())
filePane = paneStyle.Render(m.fileList.View())
diffPane = rightPaneStyle.
BorderForeground(lipgloss.Color("#ca9ee6")).
Render(m.diffView.View())
}
// Create the left column by joining repo and file lists vertically
leftColumn := lipgloss.JoinVertical(
lipgloss.Left,
repoPane,
filePane,
)
// Create the right column with the diff view
rightColumn := diffPane
// Join the two columns horizontally
content := lipgloss.JoinHorizontal(
lipgloss.Top,
leftColumn,
rightColumn,
)
// Show spinner or help text
var help string
if m.isFetching {
spinnerView := m.spinner.View()
fetchText := lipgloss.NewStyle().
Foreground(lipgloss.Color("#737994")).
Render(" Fetching remote updates from repositories...")
help = spinnerView + fetchText
} else {
helpText := fmt.Sprintf("Press 'r' to refresh, 'q' to quit, Tab to switch panes, ↑↓/PgUp/PgDn to navigate, Enter to open %s", m.config.EnterCommandBinary)
help = lipgloss.NewStyle().
Foreground(lipgloss.Color("#737994")).
Width(m.width).
Render(helpText)
}
joined := lipgloss.JoinVertical(lipgloss.Left, content, help)
// Force the final frame to exactly match the terminal size to prevent scrollback growth
return lipgloss.Place(m.width, m.height, lipgloss.Left, lipgloss.Top, joined)
}
func main() {
// Parse command line flags
addRepo := flag.String("a", "", "Add a repository to the config")
listRepos := flag.Bool("l", false, "List repositories in the config")
deleteRepo := flag.String("d", "", "Delete a repository from the config")
versionShort := flag.Bool("v", false, "Display version")
versionLong := flag.Bool("version", false, "Display version")
flag.Parse()
// Handle version flags
if *versionShort || *versionLong {
fmt.Println(Version)
return
}
// Handle add repository command
if *addRepo != "" {
err := addRepositoryFromCommandLine(*addRepo)
if err != nil {
fmt.Printf("Error adding repository: %v\n", err)
os.Exit(1)
}
return
}
// Handle list repositories command
if *listRepos {
err := listRepositoriesFromCommandLine()
if err != nil {
fmt.Printf("Error listing repositories: %v\n", err)
os.Exit(1)
}
return
}
// Handle delete repository command
if *deleteRepo != "" {
err := deleteRepositoryFromCommandLine(*deleteRepo)
if err != nil {
fmt.Printf("Error deleting repository: %v\n", err)
os.Exit(1)
}
return
}
m, err := initialModel()
if err != nil {
fmt.Printf("Error initializing: %v\n", err)
os.Exit(1)
}
// Use the alternate screen to avoid polluting scrollback while the TUI runs.
// If running inside tmux, ensure: set -g alternate-screen on
p := tea.NewProgram(m, tea.WithAltScreen())
finalModel, err := p.Run()
if err != nil {
fmt.Printf("Error running program: %v\n", err)
os.Exit(1)
}
// Check if we need to launch the configured binary
if result, ok := finalModel.(model); ok && result.launchLazyGit {
commandTemplate := result.config.EnterCommandBinary
// Replace $REPO with the selected repository path