-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1343 lines (1202 loc) · 37.8 KB
/
Copy pathmain.go
File metadata and controls
1343 lines (1202 loc) · 37.8 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 (
"bufio"
"fmt"
"io"
"log"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime/debug"
"slices"
"strconv"
"strings"
"sync"
"time"
)
const VERSION = "7.1.2"
// HistoryLimit is the maximum number of commits to review; we'll exit if we
// find all files before it; if a file was more than this many commits ago we
// won't print its info
const HistoryLimit = "50000"
type Diff struct {
plus int
minus int
}
type File struct {
entry os.DirEntry
name string // used for deleted files that don't have a DirEntry
oldName string // pre-rename path for R/C status (relative to current directory)
status string
diffSum *Diff
diffStat string
author string
authorEmail string
hash string // full hash
shortHash string // Git's abbreviated hash (length varies by repo size)
lastModified string
commitTime int64 // unix timestamp of the commit for precise sorting
message string
isDir bool
isExe bool
isDeleted bool
}
// RenderContext holds settings that affect how output is rendered
type RenderContext struct {
GithubURL string
Dir string
MonoHash bool
NerdFont bool
}
// DebugTimer tracks timing information for debug mode
type DebugTimer struct {
timings map[string]time.Duration
fileTimings map[string]int // stores line counts for file lookups
mu sync.Mutex
}
func newDebugTimer() *DebugTimer {
return &DebugTimer{
timings: make(map[string]time.Duration),
fileTimings: make(map[string]int),
}
}
func (dt *DebugTimer) time(name string, fn func()) {
start := time.Now()
fn()
elapsed := time.Since(start)
dt.mu.Lock()
dt.timings[name] = elapsed
dt.mu.Unlock()
}
func (dt *DebugTimer) record(name string, duration time.Duration) {
dt.mu.Lock()
dt.timings[name] = duration
dt.mu.Unlock()
}
func (dt *DebugTimer) print() {
fmt.Fprintf(os.Stderr, "\nDebug Timings:\n")
// Define the order we want to print top-level timings
topLevelOrder := []string{
"fetchGitData",
"filesFromCurDir",
"changedFilesFromStatus",
"parseGitLog",
"parseDiffStat",
"makeDiffGraph",
"showColumns",
}
// Print each top-level timing
for _, name := range topLevelOrder {
if duration, ok := dt.timings[name]; ok {
fmt.Fprintf(os.Stderr, " %s: %v\n", name, duration)
// If this is fetchGitData, print its nested timings
if name == "fetchGitData" {
for childName, childDuration := range dt.timings {
if stripped, ok := strings.CutPrefix(childName, " "); ok {
fmt.Fprintf(os.Stderr, " %s: %v\n", stripped, childDuration)
}
}
}
}
}
}
// printDebugFileInfo prints debug information about file processing
func printDebugFileInfo(timer *DebugTimer, files []*File) {
// Find the file that took the longest to find in git log
var slowestFile string
var slowestLines int
for fileName, lines := range timer.fileTimings {
if lines > slowestLines {
slowestFile = fileName
slowestLines = lines
}
}
if slowestFile != "" {
fmt.Fprintf(os.Stderr, "\nSlowest file to find: %s (%d lines)\n", slowestFile, slowestLines)
}
// Check for files that weren't found (no hash means not found in history)
var notFound []string
for _, file := range files {
if file.hash == "" {
notFound = append(notFound, file.Name())
}
}
if len(notFound) > 0 {
fmt.Fprintf(os.Stderr, "\nWarning: %d file(s) not found in git history (possibly beyond %s commit limit):\n", len(notFound), HistoryLimit)
for _, fileName := range notFound {
fmt.Fprintf(os.Stderr, " - %s\n", fileName)
}
}
}
// Name returns the file name, either from the DirEntry or the name field
func (f *File) Name() string {
if f.entry != nil {
return f.entry.Name()
}
return f.name
}
func must[T any](a T, e error) T {
if e != nil {
panic(e)
}
return a
}
// gitResults holds the output of all git commands that can be run in parallel
type gitResults struct {
root string
status []byte
diffStat []byte
currentBranch string
remotes []byte
lsFiles []byte // tracked files from git ls-files
isEmpty bool // true if repo has no commits yet
}
// isEmptyRepo checks if the repository has no commits yet by verifying if HEAD
// exists. If it doesn't, this could mean:
//
// 1. We're in an empty repo (no commits yet) - the case we care about
//
// 2. We're not in a git repo at all - this will be caught by gitRoot() or
// gitStatus()
//
// We check exit code 128 (git's fatal error code) because it's the best signal
// I found for "empty repository"
func isEmptyRepo() bool {
cmd := exec.Command("git", "-c", "core.fsmonitor=false", "rev-parse", "--verify", "HEAD")
err := cmd.Run()
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
return exitErr.ExitCode() == 128
}
}
return false
}
// fetchGitData runs all independent git commands in parallel and returns the results
func fetchGitData(timer *DebugTimer) *gitResults {
results := &gitResults{}
var wg sync.WaitGroup
wg.Go(func() {
start := time.Now()
results.root = gitRoot()
if timer != nil {
timer.record(" gitRoot", time.Since(start))
}
})
wg.Go(func() {
start := time.Now()
results.status = gitStatus()
if timer != nil {
timer.record(" gitStatus", time.Since(start))
}
})
wg.Go(func() {
start := time.Now()
results.currentBranch = headDescription()
if timer != nil {
timer.record(" headDescription", time.Since(start))
}
})
wg.Go(func() {
start := time.Now()
results.remotes = gitRemotes()
if timer != nil {
timer.record(" gitRemotes", time.Since(start))
}
})
wg.Go(func() {
start := time.Now()
results.lsFiles = gitLsFiles()
if timer != nil {
timer.record(" gitLsFiles", time.Since(start))
}
})
// No diff stats in empty repo
if isEmptyRepo() {
results.isEmpty = true
results.diffStat = []byte{}
} else {
wg.Go(func() {
start := time.Now()
results.diffStat = gitDiffStat()
if timer != nil {
timer.record(" gitDiffStat", time.Since(start))
}
})
}
wg.Wait()
return results
}
// printVersion prints version info including the commit hash if available
func printVersion() {
commit := ""
if info, ok := debug.ReadBuildInfo(); ok {
for _, setting := range info.Settings {
if setting.Key == "vcs.revision" {
commit = setting.Value
if len(commit) > 7 {
commit = commit[:7]
}
break
}
}
}
if commit != "" {
fmt.Printf("%s (%s)\n", VERSION, commit)
} else {
fmt.Printf("%s\n", VERSION)
}
}
func usage() {
fmt.Printf(`GIT-LS(1)
NAME
git-ls - show the current directory annotated with links and git info
SYNOPSIS
git ls [<dir>]
DESCRIPTION
Displays the files in the current directory, their current git status, a short diffstat, their last modified date, the author and a portion of the last commit message for that file.
All files are hyperlinked with OSC8 hyperlinks, so you should be able to open them by clicking on them in a properly-configured terminal. The author names are hyperlinked to github if the repository has a github remote, as are commit messages.
OPTIONS
--version
Print the version number and exit
--help
Print this message and exit
--diffWidth=n
Print the diffStat graph with the given width. Default is 4
--format=col1,col2,...
Specify which columns to display and in what order. Valid columns:
status, diff, filename, shorthash, hash, date, author, email,
numstat, commitmessage
Default: status,diff,filename,shorthash,date,author,commitmessage
--mono-hash
Use a single color (cyan) for all commit hashes instead of coloring
each hash uniquely based on its value
--nerdfont
Replace git status letters with Nerd Font icons (requires a Nerd
Font-patched terminal font)
-c, --changed-only
Only show files that have changes (appear in git status). This
filters out unmodified tracked files and shows only files with
status indicators (modified, added, deleted, renamed, etc.)
-s, --sort
Sort files by last git modification date, most recent first.
Files without a date (ignored, untracked, .git) are placed at
the bottom in alphabetical order.
--debug
Print debug timing information to stderr, including which file
took the longest to find in git history and warnings for files
not found (possibly beyond the history limit)
%s
`, link("https://github.com/llimllib/git-ls", "https://github.com/llimllib/git-ls"))
}
func main() {
os.Exit(run())
}
func run() int {
argv := os.Args[1:]
diffWidth := 4
monoHash := false
nerdFont := false
changedOnly := false
sortByDate := false
debug := false
var formatColumns []Column
for len(argv) > 0 {
if argv[0] == "--version" {
printVersion()
return 0
}
if argv[0] == "--help" || argv[0] == "-h" {
usage()
return 0
}
if argv[0] == "--mono-hash" {
monoHash = true
argv = argv[1:]
} else if argv[0] == "--nerdfont" {
nerdFont = true
argv = argv[1:]
} else if argv[0] == "--changed-only" || argv[0] == "-c" {
changedOnly = true
argv = argv[1:]
} else if argv[0] == "--sort" || argv[0] == "-s" {
sortByDate = true
argv = argv[1:]
} else if strings.HasPrefix(argv[0], "--diffWidth") {
if len(argv) == 1 {
if strings.Contains(argv[0], "=") {
parts := strings.SplitN(argv[0], "=", 2)
diffWidth = must(strconv.Atoi(parts[1]))
} else {
fmt.Fprintf(os.Stderr, "--diffWidth requires an argument\n")
return 1
}
argv = argv[1:]
} else {
diffWidth = must(strconv.Atoi(argv[1]))
argv = argv[2:]
}
} else if strings.HasPrefix(argv[0], "--format") {
if len(argv) == 1 {
if strings.Contains(argv[0], "=") {
parts := strings.SplitN(argv[0], "=", 2)
formatColumns = parseFormat(parts[1])
} else {
fmt.Fprintf(os.Stderr, "--format requires an argument\n")
return 1
}
argv = argv[1:]
} else {
formatColumns = parseFormat(argv[1])
argv = argv[2:]
}
} else if strings.HasPrefix(argv[0], "--debug") {
debug = true
argv = argv[1:]
} else {
// Non-flag argument (directory), stop parsing flags
break
}
}
var dir string
if len(argv) > 0 {
dir = argv[0]
if err := os.Chdir(dir); err != nil {
fmt.Fprintf(os.Stderr, "Failed to change directory to %s: %v\n", dir, err)
return 1
}
} else {
dir = "."
}
// Fetch all git data in parallel
var timer *DebugTimer
if debug {
timer = newDebugTimer()
}
var gitData *gitResults
if debug {
timer.time("fetchGitData", func() {
gitData = fetchGitData(timer)
})
} else {
gitData = fetchGitData(nil)
}
// Resolve symlinks to match git's perspective. Git internally resolves
// symlinks when working with worktrees, so we need to do the same to
// ensure filepath.Rel() works correctly in fileStatus().
// https://github.com/llimllib/git-ls/issues/34
resolved := must(filepath.EvalSymlinks(must(filepath.Abs("."))))
curdir := must(filepath.Rel(gitData.root, resolved))
var files []*File
if changedOnly {
// In --changed-only mode, build the file list directly from git
// status so we can show files from subdirectories with their full
// relative paths (e.g. "src/network/server.go" not just "src/")
if debug {
timer.time("changedFilesFromStatus", func() {
files = changedFilesFromStatus(gitData.status, curdir)
})
} else {
files = changedFilesFromStatus(gitData.status, curdir)
}
} else {
var err error
if debug {
timer.time("filesFromCurDir", func() {
files, err = filesFromCurDir(dir, gitData, curdir)
})
} else {
files, err = filesFromCurDir(dir, gitData, curdir)
}
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
return 1
}
}
// Now run git log on the files we'll show
// Skip git log for files that won't have history:
// - I: Ignored files - not tracked by git
// - ??: Untracked files - not in git yet
// - *: .git directory - git metadata, not file history
// - A: Newly added files
// Examples: "A ", "AM", "AD" - staged additions not yet committed
// But "M ", "MM", or mixed dirs like "A ,M " have history
var filesNeedingLog []*File
for _, file := range files {
if file.status == "I" || file.status == "??" || file.status == "*" {
continue
}
// Empty status means unmodified tracked file — it has history
if file.status == "" {
filesNeedingLog = append(filesNeedingLog, file)
continue
}
// Check if ALL statuses in a comma-separated list are new additions
// For directories, status might be "A ,M " if it has both new and modified files
allNew := true
for status := range strings.SplitSeq(file.status, ",") {
status = strings.TrimSpace(status)
// Check if this individual status represents a file with history
// If first char (index) is not 'A' and not untracked, it has history
if len(status) > 0 && status[0] != 'A' && status != "??" {
allNew = false
break
}
}
if !allNew {
filesNeedingLog = append(filesNeedingLog, file)
}
}
if debug {
timer.time("parseGitLog", func() {
if err := parseGitLog(filesNeedingLog, timer); err != nil {
fmt.Fprintf(os.Stderr, "Error: git log streaming failed: %v\n", err)
}
})
timer.time("parseDiffStat", func() {
parseDiffStat(gitData.diffStat, files)
})
} else {
if err := parseGitLog(filesNeedingLog, nil); err != nil {
fmt.Fprintf(os.Stderr, "Error: git log streaming failed: %v\n", err)
return 1
}
parseDiffStat(gitData.diffStat, files)
}
// generate a diffStat graph for every file
if debug {
timer.time("makeDiffGraph", func() {
for _, file := range files {
file.diffStat = makeDiffGraph(file, diffWidth)
}
})
} else {
for _, file := range files {
file.diffStat = makeDiffGraph(file, diffWidth)
}
}
// Sort files
if sortByDate {
sortFilesByDate(files)
} else {
sortFilesByName(files)
}
// Use default columns if not specified
if len(formatColumns) == 0 {
formatColumns = AllColumns()
}
maxWidth := terminalColumns(os.Stdout.Fd())
if maxWidth == 0 {
maxWidth = 80 // default when not a TTY
}
fmt.Printf("%s%s%s\n\n", RED, gitData.currentBranch, RESET)
rctx := &RenderContext{
GithubURL: isGithub(gitData.remotes),
Dir: must(filepath.Abs(".")),
MonoHash: monoHash,
NerdFont: nerdFont,
}
if debug {
timer.time("showColumns", func() {
showColumns(os.Stdout, maxWidth, files, rctx, formatColumns)
})
timer.print()
printDebugFileInfo(timer, filesNeedingLog)
} else {
showColumns(os.Stdout, maxWidth, files, rctx, formatColumns)
}
// Print total +/- summary if there are any diffs
if nFiles, totalPlus, totalMinus := totalDiffStats(files); totalPlus > 0 || totalMinus > 0 {
fileWord := "files"
if nFiles == 1 {
fileWord = "file"
}
fmt.Printf("\n%d %s %s+%d%s %s-%d%s\n", nFiles, fileWord, GREEN, totalPlus, RESET, RED, totalMinus, RESET)
}
return 0
}
// changedFilesFilter strips unchanged files from the files to display
func changedFilesFilter(files []*File) []*File {
var changedFiles []*File
for _, file := range files {
if file.status != "" && file.status != "I" && file.status != "*" {
changedFiles = append(changedFiles, file)
}
}
return changedFiles
}
// filesFromCurDir lists the files in the current directory. `dir` is the
// directory as the user specified it, and `curdir` is the directory as we
// resolved it from the git root
func filesFromCurDir(dir string, gitData *gitResults, curdir string) ([]*File, error) {
var files []*File
osfiles, err := os.ReadDir(".")
if err != nil {
return nil, fmt.Errorf("failed to read directory %s: %v", dir, err)
}
for _, file := range osfiles {
stat, _ := os.Stat(file.Name())
files = append(files, &File{
entry: file,
isDir: file.IsDir(),
isExe: !file.IsDir() && stat.Mode()&0o111 != 0,
})
}
fileStatus(gitData.status, gitData.lsFiles, files, curdir)
// Parse deleted files from git status and merge into file list
deletedFiles := parseDeletedFiles(gitData.status, curdir)
return append(files, deletedFiles...), nil
}
// changedFilesFromStatus builds a list of changed File structs directly from
// git status output. Unlike the normal flow (which reads the current directory
// and then filters), this produces files with full relative paths so that
// --changed-only can show files from subdirectories.
func changedFilesFromStatus(status []byte, curdir string) []*File {
var files []*File
seen := make(map[string]bool)
for line := range strings.SplitSeq(string(status), "\n") {
if len(line) < 3 {
continue
}
statusCode := line[:2]
path := line[3:]
// Skip ignored files
if statusCode == "!!" {
continue
}
// For renames/copies, use the new name and record the old name
var oldName string
if (statusCode[0] == 'R' || statusCode[0] == 'C') && strings.Contains(path, " -> ") {
parts := strings.SplitN(path, " -> ", 2)
oldName = must(filepath.Rel(curdir, parts[0]))
path = parts[1]
}
relPath := must(filepath.Rel(curdir, path))
// Skip files outside the current directory (would start with "..")
if strings.HasPrefix(relPath, "..") {
continue
}
// Deduplicate (a file can appear in status with different codes)
if seen[relPath] {
continue
}
seen[relPath] = true
isDeleted := statusCode == " D" || statusCode == "D "
isExe := false
if !isDeleted {
if stat, err := os.Stat(relPath); err == nil {
isExe = !stat.IsDir() && stat.Mode()&0o111 != 0
}
}
file := &File{
name: relPath,
status: statusCode,
oldName: oldName,
isDeleted: isDeleted,
isExe: isExe,
}
files = append(files, file)
}
return files
}
func parseFormat(formatStr string) []Column {
validCols := ValidColumns()
colNames := strings.Split(formatStr, ",")
var columns []Column
for _, name := range colNames {
name = strings.TrimSpace(name)
if col, ok := validCols[name]; ok {
columns = append(columns, col)
} else {
fmt.Fprintf(os.Stderr, "Error: Invalid column name '%s'\n", name)
fmt.Fprintf(os.Stderr, "Valid columns: status, diff, filename, shorthash, hash, date, author, email, numstat, commitmessage\n")
os.Exit(1)
}
}
return columns
}
// Pulled straight from git:
// https://github.com/git/git/blob/d4cc1ec3/diff.c#L2862-L2874
func scaleLinear(n int, width int, maxChange int) int {
if n == 0 {
return 0
}
/*
* make sure that at least one '-' or '+' is printed if
* there is any change to this path. The easiest way is to
* scale linearly as if the allotted width is one column shorter
* than it is, and then add 1 to the result.
*/
return 1 + (n * (width - 1) / maxChange)
}
// makeDiffGraph turns the total diff for a file/directory into a diff graph
// string.
func makeDiffGraph(file *File, width int) string {
if file.diffSum == nil {
return ""
}
plus := file.diffSum.plus
minus := file.diffSum.minus
if plus+minus <= width {
return fmt.Sprintf("%s%s%s%s%s",
GREEN,
strings.Repeat("+", plus),
RED,
strings.Repeat("-", minus),
RESET)
}
scaledPlus := scaleLinear(plus, width, plus+minus)
scaledMinus := scaleLinear(minus, width, plus+minus)
// scaleLinear guarantees at least 1 for non-zero values, so the sum
// can exceed width. Cap the total to width, preserving the ratio.
if scaledPlus+scaledMinus > width {
scaledMinus = width - scaledPlus
}
return fmt.Sprintf("%s%s%s%s%s",
GREEN,
strings.Repeat("+", scaledPlus),
RED,
strings.Repeat("-", scaledMinus),
RESET)
}
// sortFilesByDate sorts files by commit timestamp descending (most recent first).
// Files without a timestamp (commitTime == 0) go to the bottom, sorted alphabetically.
func sortFilesByDate(files []*File) {
slices.SortStableFunc(files, func(a, b *File) int {
if a.commitTime == 0 && b.commitTime == 0 {
return strings.Compare(strings.ToLower(a.Name()), strings.ToLower(b.Name()))
}
if a.commitTime == 0 {
return 1
}
if b.commitTime == 0 {
return -1
}
if b.commitTime != a.commitTime {
return int(b.commitTime - a.commitTime)
}
return strings.Compare(strings.ToLower(a.Name()), strings.ToLower(b.Name()))
})
}
// sortFilesByName sorts files alphabetically by name (case-insensitive).
func sortFilesByName(files []*File) {
slices.SortFunc(files, func(a, b *File) int {
return strings.Compare(strings.ToLower(a.Name()), strings.ToLower(b.Name()))
})
}
func showColumns(out io.Writer, maxWidth int, files []*File, rctx *RenderContext, columns []Column) {
// Calculate max widths for each column
colWidths := calculateColumnWidths(files, columns, rctx)
// Render each file
for _, file := range files {
lineWidth := 0
// Render each column in order
for i, col := range columns {
// Add space between columns (except before first column)
if i > 0 {
must(fmt.Fprintf(out, " "))
lineWidth += 1
}
// Check if we have space for this column
if lineWidth >= maxWidth {
break
}
// Calculate available width for this column
availableWidth := maxWidth - lineWidth
colWidth := min(colWidths[col], availableWidth)
// Check if there's room for another column after this one.
// If not, we shouldn't pad this column to avoid trailing spaces.
isLastColumn := (i == len(columns)-1) || (lineWidth+colWidth >= maxWidth)
if !isLastColumn && i+1 < len(columns) {
// Check if next column would fit (need space separator + min 1 char)
isLastColumn = (lineWidth+colWidth+1 >= maxWidth)
}
// Render the column
renderer := getColumnRenderer(col)
renderer(out, file, colWidth, rctx, isLastColumn)
lineWidth += colWidth
// If this was the last column that fits, stop rendering
if isLastColumn {
break
}
}
// Reset any remaining formatting (like strikethrough for deleted files)
if file.isDeleted {
must(fmt.Fprintf(out, "%s", RESET))
}
must(fmt.Fprintf(out, "\n"))
}
}
func gitRemotes() []byte {
// disable core.fsmonitor because git will run malicious executables
// https://github.com/califio/publications/blob/main/MADBugs/vim-vs-emacs-vs-claude/Emacs.md
// we do this on every `git` call
cmd := exec.Command("git", "-c", "core.fsmonitor=false", "remote", "-v")
out, err := cmd.Output()
if err != nil {
log.Fatalf("Failed to get git status: %v", err)
}
return out
}
func isGithub(out []byte) string {
githubRe := regexp.MustCompile(`github.com[:/]([\w-_]+)/([\w-_]+)`)
matches := githubRe.FindStringSubmatch(string(out))
if len(matches) == 3 {
return fmt.Sprintf("https://github.com/%s/%s", matches[1], matches[2])
}
return ""
}
// headDescription returns a string describing the current HEAD state,
// matching git-status output: "On branch X", "HEAD detached at X",
// "HEAD detached from X", or rebase-in-progress messages.
// The returned string includes the prefix (e.g. "On branch ").
func headDescription() string {
// Try symbolic-ref first — if it works, we're on a branch
cmd := exec.Command("git", "-c", "core.fsmonitor=false", "symbolic-ref", "--short", "HEAD")
out, err := cmd.Output()
if err == nil {
return "On branch " + strings.TrimSpace(string(out))
}
// We're in detached HEAD state. Check for rebase.
gitDir := gitCommonDir()
if desc := rebaseDescription(gitDir); desc != "" {
return desc
}
// Determine "detached at" vs "detached from" by comparing HEAD to the
// commit we originally detached at (found via reflog).
return detachedDescription()
}
// gitCommonDir returns the path to the git common dir (handles worktrees).
func gitCommonDir() string {
cmd := exec.Command("git", "-c", "core.fsmonitor=false", "rev-parse", "--git-common-dir")
out, err := cmd.Output()
if err != nil {
return ".git"
}
return strings.TrimSpace(string(out))
}
// rebaseDescription checks for an in-progress rebase and returns the
// appropriate status string, or "" if no rebase is active.
func rebaseDescription(gitDir string) string {
ontoBytes, err := os.ReadFile(filepath.Join(gitDir, "rebase-merge", "onto"))
if err == nil {
onto := strings.TrimSpace(string(ontoBytes))
onto = shortOid(onto)
if _, e := os.Stat(filepath.Join(gitDir, "rebase-merge", "interactive")); e == nil {
return "interactive rebase in progress; onto " + onto
}
return "rebase in progress; onto " + onto
}
ontoBytes, err = os.ReadFile(filepath.Join(gitDir, "rebase-apply", "onto"))
if err == nil {
onto := strings.TrimSpace(string(ontoBytes))
onto = shortOid(onto)
return "rebase in progress; onto " + onto
}
return ""
}
// shortOid abbreviates a full hex oid via rev-parse --short.
func shortOid(oid string) string {
cmd := exec.Command("git", "-c", "core.fsmonitor=false", "rev-parse", "--short", oid)
out, err := cmd.Output()
if err != nil {
return oid
}
return strings.TrimSpace(string(out))
}
// detachedDescription returns "HEAD detached at X" or "HEAD detached from X"
// by inspecting the reflog, mirroring git-status behavior.
func detachedDescription() string {
// Walk the reflog to find the checkout/switch entry where we detached.
// That entry's oid is the commit we originally landed on.
cmd := exec.Command("git", "-c", "core.fsmonitor=false",
"reflog", "--format=%H %gs", "HEAD")
reflogOut, err := cmd.Output()
if err != nil {
return "Not currently on any branch."
}
var detachedOid string
for line := range strings.SplitSeq(strings.TrimSpace(string(reflogOut)), "\n") {
if strings.Contains(line, "checkout: ") || strings.Contains(line, "switch: ") {
detachedOid, _, _ = strings.Cut(line, " ")
break
}
}
if detachedOid == "" {
return "Not currently on any branch."
}
// Get current HEAD oid
cmd = exec.Command("git", "-c", "core.fsmonitor=false", "rev-parse", "HEAD")
headOut, err := cmd.Output()
if err != nil {
return "Not currently on any branch."
}
headOid := strings.TrimSpace(string(headOut))
atOrFrom := "at"
if headOid != detachedOid {
atOrFrom = "from"
}
// Try to find a friendly name (tag or branch) that points at detachedOid
name := friendlyRefName(detachedOid)
return "HEAD detached " + atOrFrom + " " + name
}
// friendlyRefName tries to describe an oid with a tag or branch name.
// Falls back to the short hash.
func friendlyRefName(oid string) string {
// Try describe --tags --exact-match first for tags
cmd := exec.Command("git", "-c", "core.fsmonitor=false", "describe", "--tags", "--exact-match", oid)
out, err := cmd.Output()
if err == nil {
return strings.TrimSpace(string(out))
}
// Try branch name via name-rev
cmd = exec.Command("git", "-c", "core.fsmonitor=false", "name-rev", "--name-only", "--no-undefined", "--refs=refs/heads/*", oid)
out, err = cmd.Output()
if err == nil {
name := strings.TrimSpace(string(out))
if name != "" && !strings.Contains(name, "~") && !strings.Contains(name, "^") {
return name
}
}
return shortOid(oid)
}
// gitRoot returns the root directory of the git repository
func gitRoot() string {
cmd := exec.Command("git", "-c", "core.fsmonitor=false", "rev-parse", "--show-toplevel")
out, err := cmd.Output()
if err != nil {
log.Fatalf("Failed to get git status: %v", err)
}
return strings.TrimSpace(string(out))
}
// gitStatus accepts a dir and a slice of files, and adds the git status to
// each file in place
func gitStatus() []byte {
cmd := exec.Command("git", "-c", "core.fsmonitor=false", "status", "--porcelain")
out, err := cmd.Output()
if err != nil {
log.Fatalf("Failed to get git status: %v", err)
}
return out
}
// gitLsFiles returns all tracked files
func gitLsFiles() []byte {
cmd := exec.Command("git", "-c", "core.fsmonitor=false", "ls-files")
out, err := cmd.Output()
if err != nil {
log.Fatalf("Failed to get git ls-files: %v", err)
}
return out
}