Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
708 lines (611 loc) · 16.9 KB
/
Copy pathmain.go
File metadata and controls
708 lines (611 loc) · 16.9 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
package main
import (
"context"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"sync"
"time"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/fsnotify/fsnotify"
"github.com/spf13/cobra"
)
type GitStatus struct {
Symbol string
Message string
Branch string
LastCommit string
RepoPath string
RelativePath string
ModTime time.Time
}
type Config struct {
Directory string
Report bool
All bool
TUI bool
Depth int
Theme string
}
type model struct {
repos []GitStatus
cursor int
loading bool
baseDir string
showDetail bool
config Config
cache map[string]GitStatus
animations *AnimationState
watcher *fsnotify.Watcher
lastUpdate time.Time
updateCount int
hackerFX *HackerEffects
matrixMode bool
termWidth int
termHeight int
}
var config Config
func main() {
rootCmd := &cobra.Command{
Use: "git-status-dash [directory]",
Short: "Monitor git repository status in real-time",
Long: `Git Status Dashboard recursively scans directories for git repositories
and displays their status with beautiful TUI or report output.`,
Args: cobra.MaximumNArgs(1),
Run: run,
}
// Config commands
configCmd := &cobra.Command{
Use: "config",
Short: "Manage configuration",
Long: "Manage themes, settings, and preferences for git-status-dash",
}
initCmd := &cobra.Command{
Use: "init",
Short: "Initialize config with defaults",
Run: func(cmd *cobra.Command, args []string) {
if err := initConfig(); err != nil {
log.Fatal(err)
}
},
}
showCmd := &cobra.Command{
Use: "show",
Short: "Show current configuration",
Run: func(cmd *cobra.Command, args []string) {
showConfig()
},
}
themesCmd := &cobra.Command{
Use: "themes",
Short: "List available themes",
Run: func(cmd *cobra.Command, args []string) {
listAllThemes()
},
}
setThemeCmd := &cobra.Command{
Use: "theme <name>",
Short: "Set the active theme",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
setTheme(args[0])
},
}
autoCmd := &cobra.Command{
Use: "auto",
Short: "Auto-detect and set theme based on system",
Run: func(cmd *cobra.Command, args []string) {
if err := setAutoTheme(); err != nil {
log.Fatal(err)
}
},
}
downloadCmd := &cobra.Command{
Use: "download <source>",
Short: "Download theme from external source",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if err := downloadTheme(args[0]); err != nil {
log.Fatal(err)
}
},
}
sourcesCmd := &cobra.Command{
Use: "sources",
Short: "List available theme sources",
Run: func(cmd *cobra.Command, args []string) {
listThemeSources()
},
}
importCmd := &cobra.Command{
Use: "import <app-type> <file-path>",
Short: "Import theme from local file (vscode/alacritty/kitty)",
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
if err := importLocalTheme(args[0], args[1]); err != nil {
log.Fatal(err)
}
},
}
setCmd := &cobra.Command{
Use: "set <key> <value>",
Short: "Set a configuration value",
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
setConfigValue(args[0], args[1])
},
}
configCmd.AddCommand(initCmd, showCmd, themesCmd, setThemeCmd, autoCmd, downloadCmd, sourcesCmd, importCmd, setCmd)
rootCmd.AddCommand(configCmd)
rootCmd.Flags().BoolVarP(&config.Report, "report", "r", false, "Generate a brief report")
rootCmd.Flags().StringVarP(&config.Directory, "directory", "d", "", "Specify the directory to scan")
rootCmd.Flags().BoolVarP(&config.All, "all", "a", false, "Show all repositories, including synced ones")
rootCmd.Flags().BoolVarP(&config.TUI, "tui", "t", false, "Interactive TUI interface")
rootCmd.Flags().IntVar(&config.Depth, "depth", -1, "Limit recursion depth when scanning repos")
rootCmd.Flags().StringVar(&config.Theme, "theme", "", "Override theme for this run")
rootCmd.SetHelpTemplate(`Git Status Dashboard
Usage:
{{.UseLine}}
Flags:
{{.LocalFlags.FlagUsages}}
Examples:
git-status-dash --report
git-status-dash -d ~/projects -a
Status Information:
✓ Synced and up to date
↑ Ahead of remote (local commits to push)
↓ Behind remote (commits to pull)
↕ Diverged (need to merge or rebase)
✗ Uncommitted changes
⚠ Error accessing repository
`)
if err := rootCmd.Execute(); err != nil {
log.Fatal(err)
}
}
func run(cmd *cobra.Command, args []string) {
if config.Directory == "" {
if len(args) > 0 {
config.Directory = args[0]
} else {
var err error
config.Directory, err = os.Getwd()
if err != nil {
log.Fatal(err)
}
}
}
if config.Depth == -1 {
config.Depth = -1 // unlimited
}
// Default to TUI unless --report is specified
if !config.Report {
config.TUI = true
}
if config.TUI {
runTUI()
} else {
runReport()
}
}
func runTUI() {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Printf("Warning: Could not create file watcher: %v", err)
}
m := model{
repos: []GitStatus{},
loading: true,
baseDir: config.Directory,
showDetail: false,
config: config,
cache: make(map[string]GitStatus),
animations: NewAnimationState(),
watcher: watcher,
lastUpdate: time.Now(),
updateCount: 0,
hackerFX: NewHackerEffects(80, 24), // Default terminal size
matrixMode: false,
termWidth: 80,
termHeight: 24,
}
p := tea.NewProgram(m, tea.WithAltScreen())
if _, err := p.Run(); err != nil {
log.Fatal(err)
}
if watcher != nil {
watcher.Close()
}
}
func runReport() {
repos := findGitReposOptimized(config.Directory, config.Depth)
fmt.Printf("Found %d repositories, loading......\n", len(repos))
reposToShow := repos
if !config.All {
var unsynced []GitStatus
for _, repo := range repos {
if repo.Symbol != "✓" {
unsynced = append(unsynced, repo)
}
}
reposToShow = unsynced
}
for _, repo := range reposToShow {
repoName := repo.RelativePath
if repoName == "" {
repoName = "."
}
line := fmt.Sprintf("%s %-30s %s", repo.Symbol, repoName, repo.Message)
switch repo.Symbol {
case "✓":
fmt.Printf("\033[32m%s\033[0m\n", line)
case "✗", "⚠":
fmt.Printf("\033[31m%s\033[0m\n", line)
case "↑", "↓", "↕":
fmt.Printf("\033[33m%s\033[0m\n", line)
default:
fmt.Println(line)
}
}
}
func (m model) Init() tea.Cmd {
commands := []tea.Cmd{
scanRepos(m.baseDir, m.config.Depth, m.cache),
tea.Tick(time.Millisecond*100, func(t time.Time) tea.Msg {
return tickMsg(t)
}),
tea.Tick(time.Millisecond*16, func(t time.Time) tea.Msg {
return animationTickMsg(t)
}),
}
// Set up file watching
if m.watcher != nil {
commands = append(commands, m.watchForChanges())
go m.setupWatchers()
}
return tea.Batch(commands...)
}
func (m model) watchForChanges() tea.Cmd {
return func() tea.Msg {
if m.watcher == nil {
return nil
}
select {
case event, ok := <-m.watcher.Events:
if !ok {
return nil
}
// Trigger rescan on git-related file changes
if strings.Contains(event.Name, ".git") ||
strings.HasSuffix(event.Name, ".go") ||
strings.HasSuffix(event.Name, ".js") ||
strings.HasSuffix(event.Name, ".py") {
return fileChangeMsg(event.Name)
}
case err, ok := <-m.watcher.Errors:
if !ok {
return nil
}
log.Printf("Watcher error: %v", err)
}
return nil
}
}
func (m model) setupWatchers() {
if m.watcher == nil {
return
}
// Watch all git repositories
for _, repo := range m.repos {
gitDir := filepath.Join(repo.RepoPath, ".git")
m.watcher.Add(gitDir)
m.watcher.Add(repo.RepoPath) // Watch the repo root too
}
}
type reposFoundMsg []GitStatus
type tickMsg time.Time
type fileChangeMsg string
type animationTickMsg time.Time
func scanRepos(baseDir string, depth int, cache map[string]GitStatus) tea.Cmd {
return tea.Cmd(func() tea.Msg {
repos := findGitRepos(baseDir, depth, cache)
return reposFoundMsg(repos)
})
}
func findGitRepos(baseDir string, maxDepth int, cache map[string]GitStatus) []GitStatus {
var repos []GitStatus
var mu sync.Mutex
var wg sync.WaitGroup
walkWithDepth(baseDir, baseDir, 0, maxDepth, &repos, &mu, &wg, cache)
wg.Wait()
// Sort by modification time (newest first) like original
sort.Slice(repos, func(i, j int) bool {
return repos[i].ModTime.After(repos[j].ModTime)
})
return repos
}
func walkWithDepth(currentPath, baseDir string, currentDepth, maxDepth int, repos *[]GitStatus, mu *sync.Mutex, wg *sync.WaitGroup, cache map[string]GitStatus) {
if maxDepth != -1 && currentDepth > maxDepth {
return
}
entries, err := os.ReadDir(currentPath)
if err != nil {
return
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
path := filepath.Join(currentPath, entry.Name())
if entry.Name() == ".git" {
repoPath := currentPath
wg.Add(1)
go func(rp string) {
defer wg.Done()
status := getGitStatus(rp, baseDir, cache)
mu.Lock()
*repos = append(*repos, status)
mu.Unlock()
}(repoPath)
return // Don't recurse into .git directory
}
// Skip heavy directories
if entry.Name() == "node_modules" || entry.Name() == ".cache" || entry.Name() == ".venv" {
continue
}
walkWithDepth(path, baseDir, currentDepth+1, maxDepth, repos, mu, wg, cache)
}
}
func getGitStatus(repoPath, baseDir string, cache map[string]GitStatus) GitStatus {
// Remove cache for now to fix race condition
// TODO: Add proper mutex if we want caching
relPath, _ := filepath.Rel(baseDir, repoPath)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Get modification time
info, err := os.Stat(repoPath)
var modTime time.Time
if err == nil {
modTime = info.ModTime()
}
status := GitStatus{
RepoPath: repoPath,
RelativePath: relPath,
Symbol: "⚠",
Message: "Error accessing repository",
ModTime: modTime,
}
statusCmd := exec.CommandContext(ctx, "git", "-C", repoPath, "status", "--porcelain")
statusOut, err := statusCmd.Output()
if err != nil {
return status
}
aheadCmd := exec.CommandContext(ctx, "git", "-C", repoPath, "rev-list", "--count", "@{u}..HEAD")
aheadOut, _ := aheadCmd.Output()
ahead := strings.TrimSpace(string(aheadOut))
behindCmd := exec.CommandContext(ctx, "git", "-C", repoPath, "rev-list", "--count", "HEAD..@{u}")
behindOut, _ := behindCmd.Output()
behind := strings.TrimSpace(string(behindOut))
branchCmd := exec.CommandContext(ctx, "git", "-C", repoPath, "rev-parse", "--abbrev-ref", "HEAD")
branchOut, _ := branchCmd.Output()
status.Branch = strings.TrimSpace(string(branchOut))
commitCmd := exec.CommandContext(ctx, "git", "-C", repoPath, "log", "-1", "--pretty=%h %cr %an")
commitOut, _ := commitCmd.Output()
status.LastCommit = strings.TrimSpace(string(commitOut))
statusStr := strings.TrimSpace(string(statusOut))
if statusStr == "" && ahead == "0" && behind == "0" {
status.Symbol = "✓"
status.Message = "Up to date"
} else if ahead != "0" && behind != "0" {
status.Symbol = "↕"
status.Message = fmt.Sprintf("Diverged (%s ahead, %s behind)", ahead, behind)
} else if ahead != "0" {
status.Symbol = "↑"
status.Message = fmt.Sprintf("%s commit(s) to push", ahead)
} else if behind != "0" {
status.Symbol = "↓"
status.Message = fmt.Sprintf("%s commit(s) to pull", behind)
} else {
status.Symbol = "✗"
status.Message = "Uncommitted changes"
}
return status
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.KeyMsg:
switch msg.String() {
case "ctrl+c", "q":
return m, tea.Quit
case "up", "k":
oldCursor := m.cursor
if m.cursor > 0 {
m.cursor--
// Animate cursor movement
m.animations.AnimateToPosition(float64(m.cursor))
if oldCursor != m.cursor {
m.animations.AddStatusChangeParticles(0, m.cursor, "nav")
}
}
case "down", "j":
oldCursor := m.cursor
if m.cursor < len(m.repos)-1 {
m.cursor++
// Animate cursor movement
m.animations.AnimateToPosition(float64(m.cursor))
if oldCursor != m.cursor {
m.animations.AddStatusChangeParticles(0, m.cursor, "nav")
}
}
case "enter", " ":
m.showDetail = !m.showDetail
if m.showDetail && len(m.repos) > 0 {
m.animations.AddStatusChangeParticles(15, 5, m.repos[m.cursor].Symbol)
}
case "esc":
m.showDetail = false
case "m":
// Toggle matrix mode
m.matrixMode = !m.matrixMode
case "r":
// Force refresh
m.loading = true
m.updateCount++
m.lastUpdate = time.Now()
// Clear cache to force fresh data
m.cache = make(map[string]GitStatus)
return m, scanRepos(m.baseDir, m.config.Depth, m.cache)
}
case reposFoundMsg:
repos := []GitStatus(msg)
// Check for status changes and trigger particles
for i, newRepo := range repos {
for j, oldRepo := range m.repos {
if newRepo.RepoPath == oldRepo.RepoPath && newRepo.Symbol != oldRepo.Symbol {
m.animations.AddStatusChangeParticles(30, j, newRepo.Symbol)
break
}
}
_ = i
}
if !m.config.All {
var unsynced []GitStatus
for _, repo := range repos {
if repo.Symbol != "✓" {
unsynced = append(unsynced, repo)
}
}
m.repos = unsynced
} else {
m.repos = repos
}
m.loading = false
m.lastUpdate = time.Now()
m.updateCount++
// Set up watchers for new repos
if m.watcher != nil {
go m.setupWatchers()
}
case fileChangeMsg:
// File changed, trigger refresh
if time.Since(m.lastUpdate) > 2*time.Second { // Debounce
m.loading = true
m.lastUpdate = time.Now()
return m, tea.Batch(
scanRepos(m.baseDir, m.config.Depth, m.cache),
m.watchForChanges(),
)
}
return m, m.watchForChanges()
case animationTickMsg:
m.animations.Update()
m.hackerFX.Update(m.termWidth, m.termHeight)
return m, tea.Tick(time.Millisecond*16, func(t time.Time) tea.Msg {
return animationTickMsg(t)
})
case tickMsg:
return m, tea.Tick(time.Millisecond*100, func(t time.Time) tea.Msg {
return tickMsg(t)
})
}
return m, nil
}
func (m model) View() string {
var s strings.Builder
titleStyle := lipgloss.NewStyle().
Bold(true).
Foreground(lipgloss.Color("62")).
Padding(1, 2)
s.WriteString(titleStyle.Render("🚀 Git Status Dashboard"))
s.WriteString("\n\n")
if m.loading {
spinner := []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}
loadingStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("205")).
Bold(true)
s.WriteString(loadingStyle.Render(fmt.Sprintf("%s Scanning repositories...", spinner[int(time.Now().UnixNano()/100000000)%len(spinner)])))
return s.String()
}
if len(m.repos) == 0 {
s.WriteString("No git repositories found.")
return s.String()
}
// Main repo list
for i, repo := range m.repos {
cursor := " "
if m.cursor == i {
cursor = ">"
}
symbolStyle := lipgloss.NewStyle()
repoStyle := lipgloss.NewStyle()
messageStyle := lipgloss.NewStyle()
switch repo.Symbol {
case "✓":
symbolStyle = symbolStyle.Foreground(lipgloss.Color("46"))
repoStyle = repoStyle.Foreground(lipgloss.Color("46"))
messageStyle = messageStyle.Foreground(lipgloss.Color("46"))
case "✗", "⚠":
symbolStyle = symbolStyle.Foreground(lipgloss.Color("196"))
repoStyle = repoStyle.Foreground(lipgloss.Color("196"))
messageStyle = messageStyle.Foreground(lipgloss.Color("196"))
case "↑", "↓", "↕":
symbolStyle = symbolStyle.Foreground(lipgloss.Color("220"))
repoStyle = repoStyle.Foreground(lipgloss.Color("220"))
messageStyle = messageStyle.Foreground(lipgloss.Color("220"))
}
if m.cursor == i {
symbolStyle = symbolStyle.Background(lipgloss.Color("238"))
repoStyle = repoStyle.Background(lipgloss.Color("238"))
messageStyle = messageStyle.Background(lipgloss.Color("238"))
}
repoName := repo.RelativePath
if repoName == "" {
repoName = "."
}
line := fmt.Sprintf("%s %s %-30s %s",
cursor,
symbolStyle.Render(repo.Symbol),
repoStyle.Render(repoName),
messageStyle.Render(repo.Message),
)
s.WriteString(line + "\n")
}
// Detail popup
if m.showDetail && len(m.repos) > 0 && m.cursor < len(m.repos) {
repo := m.repos[m.cursor]
detailStyle := lipgloss.NewStyle().
Border(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("62")).
Padding(1, 2).
Margin(1, 0).
Background(lipgloss.Color("0"))
detailContent := fmt.Sprintf(
"Repository Details\n\n"+
"Path: %s\n"+
"Branch: %s\n"+
"Status: %s\n"+
"Last Commit: %s",
repo.RepoPath,
repo.Branch,
repo.Message,
repo.LastCommit,
)
s.WriteString("\n")
s.WriteString(detailStyle.Render(detailContent))
}
s.WriteString("\n")
helpStyle := lipgloss.NewStyle().
Foreground(lipgloss.Color("241")).
Italic(true)
helpText := "↑/↓: navigate • enter: details • q: quit"
if m.showDetail {
helpText = "↑/↓: navigate • esc: close details • q: quit"
}
s.WriteString(helpStyle.Render(helpText))
return s.String()
}