Repository navigation
Expand file tree
/
Copy pathmain_test.go
More file actions
1484 lines (1314 loc) · 42.4 KB
/
Copy pathmain_test.go
File metadata and controls
1484 lines (1314 loc) · 42.4 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 (
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"time"
)
func TestMakeDiffGraph(t *testing.T) {
tests := []struct {
name string
file *File
width int
expected string
}{
{
name: "nil diffSum",
file: &File{},
width: 4,
expected: "",
},
{
name: "only additions",
file: &File{diffSum: &Diff{plus: 3, minus: 0}},
width: 4,
expected: GREEN + "+++" + RED + "" + RESET,
},
{
name: "only deletions",
file: &File{diffSum: &Diff{plus: 0, minus: 2}},
width: 4,
expected: GREEN + "" + RED + "--" + RESET,
},
{
name: "additions and deletions within width",
file: &File{diffSum: &Diff{plus: 2, minus: 2}},
width: 4,
expected: GREEN + "++" + RED + "--" + RESET,
},
{
name: "additions and deletions exceeding width are scaled",
file: &File{diffSum: &Diff{plus: 10, minus: 10}},
width: 4,
expected: GREEN + "++" + RED + "--" + RESET,
},
{
name: "new file with 4 additions fits in width 4",
file: &File{diffSum: &Diff{plus: 4, minus: 0}},
width: 4,
expected: GREEN + "++++" + RED + "" + RESET,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := makeDiffGraph(tt.file, tt.width)
if result != tt.expected {
t.Errorf("makeDiffGraph() = %q, expected %q", result, tt.expected)
}
})
}
}
func TestIsGithub(t *testing.T) {
tests := []struct {
name string
input []byte
expected string
}{
{
name: "Valid GitHub remote",
input: []byte("origin\tgit@github.com:username/repo.git (fetch)\norigin\tgit@github.com:username/repo.git (push)"),
expected: "https://github.com/username/repo",
},
{
name: "Valid GitHub remote with HTTP",
input: []byte("origin\thttps://github.com/username/repo.git (fetch)\norigin\thttps://github.com/username/repo.git (push)"),
expected: "https://github.com/username/repo",
},
{
name: "Invalid remote",
input: []byte("origin\tgit@example.com:username/repo.git (fetch)\norigin\tgit@example.com:username/repo.git (push)"),
expected: "",
},
{
name: "Empty input",
input: []byte{},
expected: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := isGithub(tt.input)
if result != tt.expected {
t.Errorf("isGithub(%s) = %q, expected %q", tt.input, result, tt.expected)
}
})
}
}
type mockDirEntry struct {
name string
}
func (m *mockDirEntry) Name() string {
return m.name
}
func (m *mockDirEntry) IsDir() bool {
return false
}
func (m *mockDirEntry) Type() os.FileMode {
return 0
}
func (m *mockDirEntry) Info() (os.FileInfo, error) {
return nil, nil
}
func TestFileStatus(t *testing.T) {
tests := []struct {
name string
status string
files []*File
dir string
expected []string
expectedOldName []string // expected oldName per file (empty string = not set)
}{
{
name: "empty status and files",
status: "",
files: []*File{},
expected: []string{},
dir: "",
},
{
name: "single file with modified status",
status: " M file.go",
files: []*File{
{entry: &mockDirEntry{name: "file.go"}},
},
expected: []string{" M"},
dir: "",
},
{
name: "multiple files with different statuses",
status: "M file1.go\nA file2.go",
files: []*File{
{entry: &mockDirEntry{name: "file1.go"}},
{entry: &mockDirEntry{name: "file2.go"}},
{entry: &mockDirEntry{name: "ignored.go"}},
},
expected: []string{"M ", "A ", "I"},
dir: "",
},
{
name: ".git directory status",
status: "M file1.go",
files: []*File{
{entry: &mockDirEntry{name: "file1.go"}},
{entry: &mockDirEntry{name: ".git"}},
},
expected: []string{"M ", "*"},
dir: "",
},
{
name: "subdirectory",
status: "M homedir/file2.go",
files: []*File{
{entry: &mockDirEntry{name: "file2.go"}},
},
dir: "homedir/",
expected: []string{"M "},
},
{
name: "rename maps status to new filename",
status: "R old-name.txt -> new-name.txt",
files: []*File{{entry: &mockDirEntry{name: "new-name.txt"}}},
expected: []string{"R "},
expectedOldName: []string{"old-name.txt"},
dir: "",
},
{
name: "copy maps status to new filename",
status: "C source.txt -> copy.txt",
files: []*File{{entry: &mockDirEntry{name: "copy.txt"}}},
expected: []string{"C "},
expectedOldName: []string{"source.txt"},
dir: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Build lsFiles data: all files in status (except ignored/untracked) are tracked
var lsFilesBuilder strings.Builder
for i, f := range tt.files {
// Files with status in git (not ignored, not untracked) are tracked
if tt.expected[i] != "I" && tt.expected[i] != "??" && f.entry != nil && f.entry.Name() != ".git" {
lsFilesBuilder.WriteString(f.entry.Name())
lsFilesBuilder.WriteString("\n")
}
}
fileStatus([]byte(tt.status), []byte(lsFilesBuilder.String()), tt.files, tt.dir)
for i, f := range tt.files {
if f.status != tt.expected[i] {
t.Errorf("expected status %q for %s, got %q", tt.expected[i], f.entry.Name(), f.status)
}
if tt.expectedOldName != nil {
if f.oldName != tt.expectedOldName[i] {
t.Errorf("expected oldName %q for %s, got %q", tt.expectedOldName[i], f.entry.Name(), f.oldName)
}
}
}
})
}
}
// parseArgs extracts diffWidth and directory from command line arguments.
// This is extracted from main() for testability.
func parseArgs(argv []string) (diffWidth int, dir string) {
diffWidth = 4
for len(argv) > 0 {
if argv[0] == "--version" || argv[0] == "--help" || argv[0] == "-h" {
return diffWidth, ""
}
if len(argv[0]) > 0 && argv[0][:2] == "--" && len(argv[0]) > 11 && argv[0][:11] == "--diffWidth" {
if len(argv) == 1 {
if len(argv[0]) > 11 && argv[0][11] == '=' {
parts := make([]string, 2)
parts[0] = argv[0][:11]
parts[1] = argv[0][12:]
diffWidth, _ = parseInt(parts[1])
}
argv = argv[1:]
} else {
diffWidth, _ = parseInt(argv[1])
argv = argv[2:]
}
} else {
// Non-flag argument (directory), stop parsing flags
break
}
}
if len(argv) > 0 {
dir = argv[0]
} else {
dir = "."
}
return diffWidth, dir
}
func parseInt(s string) (int, error) {
var n int
for _, c := range s {
if c < '0' || c > '9' {
return 0, fmt.Errorf("invalid integer: %s", s)
}
n = n*10 + int(c-'0')
}
return n, nil
}
func TestParseArgs(t *testing.T) {
tests := []struct {
name string
args []string
expectedDir string
expectedWidth int
}{
{
name: "no arguments",
args: []string{},
expectedDir: ".",
expectedWidth: 4,
},
{
name: "directory argument",
args: []string{"bin"},
expectedDir: "bin",
expectedWidth: 4,
},
{
name: "directory with path",
args: []string{"some/nested/dir"},
expectedDir: "some/nested/dir",
expectedWidth: 4,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
width, dir := parseArgs(tt.args)
if dir != tt.expectedDir {
t.Errorf("parseArgs(%v) dir = %q, expected %q", tt.args, dir, tt.expectedDir)
}
if width != tt.expectedWidth {
t.Errorf("parseArgs(%v) width = %d, expected %d", tt.args, width, tt.expectedWidth)
}
})
}
}
// TestDirectoryArgDoesNotHang tests that passing a directory argument doesn't cause an infinite loop.
// This is a regression test for a bug where the argument parsing loop would hang forever
// when a non-flag argument (like a directory name) was passed.
func TestDirectoryArgDoesNotHang(t *testing.T) {
done := make(chan bool, 1)
go func() {
// This should complete almost instantly
_, dir := parseArgs([]string{"bin"})
if dir != "bin" {
t.Errorf("Expected dir to be 'bin', got %q", dir)
}
done <- true
}()
select {
case <-done:
// Test passed
case <-time.After(1 * time.Second):
t.Fatal("parseArgs hung when given a directory argument - argument parsing loop is infinite")
}
}
// TestShowFileHyperlinks verifies that file hyperlinks are generated correctly.
// This is a regression test for a bug where passing a directory argument would
// cause incorrect hyperlinks (e.g., "git-ls bin" would generate links like
// "bin/bin/release.sh" instead of "bin/release.sh").
func TestShowFileHyperlinks(t *testing.T) {
tests := []struct {
name string
dir string // absolute path passed to show()
fileName string
expectedURL string // the file path portion we expect in the URL
}{
{
name: "file in subdirectory",
dir: "/repo/bin",
fileName: "release.sh",
expectedURL: "/repo/bin/release.sh",
},
{
name: "file in root",
dir: "/repo",
fileName: "main.go",
expectedURL: "/repo/main.go",
},
{
name: "nested subdirectory",
dir: "/repo/src/pkg",
fileName: "util.go",
expectedURL: "/repo/src/pkg/util.go",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
files := []*File{
{entry: &mockDirEntry{name: tt.fileName}},
}
var buf strings.Builder
rctx := &RenderContext{
GithubURL: "",
Dir: tt.dir,
MonoHash: false,
}
showColumns(&buf, 200, files, rctx, AllColumns())
output := buf.String()
// Check that the output contains the correct file URL path
// The hyperlink format is: \e]8;;<url>\e\<text>\e]8;;\e\
expectedPath := fmt.Sprintf("file://%s%s", must(os.Hostname()), tt.expectedURL)
if !strings.Contains(output, expectedPath) {
t.Errorf("Expected output to contain %q, but got:\n%q", expectedPath, output)
}
// Make sure we don't have a doubled directory (the bug we're preventing)
// e.g., /repo/bin/bin/release.sh
doubledDir := tt.dir + "/" + tt.dir[strings.LastIndex(tt.dir, "/")+1:]
if strings.Contains(output, doubledDir+"/") {
t.Errorf("Found doubled directory path in output: %q", output)
}
})
}
}
// TestWorktreeWithSymlink tests that git-ls works correctly in a worktree
// accessed via symlink. This is a regression test for issue #34.
func TestWorktreeWithSymlink(t *testing.T) {
// Create a temporary directory for our test
tmpDir := t.TempDir()
// Create a git repo with one commit
repoDir := tmpDir + "/repo"
if err := os.Mkdir(repoDir, 0o755); err != nil {
t.Fatalf("Failed to create repo dir: %v", err)
}
// Initialize git repo
if err := runCmd(repoDir, "git", "init", "-b", "main"); err != nil {
t.Fatalf("Failed to init repo: %v", err)
}
// Configure git user for this test repo
if err := runCmd(repoDir, "git", "config", "user.email", "test@example.com"); err != nil {
t.Fatalf("Failed to set git email: %v", err)
}
if err := runCmd(repoDir, "git", "config", "user.name", "Test User"); err != nil {
t.Fatalf("Failed to set git name: %v", err)
}
// Create and commit a file
if err := os.WriteFile(repoDir+"/file1.txt", []byte("hello"), 0o644); err != nil {
t.Fatalf("Failed to write file: %v", err)
}
if err := runCmd(repoDir, "git", "add", "file1.txt"); err != nil {
t.Fatalf("Failed to add file: %v", err)
}
if err := runCmd(repoDir, "git", "commit", "-m", "initial commit"); err != nil {
t.Fatalf("Failed to commit: %v", err)
}
// Create a worktree
wtDir := tmpDir + "/worktree"
if err := runCmd(repoDir, "git", "worktree", "add", wtDir, "-b", "wt-branch"); err != nil {
t.Fatalf("Failed to create worktree: %v", err)
}
// Add an untracked file in the worktree
if err := os.WriteFile(wtDir+"/rootfile.txt", []byte("untracked"), 0o644); err != nil {
t.Fatalf("Failed to write untracked file: %v", err)
}
// Create a symlink to the worktree
linkDir := tmpDir + "/link-to-wt"
if err := os.Symlink(wtDir, linkDir); err != nil {
t.Fatalf("Failed to create symlink: %v", err)
}
// Test case 1: Run from real worktree
t.Run("real worktree", func(t *testing.T) {
// Change to the real worktree directory
oldDir, _ := os.Getwd()
defer func() {
if err := os.Chdir(oldDir); err != nil {
t.Logf("Failed to restore directory: %v", err)
}
}()
if err := os.Chdir(wtDir); err != nil {
t.Fatalf("Failed to chdir to worktree: %v", err)
}
// This should not panic
// We're testing the internal functions that were panicking
gitData := fetchGitData(nil)
curdir, err := filepath.Rel(gitData.root, must(filepath.Abs(".")))
if err != nil {
t.Fatalf("Failed to get curdir: %v", err)
}
osfiles, err := os.ReadDir(".")
if err != nil {
t.Fatalf("Failed to read directory: %v", err)
}
var files []*File
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,
})
}
// This was panicking before the fix
fileStatus(gitData.status, gitData.lsFiles, files, curdir)
// Verify we found the untracked file
found := false
for _, f := range files {
if f.Name() == "rootfile.txt" {
found = true
break
}
}
if !found {
t.Error("Expected to find rootfile.txt in file list")
}
})
// Test case 2: Run from symlink to worktree
t.Run("symlink to worktree", func(t *testing.T) {
// Change to the symlink directory
oldDir, _ := os.Getwd()
defer func() {
if err := os.Chdir(oldDir); err != nil {
t.Logf("Failed to restore directory: %v", err)
}
}()
if err := os.Chdir(linkDir); err != nil {
t.Fatalf("Failed to chdir to symlink: %v", err)
}
// This should not panic
gitData := fetchGitData(nil)
curdir, err := filepath.Rel(gitData.root, must(filepath.Abs(".")))
if err != nil {
t.Fatalf("Failed to get curdir: %v", err)
}
osfiles, err := os.ReadDir(".")
if err != nil {
t.Fatalf("Failed to read directory: %v", err)
}
var files []*File
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,
})
}
// This was panicking before the fix
fileStatus(gitData.status, gitData.lsFiles, files, curdir)
// Verify we found the untracked file
found := false
for _, f := range files {
if f.Name() == "rootfile.txt" {
found = true
break
}
}
if !found {
t.Error("Expected to find rootfile.txt in file list")
}
})
}
// runCmd is a helper to run a command in a specific directory
func runCmd(dir string, name string, args ...string) error {
cmd := exec.Command(name, args...)
cmd.Dir = dir
out, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("%w: %s", err, string(out))
}
return nil
}
// TestSubdirectoryGitInfo tests that git-ls shows git information for files
// when run on a subdirectory. This is a regression test for a bug where
// parseGitLogStreaming wasn't using --relative, causing paths from git log
// to not match the files we were looking for.
func TestSubdirectoryGitInfo(t *testing.T) {
// Create a temporary directory for our test
tmpDir := t.TempDir()
// Create a git repo
repoDir := tmpDir + "/repo"
if err := os.Mkdir(repoDir, 0o755); err != nil {
t.Fatalf("Failed to create repo dir: %v", err)
}
// Initialize git repo
if err := runCmd(repoDir, "git", "init", "-b", "main"); err != nil {
t.Fatalf("Failed to init repo: %v", err)
}
// Configure git user for this test repo
if err := runCmd(repoDir, "git", "config", "user.email", "test@example.com"); err != nil {
t.Fatalf("Failed to set git email: %v", err)
}
if err := runCmd(repoDir, "git", "config", "user.name", "Test User"); err != nil {
t.Fatalf("Failed to set git name: %v", err)
}
// Create a subdirectory with a file
subDir := repoDir + "/docs"
if err := os.Mkdir(subDir, 0o755); err != nil {
t.Fatalf("Failed to create subdir: %v", err)
}
if err := os.WriteFile(subDir+"/README.md", []byte("# Documentation"), 0o644); err != nil {
t.Fatalf("Failed to write file: %v", err)
}
// Commit the file
if err := runCmd(repoDir, "git", "add", "docs/README.md"); err != nil {
t.Fatalf("Failed to add file: %v", err)
}
if err := runCmd(repoDir, "git", "commit", "-m", "Add documentation"); err != nil {
t.Fatalf("Failed to commit: %v", err)
}
// Change to the subdirectory (simulating: git-ls docs)
oldDir, _ := os.Getwd()
defer func() {
if err := os.Chdir(oldDir); err != nil {
t.Logf("Failed to restore directory: %v", err)
}
}()
if err := os.Chdir(subDir); err != nil {
t.Fatalf("Failed to chdir to subdirectory: %v", err)
}
// Read the files in the subdirectory
osfiles, err := os.ReadDir(".")
if err != nil {
t.Fatalf("Failed to read directory: %v", err)
}
var files []*File
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,
})
}
// Run parseGitLogStreaming to get git info
if err := parseGitLog(files, nil); err != nil {
t.Fatalf("parseGitLog failed: %v", err)
}
// Verify that README.md has git info populated
var readme *File
for _, f := range files {
if f.Name() == "README.md" {
readme = f
break
}
}
if readme == nil {
t.Fatal("README.md not found in file list")
}
// Check that git info was populated
if readme.hash == "" {
t.Error("Expected README.md to have a commit hash, but it was empty")
}
if readme.author == "" {
t.Error("Expected README.md to have an author, but it was empty")
}
if readme.message == "" {
t.Error("Expected README.md to have a commit message, but it was empty")
}
if readme.lastModified == "" {
t.Error("Expected README.md to have a last modified date, but it was empty")
}
// Verify the values are correct
if readme.author != "Test User" {
t.Errorf("Expected author 'Test User', got %q", readme.author)
}
if readme.message != "Add documentation" {
t.Errorf("Expected message 'Add documentation', got %q", readme.message)
}
}
// TestEmptyRepository tests that git-ls works correctly in an empty repository
// (one with no commits yet). This is a regression test for issue #35.
func TestEmptyRepository(t *testing.T) {
// Create a temporary directory for our test
tmpDir := t.TempDir()
// Create an empty git repo (no commits)
repoDir := tmpDir + "/empty-repo"
if err := os.Mkdir(repoDir, 0o755); err != nil {
t.Fatalf("Failed to create repo dir: %v", err)
}
// Initialize git repo
if err := runCmd(repoDir, "git", "init", "-b", "main"); err != nil {
t.Fatalf("Failed to init repo: %v", err)
}
// Configure git user for this test repo
if err := runCmd(repoDir, "git", "config", "user.email", "test@example.com"); err != nil {
t.Fatalf("Failed to set git email: %v", err)
}
if err := runCmd(repoDir, "git", "config", "user.name", "Test User"); err != nil {
t.Fatalf("Failed to set git name: %v", err)
}
// Create a file but don't commit it
if err := os.WriteFile(repoDir+"/test.txt", []byte("hello"), 0o644); err != nil {
t.Fatalf("Failed to write file: %v", err)
}
// Change to the empty repo directory
oldDir, _ := os.Getwd()
defer func() {
if err := os.Chdir(oldDir); err != nil {
t.Logf("Failed to restore directory: %v", err)
}
}()
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("Failed to chdir to empty repo: %v", err)
}
// This should not crash with "fatal: ambiguous argument 'HEAD'"
// Before the fix, gitDiffStat() would call log.Fatalf() here
diffStat := gitDiffStat()
// In an empty repo with no commits, there should be no diff stats
// (because there's no HEAD to compare against)
if len(diffStat) != 0 {
t.Logf("Expected empty diffStat in empty repo, got: %s", string(diffStat))
// Note: This is logged but not a failure - the important thing is
// that gitDiffStat() didn't crash
}
t.Log("Successfully ran gitDiffStat() in empty repository without crashing")
}
// TestChangedOnly verifies that the --changed-only flag filters files
// to only show those with git status.
func TestChangedOnly(t *testing.T) {
// Create test files with different statuses
files := []*File{
{entry: &mockDirEntry{name: "modified.go"}, status: "M "},
{entry: &mockDirEntry{name: "untracked.go"}, status: "??"},
{entry: &mockDirEntry{name: "clean.go"}, status: ""},
{entry: &mockDirEntry{name: "added.go"}, status: "A "},
{entry: &mockDirEntry{name: "another-clean.go"}, status: ""},
{name: "deleted.go", status: "D ", isDeleted: true},
{entry: &mockDirEntry{name: "ignored.log"}, status: "I"},
{entry: &mockDirEntry{name: ".git"}, status: "*"},
}
// Filter to only changed files
changedFiles := changedFilesFilter(files)
// Verify we got only the files with status (ignored files excluded)
if len(changedFiles) != 4 {
t.Errorf("Expected 4 changed files, got %d", len(changedFiles))
}
// Verify the correct files were kept
expectedNames := map[string]bool{
"modified.go": true,
"untracked.go": true,
"added.go": true,
"deleted.go": true,
}
for _, f := range changedFiles {
name := f.Name()
if !expectedNames[name] {
t.Errorf("Unexpected file in changed list: %s", name)
}
delete(expectedNames, name)
}
if len(expectedNames) > 0 {
for name := range expectedNames {
t.Errorf("Expected file %s was not in changed list", name)
}
}
}
// TestUnmodifiedFileGetsGitInfo verifies that clean tracked files (empty status)
// get their commit information populated. This is a regression test for a bug
// introduced with --changed-only where the filesNeedingLog filter excluded files
// with empty status, causing unmodified files to show no commit info.
func TestUnmodifiedFileGetsGitInfo(t *testing.T) {
tmpDir := t.TempDir()
repoDir := tmpDir + "/repo"
if err := os.Mkdir(repoDir, 0o755); err != nil {
t.Fatalf("Failed to create repo dir: %v", err)
}
if err := runCmd(repoDir, "git", "init", "-b", "main"); err != nil {
t.Fatalf("Failed to init repo: %v", err)
}
if err := runCmd(repoDir, "git", "config", "user.email", "test@example.com"); err != nil {
t.Fatalf("Failed to set git email: %v", err)
}
if err := runCmd(repoDir, "git", "config", "user.name", "Test User"); err != nil {
t.Fatalf("Failed to set git name: %v", err)
}
if err := os.WriteFile(repoDir+"/clean.go", []byte("package main\n"), 0o644); err != nil {
t.Fatalf("Failed to write file: %v", err)
}
if err := runCmd(repoDir, "git", "add", "clean.go"); err != nil {
t.Fatalf("Failed to add file: %v", err)
}
if err := runCmd(repoDir, "git", "commit", "-m", "add clean file"); err != nil {
t.Fatalf("Failed to commit: %v", err)
}
oldDir, _ := os.Getwd()
defer func() {
if err := os.Chdir(oldDir); err != nil {
t.Logf("Failed to restore directory: %v", err)
}
}()
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("Failed to chdir: %v", err)
}
osfiles, err := os.ReadDir(".")
if err != nil {
t.Fatalf("Failed to read directory: %v", err)
}
var files []*File
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,
})
}
gitData := fetchGitData(nil)
resolved := must(filepath.EvalSymlinks(must(filepath.Abs("."))))
curdir := must(filepath.Rel(gitData.root, resolved))
fileStatus(gitData.status, gitData.lsFiles, files, curdir)
// Replicate the filesNeedingLog filter from main() — this is the code under test
var filesNeedingLog []*File
for _, file := range files {
if file.status == "I" || file.status == "??" || file.status == "*" {
continue
}
if file.status == "" {
filesNeedingLog = append(filesNeedingLog, file)
continue
}
allNew := true
for status := range strings.SplitSeq(file.status, ",") {
status = strings.TrimSpace(status)
if len(status) > 0 && status[0] != 'A' && status != "??" {
allNew = false
break
}
}
if !allNew {
filesNeedingLog = append(filesNeedingLog, file)
}
}
if err := parseGitLog(filesNeedingLog, nil); err != nil {
t.Fatalf("parseGitLog failed: %v", err)
}
var clean *File
for _, f := range files {
if f.Name() == "clean.go" {
clean = f
break
}
}
if clean == nil {
t.Fatal("clean.go not found in file list")
}
if clean.hash == "" {
t.Error("Expected unmodified tracked file to have a commit hash, but it was empty")
}
if clean.message != "add clean file" {
t.Errorf("Expected message 'add clean file', got %q", clean.message)
}
}
// TestSkipGitLogForIgnoredFiles verifies that we skip git log for files
// that don't have meaningful history (ignored, untracked, .git, newly added)
func TestSkipGitLogForIgnoredFiles(t *testing.T) {
files := []*File{
{entry: &mockDirEntry{name: "modified.go"}, status: "M "},
{entry: &mockDirEntry{name: "ignored.log"}, status: "I"},
{entry: &mockDirEntry{name: "untracked.go"}, status: "??"},
{entry: &mockDirEntry{name: ".git"}, status: "*"},
{entry: &mockDirEntry{name: "added.go"}, status: "A "},
{entry: &mockDirEntry{name: "added-modified.go"}, status: "AM"},
{entry: &mockDirEntry{name: "dir-with-changes"}, status: "A ,M "},
}
// Filter files that need git log (mimicking the optimization)
var filesNeedingLog []*File
for _, file := range files {
if file.status == "I" || file.status == "??" || file.status == "*" {
continue
}
// Check if ALL statuses are additions (no history to look up)
allNew := true
for status := range strings.SplitSeq(file.status, ",") {
status = strings.TrimSpace(status)
if len(status) > 0 && status[0] != 'A' && status != "??" {
allNew = false
break
}
}
if !allNew {
filesNeedingLog = append(filesNeedingLog, file)
}
}
// Should have 2 files: modified.go and dir-with-changes
// Skip: ignored, untracked, .git, purely added files
if len(filesNeedingLog) != 2 {
t.Errorf("Expected 2 files needing git log, got %d", len(filesNeedingLog))
}
expectedNames := map[string]bool{
"modified.go": true,
"dir-with-changes": true,
}
for _, f := range filesNeedingLog {
name := f.Name()
if !expectedNames[name] {
t.Errorf("Unexpected file needing git log: %s", name)
}
delete(expectedNames, name)
}
if len(expectedNames) > 0 {
for name := range expectedNames {
t.Errorf("Expected file %s was not in files needing git log", name)
}
}
}
// the file's previous name. This is a regression test for a bug where renamed
// files had no git log info because git log couldn't find history under the
// new name.
func TestRenamedFileGitInfo(t *testing.T) {
tmpDir := t.TempDir()
repoDir := tmpDir + "/repo"
if err := os.Mkdir(repoDir, 0o755); err != nil {
t.Fatalf("Failed to create repo dir: %v", err)
}
if err := runCmd(repoDir, "git", "init", "-b", "main"); err != nil {
t.Fatalf("Failed to init repo: %v", err)
}
if err := runCmd(repoDir, "git", "config", "user.email", "test@example.com"); err != nil {
t.Fatalf("Failed to set git email: %v", err)
}
if err := runCmd(repoDir, "git", "config", "user.name", "Test User"); err != nil {
t.Fatalf("Failed to set git name: %v", err)
}
// Create and commit a file
if err := os.WriteFile(repoDir+"/old-name.txt", []byte("hello world\n"), 0o644); err != nil {
t.Fatalf("Failed to write file: %v", err)
}
if err := runCmd(repoDir, "git", "add", "old-name.txt"); err != nil {
t.Fatalf("Failed to add file: %v", err)
}
if err := runCmd(repoDir, "git", "commit", "-m", "initial commit"); err != nil {
t.Fatalf("Failed to commit: %v", err)
}
// Rename the file and stage it
if err := runCmd(repoDir, "git", "mv", "old-name.txt", "new-name.txt"); err != nil {
t.Fatalf("Failed to rename file: %v", err)
}
// Change to the repo directory
oldDir, _ := os.Getwd()
defer func() {
if err := os.Chdir(oldDir); err != nil {
t.Logf("Failed to restore directory: %v", err)
}
}()
if err := os.Chdir(repoDir); err != nil {
t.Fatalf("Failed to chdir: %v", err)
}
osfiles, err := os.ReadDir(".")
if err != nil {
t.Fatalf("Failed to read directory: %v", err)