gitlogue 0.9.0

A Git history screensaver - watch your code rewrite itself
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
use anyhow::{Context, Result};
use chrono::{DateTime, Local, Utc};
use chrono_english::{parse_date_string, Dialect};
use git2::{Commit as Git2Commit, Delta, DiffOptions, Oid, Repository};
use globset::{Glob, GlobSet, GlobSetBuilder};
use rand::RngExt;
use std::cell::RefCell;
use std::path::Path;
use std::sync::OnceLock;

// Thread-safe global pattern matcher for user-defined ignore patterns
static USER_PATTERNS: OnceLock<GlobSet> = OnceLock::new();

// Maximum blob size to read (500KB)
const MAX_BLOB_SIZE: usize = 500 * 1024;

// Maximum number of changed lines per file to animate
// Files with more changes will be skipped to prevent performance issues
const MAX_CHANGE_LINES: usize = 2000;

/// Specifies which working tree changes to show in diff mode
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub enum DiffMode {
    #[default]
    Staged, // Only staged changes (index vs HEAD)
    Unstaged, // Only unstaged changes (workdir vs index)
}

// Files to exclude from diff animation (lock files and generated files)
const EXCLUDED_FILES: &[&str] = &[
    // JavaScript/Node.js
    "yarn.lock",
    "package-lock.json",
    "pnpm-lock.yaml",
    "bun.lock",
    "bun.lockb",
    // Rust
    "Cargo.lock",
    // Ruby
    "Gemfile.lock",
    // Python
    "poetry.lock",
    "Pipfile.lock",
    "uv.lock",
    // PHP
    "composer.lock",
    // Go
    "go.sum",
    // Swift
    "Package.resolved",
    // Dart/Flutter
    "pubspec.lock",
    // .NET/C#
    "packages.lock.json",
    "project.assets.json",
    // Elixir
    "mix.lock",
    // Java/Gradle
    "gradle.lockfile",
    "buildscript-gradle.lockfile",
    // Scala
    "build.sbt.lock",
    // Bazel
    "MODULE.bazel.lock",
];

// File patterns to exclude from diff animation
const EXCLUDED_PATTERNS: &[&str] = &[
    // Minified files
    ".min.js",
    ".min.css",
    // Bundled files
    ".bundle.js",
    ".bundle.css",
    // Source maps
    ".js.map",
    ".css.map",
    ".d.ts.map",
    // Test snapshots
    ".snap",
    "__snapshots__",
];

/// Initialize user-defined ignore patterns (call once at startup)
pub fn init_ignore_patterns(patterns: &[String]) -> Result<()> {
    if patterns.is_empty() {
        return Ok(());
    }

    let mut builder = GlobSetBuilder::new();

    for pattern in patterns {
        let glob =
            Glob::new(pattern).with_context(|| format!("Invalid glob pattern: {}", pattern))?;
        builder.add(glob);
    }

    let globset = builder.build().context("Failed to build glob set")?;

    USER_PATTERNS
        .set(globset)
        .map_err(|_| anyhow::anyhow!("User patterns already initialized"))?;

    Ok(())
}

/// Check if a file should be excluded from diff animation
pub fn should_exclude_file(path: &str) -> bool {
    // Check user-defined patterns first
    if let Some(patterns) = USER_PATTERNS.get() {
        if patterns.is_match(path) {
            return true;
        }
    }

    let filename = path.rsplit('/').next().unwrap_or(path);

    // Check if it's a lock file
    if EXCLUDED_FILES.contains(&filename) {
        return true;
    }

    // Check if it matches excluded patterns
    for pattern in EXCLUDED_PATTERNS {
        if filename.ends_with(pattern) || path.contains(pattern) {
            return true;
        }
    }

    false
}

// Check if a commit matches the author filter pattern (case-insensitive partial match)
fn matches_author(commit: &Git2Commit, pattern: &str) -> bool {
    let author = commit.author();
    let name = author.name().unwrap_or("");
    let email = author.email().unwrap_or("");
    let pattern_lower = pattern.to_lowercase();

    name.to_lowercase().contains(&pattern_lower) || email.to_lowercase().contains(&pattern_lower)
}

// Parse a date string using chrono-english (supports Git-like formats)
pub fn parse_date(input: &str) -> Result<DateTime<Utc>> {
    let now = Local::now();

    parse_date_string(input, now, Dialect::Us)
        .map(|dt| dt.with_timezone(&Utc))
        .with_context(|| format!("Invalid date format: '{}'. Use formats like '2024-01-01', '1 week ago', 'yesterday'", input))
}

// Check if a commit date is within the specified date range
fn matches_date_filter(
    commit: &Git2Commit,
    before: Option<&DateTime<Utc>>,
    after: Option<&DateTime<Utc>>,
) -> Result<bool> {
    let timestamp = commit.author().when().seconds();
    let commit_date = DateTime::from_timestamp(timestamp, 0).context("Invalid commit timestamp")?;

    if let Some(before_date) = before {
        if commit_date > *before_date {
            return Ok(false);
        }
    }

    if let Some(after_date) = after {
        if commit_date < *after_date {
            return Ok(false);
        }
    }

    Ok(true)
}

pub struct GitRepository {
    repo: Repository,
    commit_cache: RefCell<Option<Vec<Oid>>>,
    // Shared index for both cache-based playback (asc/desc) and range playback.
    // These modes are mutually exclusive based on CLI arguments.
    commit_index: RefCell<usize>,
    commit_range: RefCell<Option<Vec<Oid>>>,
    author_filter: Option<String>,
    before_filter: Option<DateTime<Utc>>,
    after_filter: Option<DateTime<Utc>>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum FileStatus {
    Added,
    Deleted,
    Modified,
    Renamed,
    Copied,
    Unmodified,
}

impl FileStatus {
    pub fn as_str(&self) -> &str {
        match self {
            FileStatus::Added => "A",
            FileStatus::Deleted => "D",
            FileStatus::Modified => "M",
            FileStatus::Renamed => "R",
            FileStatus::Copied => "C",
            FileStatus::Unmodified => "U",
        }
    }
}

impl From<Delta> for FileStatus {
    fn from(delta: Delta) -> Self {
        match delta {
            Delta::Added => FileStatus::Added,
            Delta::Deleted => FileStatus::Deleted,
            Delta::Modified => FileStatus::Modified,
            Delta::Renamed => FileStatus::Renamed,
            Delta::Copied => FileStatus::Copied,
            Delta::Unmodified => FileStatus::Unmodified,
            _ => FileStatus::Modified,
        }
    }
}

#[derive(Debug, Clone)]
pub enum LineChangeType {
    Addition,
    Deletion,
    Context,
}

#[derive(Debug, Clone)]
pub struct LineChange {
    pub change_type: LineChangeType,
    pub content: String,
    #[allow(dead_code)]
    pub old_line_no: Option<usize>,
    #[allow(dead_code)]
    pub new_line_no: Option<usize>,
}

#[derive(Debug, Clone)]
pub struct DiffHunk {
    pub old_start: usize,
    #[allow(dead_code)]
    pub old_lines: usize,
    #[allow(dead_code)]
    pub new_start: usize,
    #[allow(dead_code)]
    pub new_lines: usize,
    pub lines: Vec<LineChange>,
}

#[derive(Debug, Clone)]
pub struct FileChange {
    pub path: String,
    #[allow(dead_code)]
    pub old_path: Option<String>,
    pub status: FileStatus,
    #[allow(dead_code)]
    pub is_binary: bool,
    pub is_excluded: bool,
    pub exclusion_reason: Option<String>,
    pub old_content: Option<String>,
    #[allow(dead_code)]
    pub new_content: Option<String>,
    pub hunks: Vec<DiffHunk>,
    #[allow(dead_code)]
    pub diff: String,
}

#[derive(Debug, Clone)]
pub struct CommitMetadata {
    pub hash: String,
    pub author: String,
    pub date: DateTime<Utc>,
    pub message: String,
    pub changes: Vec<FileChange>,
}

impl CommitMetadata {
    /// Returns indices sorted in FileTree display order (directory -> filename)
    pub fn sorted_file_indices(&self) -> Vec<usize> {
        let mut indices: Vec<usize> = (0..self.changes.len()).collect();
        indices.sort_by_key(|&index| {
            let path = &self.changes[index].path;
            let parts: Vec<&str> = path.split('/').collect();

            if parts.len() == 1 {
                // Root level file: ("", filename)
                (String::new(), path.clone())
            } else {
                // File in directory: (directory, filename)
                let dir = parts[..parts.len() - 1].join("/");
                let filename = parts[parts.len() - 1].to_string();
                (dir, filename)
            }
        });
        indices
    }
}

impl GitRepository {
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let repo = Repository::open(path).context("Failed to open Git repository")?;
        Ok(Self {
            repo,
            commit_cache: RefCell::new(None),
            commit_index: RefCell::new(0),
            commit_range: RefCell::new(None),
            author_filter: None,
            before_filter: None,
            after_filter: None,
        })
    }

    pub fn get_commit(&self, hash: &str) -> Result<CommitMetadata> {
        let obj = self
            .repo
            .revparse_single(hash)
            .context("Invalid commit hash or commit not found")?;

        let commit = obj.peel_to_commit().context("Object is not a commit")?;

        Self::extract_metadata_with_changes(&self.repo, &commit)
    }

    pub fn random_commit(&self) -> Result<CommitMetadata> {
        self.populate_cache()?;

        let cache = self.commit_cache.borrow();
        let candidates = cache.as_ref().unwrap();

        let selected_oid = candidates
            .get(rand::rng().random_range(0..candidates.len()))
            .context("Failed to select random commit")?;

        let commit = self.repo.find_commit(*selected_oid)?;
        Self::extract_metadata_with_changes(&self.repo, &commit)
    }

    pub fn next_asc_commit(&self) -> Result<CommitMetadata> {
        self.populate_cache()?;

        let cache = self.commit_cache.borrow();
        let candidates = cache.as_ref().unwrap();
        let mut index = self.commit_index.borrow_mut();

        if candidates.is_empty() {
            anyhow::bail!("No non-merge commits found in repository");
        }

        if *index >= candidates.len() {
            anyhow::bail!("All commits have been played");
        }

        // Asc order: oldest first (reverse of cache order)
        let asc_index = candidates.len() - 1 - *index;
        let selected_oid = candidates
            .get(asc_index)
            .context("Failed to select commit")?;

        *index += 1;

        let commit = self.repo.find_commit(*selected_oid)?;
        Self::extract_metadata_with_changes(&self.repo, &commit)
    }

    pub fn next_desc_commit(&self) -> Result<CommitMetadata> {
        self.populate_cache()?;

        let cache = self.commit_cache.borrow();
        let candidates = cache.as_ref().unwrap();
        let mut index = self.commit_index.borrow_mut();

        if candidates.is_empty() {
            anyhow::bail!("No non-merge commits found in repository");
        }

        if *index >= candidates.len() {
            anyhow::bail!("All commits have been played");
        }

        // Desc order: newest first (same as cache order)
        let selected_oid = candidates.get(*index).context("Failed to select commit")?;

        *index += 1;

        let commit = self.repo.find_commit(*selected_oid)?;
        Self::extract_metadata_with_changes(&self.repo, &commit)
    }

    pub fn reset_index(&self) {
        *self.commit_index.borrow_mut() = 0;
    }

    pub fn set_author_filter(&mut self, author: Option<String>) {
        self.author_filter = author;
    }

    pub fn set_before_filter(&mut self, before: Option<DateTime<Utc>>) {
        self.before_filter = before;
    }

    pub fn set_after_filter(&mut self, after: Option<DateTime<Utc>>) {
        self.after_filter = after;
    }

    pub fn set_commit_range(&self, range: &str) -> Result<()> {
        let commits = self.parse_commit_range(range)?;
        *self.commit_range.borrow_mut() = Some(commits);
        *self.commit_index.borrow_mut() = 0;
        Ok(())
    }

    pub fn next_range_commit_asc(&self) -> Result<CommitMetadata> {
        let range = self.commit_range.borrow();
        let commits = range.as_ref().context("Commit range not set")?;
        let mut index = self.commit_index.borrow_mut();

        if commits.is_empty() {
            anyhow::bail!("No commits in range");
        }

        if *index >= commits.len() {
            anyhow::bail!("All commits in range have been played");
        }

        let selected_oid = commits.get(*index).context("Failed to select commit")?;
        *index += 1;

        let commit = self.repo.find_commit(*selected_oid)?;
        Self::extract_metadata_with_changes(&self.repo, &commit)
    }

    pub fn next_range_commit_desc(&self) -> Result<CommitMetadata> {
        let range = self.commit_range.borrow();
        let commits = range.as_ref().context("Commit range not set")?;
        let mut index = self.commit_index.borrow_mut();

        if commits.is_empty() {
            anyhow::bail!("No commits in range");
        }

        if *index >= commits.len() {
            anyhow::bail!("All commits in range have been played");
        }

        // Desc order: newest first (reverse of asc)
        let desc_index = commits.len() - 1 - *index;
        let selected_oid = commits.get(desc_index).context("Failed to select commit")?;
        *index += 1;

        let commit = self.repo.find_commit(*selected_oid)?;
        Self::extract_metadata_with_changes(&self.repo, &commit)
    }

    pub fn random_range_commit(&self) -> Result<CommitMetadata> {
        let range = self.commit_range.borrow();
        let commits = range.as_ref().context("Commit range not set")?;

        if commits.is_empty() {
            anyhow::bail!("No commits in range");
        }

        let selected_oid = commits
            .get(rand::rng().random_range(0..commits.len()))
            .context("Failed to select random commit")?;

        let commit = self.repo.find_commit(*selected_oid)?;
        Self::extract_metadata_with_changes(&self.repo, &commit)
    }

    // Collect non-merge commits from a revwalk, applying author and date filters if set
    fn collect_commits_from_revwalk(
        &self,
        revwalk: git2::Revwalk,
        context: &str,
    ) -> Result<Vec<Oid>> {
        let mut commits = Vec::new();
        for oid in revwalk.filter_map(|oid| oid.ok()) {
            if let Ok(commit) = self.repo.find_commit(oid) {
                if commit.parent_count() <= 1 {
                    if let Some(ref pattern) = self.author_filter {
                        if !matches_author(&commit, pattern) {
                            continue;
                        }
                    }
                    if !matches_date_filter(
                        &commit,
                        self.before_filter.as_ref(),
                        self.after_filter.as_ref(),
                    )? {
                        continue;
                    }
                    commits.push(oid);
                }
            }
        }

        if commits.is_empty() {
            if self.author_filter.is_some()
                || self.before_filter.is_some()
                || self.after_filter.is_some()
            {
                anyhow::bail!("No commits found matching the filters {}", context);
            }
            anyhow::bail!("No non-merge commits found {}", context);
        }

        Ok(commits)
    }

    fn parse_commit_range(&self, range: &str) -> Result<Vec<Oid>> {
        // Reject symmetric difference operator (not supported)
        if range.contains("...") {
            anyhow::bail!(
                "Symmetric difference operator '...' is not supported. Use '..' instead (e.g., 'HEAD~5..HEAD')"
            );
        }

        if !range.contains("..") {
            anyhow::bail!(
                "Invalid range format: {}. Use formats like 'HEAD~5..HEAD' or 'abc123..'",
                range
            );
        }

        let parts: Vec<&str> = range.split("..").collect();
        if parts.len() != 2 {
            anyhow::bail!("Invalid range format: {}", range);
        }

        let start = if parts[0].is_empty() {
            None
        } else {
            Some(self.repo.revparse_single(parts[0])?.id())
        };

        let end = if parts[1].is_empty() {
            self.repo.head()?.peel_to_commit()?.id()
        } else {
            self.repo.revparse_single(parts[1])?.id()
        };

        let mut revwalk = self.repo.revwalk()?;
        revwalk.push(end)?;

        if let Some(start_oid) = start {
            revwalk.hide(start_oid)?;
        }

        let mut commits = self.collect_commits_from_revwalk(revwalk, "in range")?;
        commits.reverse();
        Ok(commits)
    }

    fn populate_cache(&self) -> Result<()> {
        let mut cache = self.commit_cache.borrow_mut();
        if cache.is_none() {
            let mut revwalk = self.repo.revwalk()?;
            revwalk.push_head()?;

            let candidates = self.collect_commits_from_revwalk(revwalk, "in repository")?;
            *cache = Some(candidates);
        }
        Ok(())
    }

    fn extract_metadata_with_changes(
        repo: &Repository,
        commit: &Git2Commit,
    ) -> Result<CommitMetadata> {
        let hash = commit.id().to_string();
        let author = commit.author();
        let author_name = author.name().unwrap_or("Unknown").to_string();
        let timestamp = author.when().seconds();
        let date = DateTime::from_timestamp(timestamp, 0).unwrap_or_else(Utc::now);
        let message = commit.message().unwrap_or("").trim().to_string();

        let changes = Self::extract_changes(repo, commit)?;

        Ok(CommitMetadata {
            hash,
            author: author_name,
            date,
            message,
            changes,
        })
    }

    fn extract_changes(repo: &Repository, commit: &Git2Commit) -> Result<Vec<FileChange>> {
        let commit_tree = commit.tree().context("Failed to get commit tree")?;
        let parent_tree = if commit.parent_count() > 0 {
            match commit.parent(0).and_then(|p| p.tree()) {
                Ok(tree) => Some(tree),
                Err(_) => return Ok(Vec::new()), // Skip if parent tree unavailable
            }
        } else {
            None
        };

        let mut diff_opts = DiffOptions::new();
        diff_opts.context_lines(3);

        let diff = match repo.diff_tree_to_tree(
            parent_tree.as_ref(),
            Some(&commit_tree),
            Some(&mut diff_opts),
        ) {
            Ok(d) => d,
            Err(_) => return Ok(Vec::new()), // Skip if diff fails
        };

        let mut changes = Vec::new();

        for i in 0..diff.deltas().len() {
            let Some(delta) = diff.get_delta(i) else {
                continue;
            };
            let status = FileStatus::from(delta.status());

            let path = delta
                .new_file()
                .path()
                .or_else(|| delta.old_file().path())
                .and_then(|p| p.to_str())
                .unwrap_or("unknown")
                .to_string();

            let old_path = if delta.status() == Delta::Renamed {
                delta
                    .old_file()
                    .path()
                    .and_then(|p| p.to_str())
                    .map(String::from)
            } else {
                None
            };

            let is_binary = delta.new_file().is_binary() || delta.old_file().is_binary();

            let old_content = if let Some(parent_tree) = parent_tree.as_ref() {
                if let Some(old_file_path) = delta.old_file().path() {
                    parent_tree
                        .get_path(old_file_path)
                        .ok()
                        .and_then(|entry| repo.find_blob(entry.id()).ok())
                        .and_then(|blob| {
                            if !blob.is_binary() && blob.size() <= MAX_BLOB_SIZE {
                                Some(String::from_utf8_lossy(blob.content()).to_string())
                            } else {
                                None
                            }
                        })
                } else {
                    None
                }
            } else {
                None
            };

            let new_content = if let Some(new_file_path) = delta.new_file().path() {
                commit_tree
                    .get_path(new_file_path)
                    .ok()
                    .and_then(|entry| repo.find_blob(entry.id()).ok())
                    .and_then(|blob| {
                        if !blob.is_binary() && blob.size() <= MAX_BLOB_SIZE {
                            Some(String::from_utf8_lossy(blob.content()).to_string())
                        } else {
                            None
                        }
                    })
            } else {
                None
            };

            let mut hunks = Vec::new();
            let mut diff_text = String::new();

            if let Ok(Some(mut patch)) = git2::Patch::from_diff(&diff, i) {
                if let Ok(patch_str) = patch.to_buf() {
                    diff_text = String::from_utf8_lossy(patch_str.as_ref()).to_string();
                }

                if !is_binary {
                    for hunk_idx in 0..patch.num_hunks() {
                        if let Ok((hunk, _hunk_lines)) = patch.hunk(hunk_idx) {
                            let mut lines = Vec::new();
                            let num_lines = patch.num_lines_in_hunk(hunk_idx).unwrap_or(0);

                            let mut old_line_no = hunk.old_start() as usize;
                            let mut new_line_no = hunk.new_start() as usize;

                            for line_idx in 0..num_lines {
                                if let Ok(line) = patch.line_in_hunk(hunk_idx, line_idx) {
                                    let content =
                                        String::from_utf8_lossy(line.content()).to_string();
                                    let origin = line.origin();

                                    let (change_type, old_no, new_no) = match origin {
                                        '+' => {
                                            let no = new_line_no;
                                            new_line_no += 1;
                                            (LineChangeType::Addition, None, Some(no))
                                        }
                                        '-' => {
                                            let no = old_line_no;
                                            old_line_no += 1;
                                            (LineChangeType::Deletion, Some(no), None)
                                        }
                                        _ => {
                                            let old_no = old_line_no;
                                            let new_no = new_line_no;
                                            old_line_no += 1;
                                            new_line_no += 1;
                                            (LineChangeType::Context, Some(old_no), Some(new_no))
                                        }
                                    };

                                    lines.push(LineChange {
                                        change_type,
                                        content,
                                        old_line_no: old_no,
                                        new_line_no: new_no,
                                    });
                                }
                            }

                            hunks.push(DiffHunk {
                                old_start: hunk.old_start() as usize,
                                old_lines: hunk.old_lines() as usize,
                                new_start: hunk.new_start() as usize,
                                new_lines: hunk.new_lines() as usize,
                                lines,
                            });
                        }
                    }
                }
            }

            // Calculate total changed lines (additions + deletions)
            let total_changed_lines: usize = hunks
                .iter()
                .flat_map(|hunk| &hunk.lines)
                .filter(|line| !matches!(line.change_type, LineChangeType::Context))
                .count();

            // Determine exclusion reason
            let (is_excluded, exclusion_reason) = if should_exclude_file(&path) {
                (true, Some("lock/generated file".to_string()))
            } else if total_changed_lines > MAX_CHANGE_LINES {
                (
                    true,
                    Some(format!("too many changes ({} lines)", total_changed_lines)),
                )
            } else {
                (false, None)
            };

            changes.push(FileChange {
                path,
                old_path,
                status,
                is_binary,
                is_excluded,
                exclusion_reason,
                old_content,
                new_content,
                hunks,
                diff: diff_text,
            });
        }

        Ok(changes)
    }

    /// Get working tree diff as CommitMetadata for animation
    ///
    /// DiffMode::Staged - Only staged changes (index vs HEAD)
    /// DiffMode::Unstaged - Only unstaged changes (workdir vs index)
    pub fn get_working_tree_diff(&self, mode: DiffMode) -> Result<CommitMetadata> {
        let changes = match mode {
            DiffMode::Staged => self.extract_staged_changes()?,
            DiffMode::Unstaged => self.extract_unstaged_changes()?,
        };

        let message = match mode {
            DiffMode::Staged => "Staged changes",
            DiffMode::Unstaged => "Unstaged changes",
        };

        Ok(CommitMetadata {
            hash: "working-tree".to_string(),
            author: "Working Tree".to_string(),
            date: Utc::now(),
            message: message.to_string(),
            changes,
        })
    }

    /// Extract staged changes (index vs HEAD)
    fn extract_staged_changes(&self) -> Result<Vec<FileChange>> {
        let head_tree = self
            .repo
            .head()
            .ok()
            .and_then(|head| head.peel_to_tree().ok());

        let index = self
            .repo
            .index()
            .context("Failed to get repository index")?;

        let mut diff_opts = DiffOptions::new();
        diff_opts.context_lines(3);

        let diff = self
            .repo
            .diff_tree_to_index(head_tree.as_ref(), Some(&index), Some(&mut diff_opts))
            .context("Failed to diff tree to index")?;

        self.extract_changes_from_diff(&diff, head_tree.as_ref(), None)
    }

    /// Extract unstaged changes (workdir vs index)
    fn extract_unstaged_changes(&self) -> Result<Vec<FileChange>> {
        let index = self
            .repo
            .index()
            .context("Failed to get repository index")?;

        let mut diff_opts = DiffOptions::new();
        diff_opts.context_lines(3);
        diff_opts.include_untracked(true);

        let diff = self
            .repo
            .diff_index_to_workdir(Some(&index), Some(&mut diff_opts))
            .context("Failed to diff index to workdir")?;

        // For unstaged, "old" content comes from index, "new" from workdir
        self.extract_changes_from_diff_workdir(&diff, &index)
    }

    /// Extract FileChange data from a git2::Diff (for staged changes)
    fn extract_changes_from_diff(
        &self,
        diff: &git2::Diff,
        old_tree: Option<&git2::Tree>,
        new_tree: Option<&git2::Tree>,
    ) -> Result<Vec<FileChange>> {
        self.extract_changes_from_diff_with_content(diff, |delta| {
            let old_content = old_tree
                .and_then(|tree| self.get_blob_content_from_tree(tree, delta.old_file().path()));
            let new_content = if let Some(tree) = new_tree {
                self.get_blob_content_from_tree(tree, delta.new_file().path())
            } else {
                // For staged changes, get from index
                self.get_index_content(delta.new_file().path())
            };
            (old_content, new_content)
        })
    }

    /// Extract FileChange data from workdir diff (for unstaged changes)
    fn extract_changes_from_diff_workdir(
        &self,
        diff: &git2::Diff,
        index: &git2::Index,
    ) -> Result<Vec<FileChange>> {
        self.extract_changes_from_diff_with_content(diff, |delta| {
            let old_content = self.get_index_content_from(index, delta.old_file().path());
            let new_content = self.get_workdir_content(delta.new_file().path());
            (old_content, new_content)
        })
    }

    /// Common diff extraction logic with pluggable content retrieval
    fn extract_changes_from_diff_with_content<F>(
        &self,
        diff: &git2::Diff,
        get_content: F,
    ) -> Result<Vec<FileChange>>
    where
        F: Fn(&git2::DiffDelta) -> (Option<String>, Option<String>),
    {
        let mut changes = Vec::new();

        for i in 0..diff.deltas().len() {
            let Some(delta) = diff.get_delta(i) else {
                continue;
            };
            let status = FileStatus::from(delta.status());

            let path = delta
                .new_file()
                .path()
                .or_else(|| delta.old_file().path())
                .and_then(|p| p.to_str())
                .unwrap_or("unknown")
                .to_string();

            let old_path = if delta.status() == Delta::Renamed {
                delta
                    .old_file()
                    .path()
                    .and_then(|p| p.to_str())
                    .map(String::from)
            } else {
                None
            };

            let is_binary = delta.new_file().is_binary() || delta.old_file().is_binary();
            let (old_content, new_content) = get_content(&delta);
            let (hunks, diff_text) = self.extract_hunks_from_diff(diff, i, is_binary)?;

            // Calculate total changed lines
            let total_changed_lines: usize = hunks
                .iter()
                .flat_map(|hunk| &hunk.lines)
                .filter(|line| !matches!(line.change_type, LineChangeType::Context))
                .count();

            let (is_excluded, exclusion_reason) = if should_exclude_file(&path) {
                (true, Some("lock/generated file".to_string()))
            } else if total_changed_lines > MAX_CHANGE_LINES {
                (
                    true,
                    Some(format!("too many changes ({} lines)", total_changed_lines)),
                )
            } else {
                (false, None)
            };

            changes.push(FileChange {
                path,
                old_path,
                status,
                is_binary,
                is_excluded,
                exclusion_reason,
                old_content,
                new_content,
                hunks,
                diff: diff_text,
            });
        }

        Ok(changes)
    }

    /// Get blob content from a tree by path
    fn get_blob_content_from_tree(
        &self,
        tree: &git2::Tree,
        path: Option<&std::path::Path>,
    ) -> Option<String> {
        let path = path?;
        let entry = tree.get_path(path).ok()?;
        let blob = self.repo.find_blob(entry.id()).ok()?;
        if !blob.is_binary() && blob.size() <= MAX_BLOB_SIZE {
            Some(String::from_utf8_lossy(blob.content()).to_string())
        } else {
            None
        }
    }

    /// Extract hunks from a diff at given delta index
    fn extract_hunks_from_diff(
        &self,
        diff: &git2::Diff,
        delta_idx: usize,
        is_binary: bool,
    ) -> Result<(Vec<DiffHunk>, String)> {
        let mut hunks = Vec::new();
        let mut diff_text = String::new();

        if let Ok(Some(mut patch)) = git2::Patch::from_diff(diff, delta_idx) {
            if let Ok(patch_str) = patch.to_buf() {
                diff_text = String::from_utf8_lossy(patch_str.as_ref()).to_string();
            }

            if !is_binary {
                for hunk_idx in 0..patch.num_hunks() {
                    if let Ok((hunk, _hunk_lines)) = patch.hunk(hunk_idx) {
                        let mut lines = Vec::new();
                        let num_lines = patch.num_lines_in_hunk(hunk_idx).unwrap_or(0);

                        let mut old_line_no = hunk.old_start() as usize;
                        let mut new_line_no = hunk.new_start() as usize;

                        for line_idx in 0..num_lines {
                            if let Ok(line) = patch.line_in_hunk(hunk_idx, line_idx) {
                                let content = String::from_utf8_lossy(line.content()).to_string();
                                let origin = line.origin();

                                let (change_type, old_no, new_no) = match origin {
                                    '+' => {
                                        let no = new_line_no;
                                        new_line_no += 1;
                                        (LineChangeType::Addition, None, Some(no))
                                    }
                                    '-' => {
                                        let no = old_line_no;
                                        old_line_no += 1;
                                        (LineChangeType::Deletion, Some(no), None)
                                    }
                                    _ => {
                                        let old_no = old_line_no;
                                        let new_no = new_line_no;
                                        old_line_no += 1;
                                        new_line_no += 1;
                                        (LineChangeType::Context, Some(old_no), Some(new_no))
                                    }
                                };

                                lines.push(LineChange {
                                    change_type,
                                    content,
                                    old_line_no: old_no,
                                    new_line_no: new_no,
                                });
                            }
                        }

                        hunks.push(DiffHunk {
                            old_start: hunk.old_start() as usize,
                            old_lines: hunk.old_lines() as usize,
                            new_start: hunk.new_start() as usize,
                            new_lines: hunk.new_lines() as usize,
                            lines,
                        });
                    }
                }
            }
        }

        Ok((hunks, diff_text))
    }

    /// Get file content from the current index
    fn get_index_content(&self, path: Option<&std::path::Path>) -> Option<String> {
        let path = path?;
        let index = self.repo.index().ok()?;
        self.get_index_content_from(&index, Some(path))
    }

    /// Get file content from a specific index
    fn get_index_content_from(
        &self,
        index: &git2::Index,
        path: Option<&std::path::Path>,
    ) -> Option<String> {
        let path = path?;
        let entry = index.get_path(path, 0)?;
        let blob = self.repo.find_blob(entry.id).ok()?;

        if !blob.is_binary() && blob.size() <= MAX_BLOB_SIZE {
            Some(String::from_utf8_lossy(blob.content()).to_string())
        } else {
            None
        }
    }

    /// Get file content from working directory.
    ///
    /// Returns `None` if:
    /// - Path is not provided
    /// - Repository is bare (no working directory)
    /// - File cannot be read (missing, permissions, binary/non-UTF8)
    /// - File size exceeds MAX_BLOB_SIZE (500KB)
    fn get_workdir_content(&self, path: Option<&std::path::Path>) -> Option<String> {
        let path = path?;
        let workdir = self.repo.workdir()?;
        let full_path = workdir.join(path);

        match std::fs::read_to_string(&full_path) {
            Ok(content) if content.len() <= MAX_BLOB_SIZE => Some(content),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_should_exclude_lock_files() {
        // JavaScript/Node.js
        assert!(should_exclude_file("package-lock.json"));
        assert!(should_exclude_file("yarn.lock"));
        assert!(should_exclude_file("pnpm-lock.yaml"));
        // Rust
        assert!(should_exclude_file("Cargo.lock"));
        // Ruby
        assert!(should_exclude_file("Gemfile.lock"));
        // Python
        assert!(should_exclude_file("poetry.lock"));
        assert!(should_exclude_file("Pipfile.lock"));
        assert!(should_exclude_file("uv.lock"));
        // PHP
        assert!(should_exclude_file("composer.lock"));
        // Go
        assert!(should_exclude_file("go.sum"));
        // Swift
        assert!(should_exclude_file("Package.resolved"));
        // Dart/Flutter
        assert!(should_exclude_file("pubspec.lock"));
        // .NET/C#
        assert!(should_exclude_file("packages.lock.json"));
        assert!(should_exclude_file("project.assets.json"));
        // Elixir
        assert!(should_exclude_file("mix.lock"));
        // Java/Gradle
        assert!(should_exclude_file("gradle.lockfile"));
        assert!(should_exclude_file("buildscript-gradle.lockfile"));
        // Scala
        assert!(should_exclude_file("build.sbt.lock"));
        // Bazel
        assert!(should_exclude_file("MODULE.bazel.lock"));
    }

    #[test]
    fn test_should_exclude_lock_files_with_path() {
        assert!(should_exclude_file("path/to/package-lock.json"));
        assert!(should_exclude_file("src/Cargo.lock"));
        assert!(should_exclude_file("frontend/yarn.lock"));
    }

    #[test]
    fn test_should_exclude_minified_files() {
        assert!(should_exclude_file("bundle.min.js"));
        assert!(should_exclude_file("app.min.css"));
        assert!(should_exclude_file("vendor.bundle.js"));
        assert!(should_exclude_file("styles.bundle.css"));
        // Source maps
        assert!(should_exclude_file("app.js.map"));
        assert!(should_exclude_file("styles.css.map"));
        assert!(should_exclude_file("types.d.ts.map"));
    }

    #[test]
    fn test_should_exclude_minified_files_with_path() {
        assert!(should_exclude_file("dist/bundle.min.js"));
        assert!(should_exclude_file("public/assets/app.min.css"));
    }

    #[test]
    fn test_should_not_exclude_normal_files() {
        assert!(!should_exclude_file("src/main.rs"));
        assert!(!should_exclude_file("package.json"));
        assert!(!should_exclude_file("Cargo.toml"));
        assert!(!should_exclude_file("app.js"));
        assert!(!should_exclude_file("styles.css"));
        assert!(!should_exclude_file("lock.txt"));
        assert!(!should_exclude_file("minify.rs"));
    }

    #[test]
    fn test_should_exclude_snapshot_files() {
        assert!(should_exclude_file("component.test.ts.snap"));
        assert!(should_exclude_file("tests/__snapshots__/test.snap"));
        assert!(should_exclude_file("__snapshots__/component.snap"));
        assert!(should_exclude_file("src/__snapshots__/app.test.js.snap"));
    }

    #[test]
    fn test_user_patterns_integration() {
        // Test all pattern types in one test since OnceLock can only be set once
        let patterns = vec![
            "*.svg".to_string(),
            "*.ipynb".to_string(),
            "dist/**".to_string(),
            "node_modules/**".to_string(),
        ];

        // Only initialize if not already initialized
        let _ = init_ignore_patterns(&patterns);

        // Test file extension patterns
        assert!(should_exclude_file("diagram.svg"));
        assert!(should_exclude_file("path/to/notebook.ipynb"));
        assert!(should_exclude_file("assets/icon.svg"));
        assert!(!should_exclude_file("image.png"));
        assert!(!should_exclude_file("script.py"));

        // Test directory patterns
        assert!(should_exclude_file("dist/bundle.js"));
        assert!(should_exclude_file("dist/css/main.css"));
        assert!(should_exclude_file("node_modules/pkg/index.js"));
        assert!(!should_exclude_file("src/index.js"));
    }

    #[test]
    fn test_empty_patterns() {
        let patterns: Vec<String> = vec![];
        assert!(init_ignore_patterns(&patterns).is_ok());
    }

    #[test]
    fn test_invalid_pattern() {
        let patterns = vec!["[invalid".to_string()];
        assert!(init_ignore_patterns(&patterns).is_err());
    }

    // DiffMode tests
    #[test]
    fn test_diff_mode_default() {
        let mode: DiffMode = Default::default();
        assert_eq!(mode, DiffMode::Staged);
    }

    // RAII guard for temporary git repository - auto-cleans on drop
    struct TestRepo {
        path: std::path::PathBuf,
        repo: git2::Repository,
    }

    impl Drop for TestRepo {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.path);
        }
    }

    impl TestRepo {
        fn new() -> Self {
            use std::sync::atomic::{AtomicU64, Ordering};
            use std::time::{SystemTime, UNIX_EPOCH};
            static COUNTER: AtomicU64 = AtomicU64::new(0);

            let unique_id = format!(
                "{}_{}_{}",
                std::process::id(),
                SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap()
                    .as_nanos(),
                COUNTER.fetch_add(1, Ordering::SeqCst)
            );
            let path = std::env::temp_dir().join(format!("gitlogue_test_{}", unique_id));
            if path.exists() {
                std::fs::remove_dir_all(&path).unwrap();
            }
            std::fs::create_dir_all(&path).unwrap();

            let repo = git2::Repository::init(&path).unwrap();

            // Configure user for commits
            let mut config = repo.config().unwrap();
            config.set_str("user.name", "Test User").unwrap();
            config.set_str("user.email", "test@example.com").unwrap();

            Self { path, repo }
        }
    }

    #[test]
    fn test_working_tree_diff_empty_repo() {
        let test_repo = TestRepo::new();
        let repo = GitRepository::open(&test_repo.path).unwrap();

        let staged = repo.get_working_tree_diff(DiffMode::Staged).unwrap();
        assert_eq!(staged.hash, "working-tree");
        assert_eq!(staged.author, "Working Tree");
        assert_eq!(staged.message, "Staged changes");
        assert!(staged.changes.is_empty());

        let unstaged = repo.get_working_tree_diff(DiffMode::Unstaged).unwrap();
        assert_eq!(unstaged.message, "Unstaged changes");
        assert!(unstaged.changes.is_empty());
    }

    #[test]
    fn test_working_tree_diff_with_unstaged_changes() {
        let test_repo = TestRepo::new();

        let file_path = test_repo.path.join("test.txt");
        std::fs::write(&file_path, "initial content\n").unwrap();
        let mut index = test_repo.repo.index().unwrap();
        index.add_path(std::path::Path::new("test.txt")).unwrap();
        index.write().unwrap();
        let tree_id = index.write_tree().unwrap();
        let tree = test_repo.repo.find_tree(tree_id).unwrap();
        let sig = test_repo.repo.signature().unwrap();
        test_repo
            .repo
            .commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
            .unwrap();

        std::fs::write(&file_path, "modified content\n").unwrap();

        let repo = GitRepository::open(&test_repo.path).unwrap();

        let unstaged = repo.get_working_tree_diff(DiffMode::Unstaged).unwrap();
        assert_eq!(unstaged.message, "Unstaged changes");
        assert_eq!(unstaged.changes.len(), 1);
        assert_eq!(unstaged.changes[0].path, "test.txt");
        assert_eq!(unstaged.changes[0].status, FileStatus::Modified);

        let staged = repo.get_working_tree_diff(DiffMode::Staged).unwrap();
        assert!(staged.changes.is_empty());
    }

    #[test]
    fn test_working_tree_diff_with_staged_changes() {
        let test_repo = TestRepo::new();

        let file_path = test_repo.path.join("test.txt");
        std::fs::write(&file_path, "initial content\n").unwrap();
        let mut index = test_repo.repo.index().unwrap();
        index.add_path(std::path::Path::new("test.txt")).unwrap();
        index.write().unwrap();
        let tree_id = index.write_tree().unwrap();
        let tree = test_repo.repo.find_tree(tree_id).unwrap();
        let sig = test_repo.repo.signature().unwrap();
        test_repo
            .repo
            .commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
            .unwrap();

        std::fs::write(&file_path, "staged content\n").unwrap();
        let mut index = test_repo.repo.index().unwrap();
        index.add_path(std::path::Path::new("test.txt")).unwrap();
        index.write().unwrap();

        let repo = GitRepository::open(&test_repo.path).unwrap();

        let staged = repo.get_working_tree_diff(DiffMode::Staged).unwrap();
        assert_eq!(staged.message, "Staged changes");
        assert_eq!(staged.changes.len(), 1);
        assert_eq!(staged.changes[0].path, "test.txt");
        assert_eq!(staged.changes[0].status, FileStatus::Modified);

        let unstaged = repo.get_working_tree_diff(DiffMode::Unstaged).unwrap();
        assert!(unstaged.changes.is_empty());
    }

    #[test]
    fn test_working_tree_diff_with_both_staged_and_unstaged() {
        let test_repo = TestRepo::new();

        let file1 = test_repo.path.join("file1.txt");
        let file2 = test_repo.path.join("file2.txt");
        std::fs::write(&file1, "file1 content\n").unwrap();
        std::fs::write(&file2, "file2 content\n").unwrap();
        let mut index = test_repo.repo.index().unwrap();
        index.add_path(std::path::Path::new("file1.txt")).unwrap();
        index.add_path(std::path::Path::new("file2.txt")).unwrap();
        index.write().unwrap();
        let tree_id = index.write_tree().unwrap();
        let tree = test_repo.repo.find_tree(tree_id).unwrap();
        let sig = test_repo.repo.signature().unwrap();
        test_repo
            .repo
            .commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
            .unwrap();

        std::fs::write(&file1, "file1 staged\n").unwrap();
        let mut index = test_repo.repo.index().unwrap();
        index.add_path(std::path::Path::new("file1.txt")).unwrap();
        index.write().unwrap();

        std::fs::write(&file2, "file2 unstaged\n").unwrap();

        let repo = GitRepository::open(&test_repo.path).unwrap();

        let staged = repo.get_working_tree_diff(DiffMode::Staged).unwrap();
        assert_eq!(staged.changes.len(), 1);
        assert_eq!(staged.changes[0].path, "file1.txt");

        let unstaged = repo.get_working_tree_diff(DiffMode::Unstaged).unwrap();
        assert_eq!(unstaged.changes.len(), 1);
        assert_eq!(unstaged.changes[0].path, "file2.txt");
    }

    #[test]
    fn test_working_tree_diff_new_file() {
        let test_repo = TestRepo::new();

        let file1 = test_repo.path.join("existing.txt");
        std::fs::write(&file1, "existing\n").unwrap();
        let mut index = test_repo.repo.index().unwrap();
        index
            .add_path(std::path::Path::new("existing.txt"))
            .unwrap();
        index.write().unwrap();
        let tree_id = index.write_tree().unwrap();
        let tree = test_repo.repo.find_tree(tree_id).unwrap();
        let sig = test_repo.repo.signature().unwrap();
        test_repo
            .repo
            .commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
            .unwrap();

        let new_file = test_repo.path.join("new_file.txt");
        std::fs::write(&new_file, "new file content\n").unwrap();
        let mut index = test_repo.repo.index().unwrap();
        index
            .add_path(std::path::Path::new("new_file.txt"))
            .unwrap();
        index.write().unwrap();

        let repo = GitRepository::open(&test_repo.path).unwrap();

        let staged = repo.get_working_tree_diff(DiffMode::Staged).unwrap();
        assert_eq!(staged.changes.len(), 1);
        assert_eq!(staged.changes[0].path, "new_file.txt");
        assert_eq!(staged.changes[0].status, FileStatus::Added);
    }

    #[test]
    fn test_working_tree_diff_deleted_file() {
        let test_repo = TestRepo::new();

        let file = test_repo.path.join("to_delete.txt");
        std::fs::write(&file, "will be deleted\n").unwrap();
        let mut index = test_repo.repo.index().unwrap();
        index
            .add_path(std::path::Path::new("to_delete.txt"))
            .unwrap();
        index.write().unwrap();
        let tree_id = index.write_tree().unwrap();
        let tree = test_repo.repo.find_tree(tree_id).unwrap();
        let sig = test_repo.repo.signature().unwrap();
        test_repo
            .repo
            .commit(Some("HEAD"), &sig, &sig, "Initial commit", &tree, &[])
            .unwrap();

        std::fs::remove_file(&file).unwrap();
        let mut index = test_repo.repo.index().unwrap();
        index
            .remove_path(std::path::Path::new("to_delete.txt"))
            .unwrap();
        index.write().unwrap();

        let repo = GitRepository::open(&test_repo.path).unwrap();

        let staged = repo.get_working_tree_diff(DiffMode::Staged).unwrap();
        assert_eq!(staged.changes.len(), 1);
        assert_eq!(staged.changes[0].path, "to_delete.txt");
        assert_eq!(staged.changes[0].status, FileStatus::Deleted);
    }

    #[test]
    fn test_working_tree_diff_metadata_fields() {
        let test_repo = TestRepo::new();
        let repo = GitRepository::open(&test_repo.path).unwrap();

        let result = repo.get_working_tree_diff(DiffMode::Staged).unwrap();

        assert_eq!(result.hash, "working-tree");
        assert_eq!(result.author, "Working Tree");
        assert_eq!(result.message, "Staged changes");
        // Date should be recent (within last minute)
        let now = Utc::now();
        let diff = now.signed_duration_since(result.date);
        assert!(diff.num_seconds() < 60);
    }
}