git-editor 2.1.0

A command-line tool to edit git commit timestamps, messages, and author information
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
use crate::rewrite::engine::{self, Edit, GitTime, Plan};
use crate::rewrite::report::print_outcome;
use crate::rewrite::rewrite_all::begin_offset;
use crate::utils::dates::{format_git_time, parse_git_time, parse_utc};
use crate::utils::datetime::spread_timestamps;
use crate::utils::prompt::read_prompted_line;
use crate::utils::prompt::{cancelled, confirm};
use crate::utils::simulation::{report_simulation, simulation_from_plan};
use crate::utils::types::CommitInfo;
use crate::utils::types::Result;
use crate::utils::validator::{is_valid_email, validate_identity_part};
use crate::{args::Args, utils::commit_history::get_commit_history};
use chrono::NaiveDateTime;
use colored::Colorize;
use crossterm::{
    cursor,
    event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers},
    terminal::{self, Clear, ClearType},
    ExecutableCommand,
};
use git2::Repository;
use std::io::{self, Write};

#[derive(Debug, Clone)]
struct CommitEdit {
    index: usize,
    original: CommitInfo,
    author_name: String,
    author_email: String,
    /// Author date as UTC; `offset_minutes` is the zone it is written in.
    timestamp: NaiveDateTime,
    offset_minutes: i32,
    message: String,
    is_modified: bool,
    modifications: ModificationFlags,
}

#[derive(Debug, Clone, Default)]
struct ModificationFlags {
    author_name_changed: bool,
    author_email_changed: bool,
    timestamp_changed: bool,
    message_changed: bool,
}

/// What the table loop should do after a key press.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TableAction {
    Continue,
    SaveAndExit,
    Cancel,
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum TableColumn {
    Index = 0,
    Hash = 1,
    AuthorName = 2,
    AuthorEmail = 3,
    Timestamp = 4,
    Message = 5,
}

/// Draws the table on the alternate screen and restores the terminal (raw mode
/// off, original screen back) when dropped — on success, error or panic.
struct TerminalGuard;

impl TerminalGuard {
    fn enter() -> Result<Self> {
        io::stdout().execute(terminal::EnterAlternateScreen)?;
        Ok(Self)
    }
}

impl Drop for TerminalGuard {
    fn drop(&mut self) {
        let _ = terminal::disable_raw_mode();
        let _ = io::stdout().execute(terminal::LeaveAlternateScreen);
        let _ = io::stdout().execute(cursor::Show);
    }
}

struct InteractiveTable {
    commits: Vec<CommitEdit>,
    current_row: usize,
    current_col: TableColumn,
    editing: bool,
    edit_buffer: String,
    /// Last validation error, shown below the table (never stored in a field).
    status: Option<String>,
    editable_fields: (bool, bool, bool, bool), // (author_name, author_email, timestamp, message)
}

impl InteractiveTable {
    fn new(
        commits: Vec<CommitInfo>,
        start_idx: usize,
        end_idx: usize,
        editable_fields: (bool, bool, bool, bool),
    ) -> Self {
        let mut commit_edits = Vec::new();

        for (i, commit) in commits[start_idx..=end_idx].iter().enumerate() {
            commit_edits.push(CommitEdit {
                index: start_idx + i,
                original: commit.clone(),
                author_name: commit.author_name.clone(),
                author_email: commit.author_email.clone(),
                timestamp: commit.timestamp,
                offset_minutes: commit.author_offset_min,
                message: commit.message.clone(), // Keep full message, truncate only for display
                is_modified: false,
                modifications: ModificationFlags::default(),
            });
        }

        // Find the first editable column as starting position
        let starting_col = if editable_fields.0 {
            // author_name
            TableColumn::AuthorName
        } else if editable_fields.1 {
            // author_email
            TableColumn::AuthorEmail
        } else if editable_fields.2 {
            // timestamp
            TableColumn::Timestamp
        } else if editable_fields.3 {
            // message
            TableColumn::Message
        } else {
            TableColumn::AuthorName // fallback
        };

        Self {
            commits: commit_edits,
            current_row: 0,
            current_col: starting_col,
            editing: false,
            edit_buffer: String::new(),
            status: None,
            editable_fields,
        }
    }

    fn draw_table(&self) {
        // Clear screen using crossterm
        let _ = io::stdout().execute(Clear(ClearType::All));
        let _ = io::stdout().execute(cursor::MoveTo(0, 0));

        crate::say!(
            "{}",
            "Interactive Commit Editor - Range Mode".bold().green()
        );

        // Show which fields are editable
        let editable_info = if self.editable_fields == (true, true, true, true) {
            "All fields editable".to_string()
        } else {
            let mut editable = Vec::new();
            if self.editable_fields.0 || self.editable_fields.1 {
                editable.push("Author");
            }
            if self.editable_fields.2 {
                editable.push("Time");
            }
            if self.editable_fields.3 {
                editable.push("Message");
            }
            format!("Editable: {}", editable.join(", "))
        };
        crate::say!("{}", editable_info.cyan());
        crate::say!(
            "{}",
            "Arrow keys/hjkl: move  Enter: edit  Esc: save & exit  q or Ctrl+C: cancel without saving"
                .yellow()
        );
        crate::say!();

        // Print header
        crate::say!(
            "{:<4} {:<8} {:<15} {:<20} {:<19} {}",
            "#".bold().white(),
            "HASH".bold().white(),
            "AUTHOR NAME".bold().white(),
            "AUTHOR EMAIL".bold().white(),
            "TIMESTAMP (UTC)".bold().white(),
            "MESSAGE".bold().white()
        );

        // Draw only the rows that fit on screen, keeping the cursor row visible.
        let screen_rows = terminal::size().map(|(_, h)| h as usize).unwrap_or(24);
        let (first, count) = viewport(
            self.current_row,
            self.commits.len(),
            screen_rows.saturating_sub(TABLE_CHROME_LINES),
        );
        for (row_idx, commit) in self.commits.iter().enumerate().skip(first).take(count) {
            let is_current_row = row_idx == self.current_row;

            // Prepare content
            let index_str = format!("{}", commit.index + 1);
            let hash_str = self.truncate_text(&commit.original.short_hash, 8);
            let author_name_str = self.truncate_text(&commit.author_name, 15);
            let author_email_str = self.truncate_text(&commit.author_email, 20);
            let timestamp_str = commit.timestamp.format("%Y-%m-%d %H:%M:%S").to_string();
            let first_line_message = commit.message.lines().next().unwrap_or("");
            let message_str = self.truncate_text(first_line_message, 40);

            // Add modification indicators and current cell brackets
            let is_current_cell_index =
                is_current_row && matches!(self.current_col, TableColumn::Index);
            let is_current_cell_hash =
                is_current_row && matches!(self.current_col, TableColumn::Hash);
            let is_current_cell_author_name =
                is_current_row && matches!(self.current_col, TableColumn::AuthorName);
            let is_current_cell_author_email =
                is_current_row && matches!(self.current_col, TableColumn::AuthorEmail);
            let is_current_cell_timestamp =
                is_current_row && matches!(self.current_col, TableColumn::Timestamp);
            let is_current_cell_message =
                is_current_row && matches!(self.current_col, TableColumn::Message);

            let index_final = index_str; // Index is never editable, so no brackets
            let hash_final = hash_str; // Hash is never editable, so no brackets

            let author_name_with_mod = if commit.modifications.author_name_changed {
                format!("*{author_name_str}")
            } else {
                author_name_str
            };
            let author_name_final = author_name_with_mod;

            let author_email_with_mod = if commit.modifications.author_email_changed {
                format!("*{author_email_str}")
            } else {
                author_email_str
            };
            let author_email_final = author_email_with_mod;

            let timestamp_with_mod = if commit.modifications.timestamp_changed {
                format!("*{timestamp_str}")
            } else {
                timestamp_str
            };
            let timestamp_final = timestamp_with_mod;

            let message_with_mod = if commit.modifications.message_changed {
                format!("*{message_str}")
            } else {
                message_str
            };
            let message_final = message_with_mod;

            // Apply formatting and colors
            if is_current_row {
                if self.editing {
                    crate::say!(
                        "{:<4} {:<8} {:<15} {:<20} {:<19} {}",
                        index_final.black().on_yellow(),
                        hash_final.black().on_yellow(),
                        author_name_final.black().on_yellow(),
                        author_email_final.black().on_yellow(),
                        timestamp_final.black().on_yellow(),
                        message_final.black().on_yellow()
                    );
                } else {
                    // Current row, not editing - highlight current cell with special background
                    let index_styled = if is_current_cell_index {
                        index_final.white().on_blue()
                    } else {
                        index_final.white().on_bright_black()
                    };
                    let hash_styled = if is_current_cell_hash {
                        hash_final.white().on_blue()
                    } else {
                        hash_final.yellow().on_bright_black()
                    };
                    let author_name_styled =
                        if is_current_cell_author_name && self.editable_fields.0 {
                            author_name_final.white().on_blue()
                        } else {
                            author_name_final.cyan().on_bright_black()
                        };
                    let author_email_styled =
                        if is_current_cell_author_email && self.editable_fields.1 {
                            author_email_final.white().on_blue()
                        } else {
                            author_email_final.blue().on_bright_black()
                        };
                    let timestamp_styled = if is_current_cell_timestamp && self.editable_fields.2 {
                        timestamp_final.white().on_blue()
                    } else {
                        timestamp_final.magenta().on_bright_black()
                    };
                    let message_styled = if is_current_cell_message && self.editable_fields.3 {
                        message_final.white().on_blue()
                    } else {
                        message_final.green().on_bright_black()
                    };

                    crate::say!(
                        "{index_styled:<4} {hash_styled:<8} {author_name_styled:<15} {author_email_styled:<20} {timestamp_styled:<19} {message_styled}"
                    );
                }
            } else {
                crate::say!(
                    "{:<4} {:<8} {:<15} {:<20} {:<19} {}",
                    index_final.white(),
                    hash_final.yellow(),
                    author_name_final.cyan(),
                    author_email_final.blue(),
                    timestamp_final.magenta(),
                    message_final.green()
                );
            }
        }

        if count < self.commits.len() {
            crate::say!(
                "{}",
                format!(
                    "Rows {}-{} of {} (scroll with ↑↓)",
                    first + 1,
                    first + count,
                    self.commits.len()
                )
                .dimmed()
            );
        }
        crate::say!();

        if let Some(status) = &self.status {
            crate::say!("{} {}", "Error:".red().bold(), status.red());
        }
        if self.editing {
            crate::say!("{}: {}", "Editing".bold().yellow(), self.edit_buffer);
            crate::say!(
                "{}",
                "Press Enter to save, Esc to cancel this edit, Ctrl+C to abandon all edits"
                    .italic()
            );
        } else {
            crate::say!(
                "{}",
                "Navigation: ←→↑↓  Edit: Enter  Save & Exit: Esc  Cancel: q / Ctrl+C".italic()
            );
            crate::say!(
                "{}",
                "Tip: Use '*' when selecting range to edit ALL commits at once".dimmed()
            );
        }
    }

    fn truncate_text(&self, text: &str, max_width: usize) -> String {
        truncate_chars(text, max_width)
    }

    fn handle_navigation_key_input(&mut self, key: KeyCode) -> TableAction {
        match key {
            KeyCode::Up if self.current_row > 0 => {
                self.current_row -= 1;
            }
            KeyCode::Down if self.current_row < self.commits.len() - 1 => {
                self.current_row += 1;
            }
            KeyCode::Left => {
                self.move_to_prev_editable_column();
            }
            KeyCode::Right => {
                self.move_to_next_editable_column();
            }
            KeyCode::Char('h') => {
                // Left (vim-style)
                self.move_to_prev_editable_column();
            }
            KeyCode::Char('l') => {
                // Right (vim-style)
                self.move_to_next_editable_column();
            }
            KeyCode::Char('k') if self.current_row > 0 => {
                // Up (vim-style)
                self.current_row -= 1;
            }
            KeyCode::Char('j') if self.current_row < self.commits.len() - 1 => {
                // Down (vim-style)
                self.current_row += 1;
            }
            KeyCode::Enter => self.start_editing(),
            KeyCode::Esc => return TableAction::SaveAndExit,
            KeyCode::Char('q') => return TableAction::Cancel,
            _ => {}
        }
        TableAction::Continue
    }

    fn is_column_editable(&self, col: &TableColumn) -> bool {
        match col {
            TableColumn::Index | TableColumn::Hash => false,
            TableColumn::AuthorName => self.editable_fields.0,
            TableColumn::AuthorEmail => self.editable_fields.1,
            TableColumn::Timestamp => self.editable_fields.2,
            TableColumn::Message => self.editable_fields.3,
        }
    }

    fn move_to_next_editable_column(&mut self) {
        let columns = [
            TableColumn::Index,
            TableColumn::Hash,
            TableColumn::AuthorName,
            TableColumn::AuthorEmail,
            TableColumn::Timestamp,
            TableColumn::Message,
        ];

        let current_index = columns
            .iter()
            .position(|c| std::mem::discriminant(c) == std::mem::discriminant(&self.current_col))
            .unwrap_or(0);

        for i in 1..columns.len() {
            let next_index = (current_index + i) % columns.len();
            let next_col = &columns[next_index];
            if self.is_column_editable(next_col) {
                self.current_col = *next_col;
                return;
            }
        }
    }

    fn move_to_prev_editable_column(&mut self) {
        let columns = [
            TableColumn::Index,
            TableColumn::Hash,
            TableColumn::AuthorName,
            TableColumn::AuthorEmail,
            TableColumn::Timestamp,
            TableColumn::Message,
        ];

        let current_index = columns
            .iter()
            .position(|c| std::mem::discriminant(c) == std::mem::discriminant(&self.current_col))
            .unwrap_or(0);

        for i in 1..columns.len() {
            let prev_index = if current_index >= i {
                current_index - i
            } else {
                columns.len() - (i - current_index)
            };
            let prev_col = &columns[prev_index];
            if self.is_column_editable(prev_col) {
                self.current_col = *prev_col;
                return;
            }
        }
    }

    fn start_editing(&mut self) {
        if !self.is_column_editable(&self.current_col) {
            return; // This column is not editable
        }

        self.editing = true;

        // Initialize edit buffer with current value
        self.edit_buffer = match self.current_col {
            TableColumn::AuthorName => self.commits[self.current_row].author_name.clone(),
            TableColumn::AuthorEmail => self.commits[self.current_row].author_email.clone(),
            TableColumn::Timestamp => {
                let commit = &self.commits[self.current_row];
                format_git_time(GitTime::new(
                    commit.timestamp.and_utc().timestamp(),
                    commit.offset_minutes,
                ))
            }
            TableColumn::Message => {
                // Use the full original message when editing, not the truncated display version
                if self.commits[self.current_row].modifications.message_changed {
                    self.commits[self.current_row].message.clone()
                } else {
                    // Get the full original message from the first line or full message
                    self.commits[self.current_row].original.message.clone()
                }
            }
            _ => String::new(),
        };
    }

    fn handle_edit_key_input(&mut self, key: KeyCode) -> TableAction {
        if key != KeyCode::Enter {
            self.status = None;
        }
        match key {
            KeyCode::Esc => {
                // Esc - cancel edit
                self.editing = false;
                self.edit_buffer.clear();
            }
            KeyCode::Enter => {
                // Enter - save edit
                if let Err(e) = self.save_current_edit() {
                    // Keep the user's input and stay in edit mode; show the error separately.
                    self.status = Some(format!(
                        "{e} (fix the value or press Esc to cancel the edit)"
                    ));
                    return TableAction::Continue;
                }
                self.status = None;
                self.editing = false;
                self.edit_buffer.clear();
            }
            KeyCode::Backspace => {
                self.edit_buffer.pop();
            }
            KeyCode::Char(c) => {
                // Handle printable characters
                self.edit_buffer.push(c);
            }
            _ => {}
        }
        TableAction::Continue
    }

    /// Route one key press; Ctrl+C always abandons the session.
    fn handle_key(&mut self, key: KeyEvent) -> TableAction {
        if key.code == KeyCode::Char('c') && key.modifiers.contains(KeyModifiers::CONTROL) {
            return TableAction::Cancel;
        }
        if self.editing {
            self.handle_edit_key_input(key.code)
        } else {
            self.handle_navigation_key_input(key.code)
        }
    }

    fn save_current_edit(&mut self) -> Result<()> {
        let commit = &mut self.commits[self.current_row];

        match self.current_col {
            TableColumn::AuthorName => {
                crate::utils::validator::validate_identity_part(&self.edit_buffer, "Author name")?;
                if commit.author_name != self.edit_buffer {
                    commit.author_name = self.edit_buffer.clone();
                    commit.modifications.author_name_changed =
                        commit.original.author_name != commit.author_name;
                }
            }
            TableColumn::AuthorEmail => {
                if self.edit_buffer.trim().is_empty() {
                    return Err("Author email cannot be empty".into());
                }
                if !crate::utils::validator::is_valid_email(&self.edit_buffer) {
                    return Err("Invalid email format".into());
                }
                if commit.author_email != self.edit_buffer {
                    commit.author_email = self.edit_buffer.clone();
                    commit.modifications.author_email_changed =
                        commit.original.author_email != commit.author_email;
                }
            }
            TableColumn::Timestamp => {
                let time = parse_git_time(&self.edit_buffer)?;
                commit.timestamp = parse_utc(&self.edit_buffer)?;
                commit.offset_minutes = time.offset_minutes;
                commit.modifications.timestamp_changed = commit.original.timestamp
                    != commit.timestamp
                    || commit.original.author_offset_min != commit.offset_minutes;
            }
            TableColumn::Message => {
                if self.edit_buffer.trim().is_empty() {
                    return Err("Commit message cannot be empty".into());
                }
                if commit.message != self.edit_buffer {
                    commit.message = self.edit_buffer.clone();
                    commit.modifications.message_changed =
                        commit.original.message != commit.message;
                }
            }
            _ => {}
        }
        // A value edited back to the original no longer counts as a change.
        let m = &commit.modifications;
        commit.is_modified = m.author_name_changed
            || m.author_email_changed
            || m.timestamp_changed
            || m.message_changed;
        Ok(())
    }

    fn run(&mut self) -> Result<bool> {
        let _terminal = TerminalGuard::enter()?;
        loop {
            // Disable raw mode for drawing the table
            let _ = terminal::disable_raw_mode();
            self.draw_table();

            // Enable raw mode only for reading input
            terminal::enable_raw_mode()?;

            if let Event::Key(key) = event::read()? {
                if key.kind != KeyEventKind::Press {
                    continue;
                }
                match self.handle_key(key) {
                    TableAction::Continue => {}
                    TableAction::SaveAndExit => break Ok(true),
                    TableAction::Cancel => break Ok(false),
                }
            }
        }
    }

    fn get_modified_commits(&self) -> Vec<&CommitEdit> {
        self.commits.iter().filter(|c| c.is_modified).collect()
    }
}

/// Lines used by the table header, footer and help text.
const TABLE_CHROME_LINES: usize = 12;

/// First visible row and number of rows for a window of `height` rows that keeps `current` visible.
fn viewport(current: usize, total: usize, height: usize) -> (usize, usize) {
    let height = height.max(3).min(total);
    let first = current.saturating_sub(height / 2).min(total - height);
    (first, height)
}

/// Shorten `text` to at most `max_width` characters (never splitting a UTF-8 char).
fn truncate_chars(text: &str, max_width: usize) -> String {
    let text = &*crate::utils::sanitize::safe(text);
    if text.chars().count() > max_width {
        let kept: String = text.chars().take(max_width.saturating_sub(1)).collect();
        format!("{kept}…")
    } else {
        text.to_string()
    }
}

pub fn parse_range_input(input: &str, total_commits: usize) -> Result<(usize, usize)> {
    let trimmed_input = input.trim();

    // Check if user entered '*' to select all commits
    if trimmed_input == "*" {
        if total_commits == 0 {
            return Err("No commits available to select".into());
        }
        return Ok((1, total_commits)); // Return 1-based indexing for all commits
    }

    let parts: Vec<&str> = trimmed_input.split('-').collect();

    if parts.len() != 2 {
        return Err("Invalid range format. Use format like '5-11' or '*' for all commits".into());
    }

    let start = parts[0]
        .trim()
        .parse::<usize>()
        .map_err(|_| "Invalid start number in range")?;
    let end = parts[1]
        .trim()
        .parse::<usize>()
        .map_err(|_| "Invalid end number in range")?;

    if start < 1 {
        return Err("Start position must be 1 or greater".into());
    }

    if end < start {
        return Err("End position must be greater than or equal to start position".into());
    }

    Ok((start, end))
}

pub fn select_commit_range(commits: &[CommitInfo]) -> Result<(usize, usize)> {
    crate::say!("\n{}", "Commit History:".bold().green());
    crate::say!("{}", "-".repeat(80).cyan());

    for (i, commit) in commits.iter().enumerate() {
        crate::say!(
            "{:3}. {} {} {} {}",
            i + 1,
            commit.short_hash.yellow().bold(),
            commit
                .timestamp
                .format("%Y-%m-%d %H:%M:%S")
                .to_string()
                .blue(),
            crate::utils::sanitize::safe(&commit.author_name).magenta(),
            crate::utils::sanitize::safe(commit.message.lines().next().unwrap_or("")).white()
        );
    }

    crate::say!("{}", "-".repeat(80).cyan());
    crate::say!(
        "\n{}",
        "Enter range in format 'start-end' (e.g., '5-11') or '*' for all commits:"
            .bold()
            .green()
    );
    crate::say_inline!("{} {} ", "Range:".bold(), "(Esc to cancel)".bright_black());
    io::stdout().flush()?;

    let input = read_prompted_line()?;
    parse_selection(&input, commits.len())
}

/// Parse `N-M`, `N` or `*` (1-based, 1 = newest) into 0-based inclusive indices.
pub fn parse_selection(input: &str, total_commits: usize) -> Result<(usize, usize)> {
    let input = input.trim();
    let (start, end) = match input.parse::<usize>() {
        Ok(single) => (single, single),
        Err(_) => parse_range_input(input, total_commits)?,
    };
    if start < 1 || end > total_commits {
        return Err(format!("Range out of bounds. Available commits: 1-{total_commits}").into());
    }
    Ok((start - 1, end - 1))
}

pub fn show_range_details(commits: &[CommitInfo], start_idx: usize, end_idx: usize) -> Result<()> {
    let total_selected = end_idx - start_idx + 1;
    let is_all_commits = total_selected == commits.len();

    if is_all_commits {
        crate::say!("\n{}", "Selected All Commits for Editing:".bold().green());
    } else {
        crate::say!("\n{}", "Selected Commit Range:".bold().green());
    }
    crate::say!("{}", "=".repeat(80).cyan());

    for (idx, commit) in commits[start_idx..=end_idx].iter().enumerate() {
        crate::say!(
            "\n{}: {} ({})",
            format!("Commit {}", start_idx + idx + 1).bold(),
            commit.short_hash.yellow(),
            &commit.oid.to_string()[..8]
        );
        crate::say!(
            "{}: {}",
            "Author".bold(),
            format!("{} <{}>", commit.author_name, commit.author_email).magenta()
        );
        crate::say!(
            "{}: {}",
            "Date".bold(),
            commit
                .timestamp
                .format("%Y-%m-%d %H:%M:%S")
                .to_string()
                .blue()
        );
        crate::say!(
            "{}: {}",
            "Message".bold(),
            crate::utils::sanitize::safe(commit.message.lines().next().unwrap_or("")).white()
        );
    }

    crate::say!("\n{}", "=".repeat(80).cyan());
    if is_all_commits {
        crate::say!(
            "{} {} commits selected for editing {}",
            "Total:".bold(),
            total_selected.to_string().green(),
            "(ALL COMMITS)".bold().yellow()
        );
    } else {
        crate::say!(
            "{} {} commits selected for editing",
            "Total:".bold(),
            total_selected.to_string().green()
        );
    }

    Ok(())
}

pub fn rewrite_range_commits(args: &Args) -> Result<()> {
    let commits = get_commit_history(args, false)?;

    if commits.is_empty() {
        crate::say!("{}", "No commits found!".red());
        return Ok(());
    }
    // Fail early on a detached/unborn HEAD and remember the tip the edits are based on.
    let head = engine::current_branch(&Repository::open(args.repo_path.as_ref().unwrap())?)?.head;

    if let Some(selection) = &args.select {
        return rewrite_selection_from_flags(args, &commits, selection, head);
    }

    let (start_idx, end_idx) = select_commit_range(&commits)?;

    // Show range details for user feedback
    show_range_details(&commits, start_idx, end_idx)?;

    // Get editable fields based on command line flags
    let editable_fields = args.get_editable_fields();

    // Launch interactive table editor
    let mut table = InteractiveTable::new(commits.clone(), start_idx, end_idx, editable_fields);
    let should_save = table.run()?;

    if !should_save {
        return Err(cancelled());
    }

    let modified_commits = table.get_modified_commits();

    if modified_commits.is_empty() {
        crate::say!("{}", "No changes made.".yellow());
        return Ok(());
    }

    // Show summary of changes
    crate::say!("\n{}", "Summary of Changes:".bold().green());
    crate::say!("{}", "=".repeat(80).cyan());

    for commit_edit in &modified_commits {
        crate::say!(
            "\n{}: {} ({})",
            format!("Commit {}", commit_edit.index + 1).bold(),
            commit_edit.original.short_hash.yellow(),
            &commit_edit.original.oid.to_string()[..8]
        );

        if commit_edit.modifications.author_name_changed {
            crate::say!(
                "  {}: {} -> {}",
                "Author Name".bold(),
                crate::utils::sanitize::safe(&commit_edit.original.author_name).red(),
                crate::utils::sanitize::safe(&commit_edit.author_name).green()
            );
        }

        if commit_edit.modifications.author_email_changed {
            crate::say!(
                "  {}: {} -> {}",
                "Author Email".bold(),
                crate::utils::sanitize::safe(&commit_edit.original.author_email).red(),
                crate::utils::sanitize::safe(&commit_edit.author_email).green()
            );
        }

        if commit_edit.modifications.timestamp_changed {
            crate::say!(
                "  {}: {} -> {}",
                "Timestamp".bold(),
                commit_edit
                    .original
                    .timestamp
                    .format("%Y-%m-%d %H:%M:%S")
                    .to_string()
                    .red(),
                commit_edit
                    .timestamp
                    .format("%Y-%m-%d %H:%M:%S")
                    .to_string()
                    .green()
            );
        }

        if commit_edit.modifications.message_changed {
            let original_first_line = commit_edit.original.message.lines().next().unwrap_or("");
            let new_first_line = commit_edit.message.lines().next().unwrap_or("");
            crate::say!(
                "  {}: {} -> {}",
                "Message".bold(),
                crate::utils::sanitize::safe(original_first_line).red(),
                crate::utils::sanitize::safe(new_first_line).green()
            );
        }
    }

    if args.simulate {
        let plan = plan_from_table(&table.commits, args.committer.into());
        let preview = simulation_from_plan(&commits, &plan, "Range Edit");
        report_simulation(&preview, args.show_diff, true);
        crate::say!("{}", "Simulation only: nothing was written.".cyan());
        return Ok(());
    }

    if !confirm(&format!("\n{}", "Apply these changes?".bold()), args.yes)? {
        return Err(cancelled());
    }

    // Apply changes
    apply_interactive_range_changes(args, &table.commits, head)?;

    if args.show_history {
        get_commit_history(args, true)?;
    }

    Ok(())
}

/// Non-interactive range edit: `--select` with `--name/--email/--begin/--end`.
fn rewrite_selection_from_flags(
    args: &Args,
    commits: &[CommitInfo],
    selection: &str,
    expected_head: git2::Oid,
) -> Result<()> {
    let (first, last) = parse_selection(selection, commits.len())?;
    // Selected commits, oldest first.
    let selected: Vec<&CommitInfo> = commits[first..=last].iter().rev().collect();

    if let Some(name) = &args.name {
        validate_identity_part(name, "Author name")?;
    }
    if let Some(email) = &args.email {
        if !is_valid_email(email) {
            return Err(format!("Invalid email format: {email}").into());
        }
    }
    let times: Option<Vec<GitTime>> = match (&args.start, &args.end) {
        (Some(begin), Some(end)) => {
            let spread = spread_timestamps(
                parse_utc(begin)?,
                parse_utc(end)?,
                selected.len(),
                args.skip_range_check,
            )?;
            let offset = begin_offset(args);
            Some(
                spread
                    .iter()
                    .map(|t| GitTime::new(t.and_utc().timestamp(), offset))
                    .collect(),
            )
        }
        (None, None) => None,
        _ => return Err("--begin and --end must be given together".into()),
    };
    if args.name.is_none() && args.email.is_none() && times.is_none() {
        return Err(
            "Nothing to change: pass --name, --email and/or --begin/--end with --select".into(),
        );
    }
    if let Some(times) = &times {
        warn_if_out_of_order(commits, first, last, times);
    }

    let edits = selected
        .iter()
        .enumerate()
        .map(|(i, commit)| {
            let edit = Edit {
                name: args.name.clone(),
                email: args.email.clone(),
                time: times.as_ref().map(|t| t[i]),
                message: None,
            };
            (commit.oid, edit)
        })
        .collect();
    let plan = Plan {
        edits,
        committer: args.committer.into(),
    };

    let preview = simulation_from_plan(commits, &plan, "Range Edit");
    report_simulation(&preview, args.show_diff, args.simulate);
    if args.simulate {
        crate::say!("{}", "Simulation only: nothing was written.".cyan());
        return Ok(());
    }
    if !confirm(&format!("\n{}", "Apply these changes?".bold()), args.yes)? {
        return Err(cancelled());
    }
    let repo = Repository::open(args.repo_path.as_ref().unwrap())?;
    let outcome = engine::apply(&repo, &plan, expected_head)?;
    print_outcome(&outcome);
    Ok(())
}

/// Warn when new dates would put the selection before its parent or after its child.
fn warn_if_out_of_order(commits: &[CommitInfo], first: usize, last: usize, times: &[GitTime]) {
    let older_neighbor = commits
        .get(last + 1)
        .map(|c| c.timestamp.and_utc().timestamp());
    let newer_neighbor = first
        .checked_sub(1)
        .map(|i| commits[i].timestamp.and_utc().timestamp());
    let (Some(earliest), Some(latest)) = (times.first(), times.last()) else {
        return;
    };
    if older_neighbor.is_some_and(|t| t > earliest.seconds)
        || newer_neighbor.is_some_and(|t| t < latest.seconds)
    {
        crate::say!(
            "{} the new dates are not in order with the commits around the selection",
            "Warning:".yellow().bold()
        );
    }
}

/// Plan for the commits edited in the table (keyed by id; untouched commits are absent).
fn plan_from_table(
    edited_commits: &[CommitEdit],
    committer: crate::rewrite::engine::CommitterMode,
) -> Plan {
    let edits = edited_commits
        .iter()
        .filter(|c| c.is_modified)
        .map(|c| {
            let m = &c.modifications;
            let edit = Edit {
                name: m.author_name_changed.then(|| c.author_name.clone()),
                email: m.author_email_changed.then(|| c.author_email.clone()),
                time: m
                    .timestamp_changed
                    .then(|| GitTime::new(c.timestamp.and_utc().timestamp(), c.offset_minutes)),
                message: m.message_changed.then(|| c.message.clone()),
            };
            (c.original.oid, edit)
        })
        .collect();
    Plan { edits, committer }
}

/// Rewrite only the commits edited in the table; older commits keep their ids.
fn apply_interactive_range_changes(
    args: &Args,
    edited_commits: &[CommitEdit],
    expected_head: git2::Oid,
) -> Result<()> {
    let repo = Repository::open(args.repo_path.as_ref().unwrap())?;
    let plan = plan_from_table(edited_commits, args.committer.into());
    let outcome = engine::apply(&repo, &plan, expected_head)?;
    print_outcome(&outcome);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn create_test_repo_with_commits() -> (TempDir, String) {
        let temp_dir = TempDir::new().unwrap();
        let repo_path = temp_dir.path().to_str().unwrap().to_string();

        // Initialize git repo
        let repo = git2::Repository::init(&repo_path).unwrap();

        // Create multiple commits
        for i in 1..=5 {
            let file_path = temp_dir.path().join(format!("test{i}.txt"));
            fs::write(&file_path, format!("test content {i}")).unwrap();

            let mut index = repo.index().unwrap();
            index
                .add_path(std::path::Path::new(&format!("test{i}.txt")))
                .unwrap();
            index.write().unwrap();

            let tree_id = index.write_tree().unwrap();
            let tree = repo.find_tree(tree_id).unwrap();

            let sig = git2::Signature::new(
                "Test User",
                "test@example.com",
                &git2::Time::new(1234567890 + i as i64 * 3600, 0),
            )
            .unwrap();

            let parents = if i == 1 {
                vec![]
            } else {
                let head = repo.head().unwrap();
                let parent_commit = head.peel_to_commit().unwrap();
                vec![parent_commit]
            };

            repo.commit(
                Some("HEAD"),
                &sig,
                &sig,
                &format!("Commit {i}"),
                &tree,
                &parents.iter().collect::<Vec<_>>(),
            )
            .unwrap();
        }

        (temp_dir, repo_path)
    }

    fn table_with_one_commit() -> InteractiveTable {
        let commit = CommitInfo {
            author_name: "Old Author".into(),
            author_email: "old@example.com".into(),
            message: "msg\n".into(),
            ..Default::default()
        };
        InteractiveTable::new(vec![commit], 0, 0, (true, true, true, true))
    }

    #[test]
    fn test_validation_error_is_not_saved_as_value() {
        let mut table = table_with_one_commit();
        table.current_col = TableColumn::AuthorName;
        table.start_editing();
        for _ in 0.."Old Author".len() {
            table.handle_edit_key_input(KeyCode::Backspace);
        }
        table.handle_edit_key_input(KeyCode::Enter);
        assert!(table.status.is_some());
        assert!(table.editing);
        assert_eq!(table.edit_buffer, "");
        table.handle_edit_key_input(KeyCode::Enter);
        assert_eq!(table.commits[0].author_name, "Old Author");
        assert!(!table.commits[0].is_modified);
    }

    #[test]
    fn test_ctrl_c_and_q_cancel_esc_saves() {
        let ctrl_c = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
        let mut table = table_with_one_commit();
        assert_eq!(table.handle_key(ctrl_c), TableAction::Cancel);
        table.start_editing();
        assert_eq!(table.handle_key(ctrl_c), TableAction::Cancel);
        assert!(!table.edit_buffer.ends_with('c'));

        let mut table = table_with_one_commit();
        let q = KeyEvent::new(KeyCode::Char('q'), KeyModifiers::NONE);
        assert_eq!(table.handle_key(q), TableAction::Cancel);
        let esc = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
        assert_eq!(table.handle_key(esc), TableAction::SaveAndExit);
    }

    #[test]
    fn test_reverted_edit_is_not_a_change() {
        let mut table = table_with_one_commit();
        table.current_col = TableColumn::AuthorName;
        table.start_editing();
        table.edit_buffer = "Someone Else".into();
        table.handle_edit_key_input(KeyCode::Enter);
        assert!(table.commits[0].is_modified);
        table.start_editing();
        table.edit_buffer = "Old Author".into();
        table.handle_edit_key_input(KeyCode::Enter);
        assert!(!table.commits[0].is_modified);
        assert!(table.get_modified_commits().is_empty());
    }

    #[test]
    fn test_viewport_keeps_current_row_visible() {
        assert_eq!(viewport(0, 5, 20), (0, 5));
        assert_eq!(viewport(0, 100, 10), (0, 10));
        assert_eq!(viewport(50, 100, 10), (45, 10));
        assert_eq!(viewport(99, 100, 10), (90, 10));
        assert_eq!(viewport(1, 2, 0), (0, 2));
        for current in 0..100 {
            let (first, count) = viewport(current, 100, 7);
            assert!(first <= current && current < first + count);
        }
    }

    #[test]
    fn test_truncate_chars_handles_multibyte_text() {
        assert_eq!(truncate_chars("张三李四王五", 5), "张三李四…");
        assert_eq!(truncate_chars("émoji 🎉 ok", 20), "émoji 🎉 ok");
        assert_eq!(truncate_chars("abcdef", 4), "abc…");
        assert_eq!(truncate_chars("", 3), "");
    }

    #[test]
    fn test_parse_selection_bounds_and_forms() {
        assert_eq!(parse_selection("2-4", 5).unwrap(), (1, 3));
        assert_eq!(parse_selection("3", 5).unwrap(), (2, 2));
        assert_eq!(parse_selection("*", 5).unwrap(), (0, 4));
        assert!(parse_selection("4-9", 5).is_err());
        assert!(parse_selection("0", 5).is_err());
        assert!(parse_selection("3-2", 5).is_err());
    }

    #[test]
    fn test_parse_range_input_valid() {
        let result = parse_range_input("5-11", 20);
        assert!(result.is_ok());
        let (start, end) = result.unwrap();
        assert_eq!(start, 5);
        assert_eq!(end, 11);
    }

    #[test]
    fn test_parse_range_input_with_spaces() {
        let result = parse_range_input(" 3 - 8 ", 20);
        assert!(result.is_ok());
        let (start, end) = result.unwrap();
        assert_eq!(start, 3);
        assert_eq!(end, 8);
    }

    #[test]
    fn test_parse_range_input_asterisk() {
        let result = parse_range_input("*", 10);
        assert!(result.is_ok());
        let (start, end) = result.unwrap();
        assert_eq!(start, 1);
        assert_eq!(end, 10);

        // Test with empty repository
        let result = parse_range_input("*", 0);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_range_input_invalid_format() {
        let result = parse_range_input("5", 20);
        assert!(result.is_err());

        let result = parse_range_input("5-11-15", 20);
        assert!(result.is_err());

        let result = parse_range_input("abc-def", 20);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_range_input_invalid_range() {
        let result = parse_range_input("11-5", 20);
        assert!(result.is_err());

        let result = parse_range_input("0-5", 20);
        assert!(result.is_err());
    }

    #[test]
    fn test_apply_range_changes_correct_commit_ordering() {
        // This test verifies that editing commit at display index 0 (newest)
        // actually modifies the newest commit, not the oldest.
        let (_temp_dir, repo_path) = create_test_repo_with_commits();
        let args = Args {
            repo_path: Some(repo_path.clone()),
            range: true,
            ..Default::default()
        };

        // get_commit_history returns newest-first
        let commits = get_commit_history(&args, false).unwrap();
        assert_eq!(commits.len(), 5);
        assert_eq!(commits[0].message, "Commit 5"); // newest
        assert_eq!(commits[4].message, "Commit 1"); // oldest

        // Simulate editing only the newest commit (display index 0)
        let new_timestamp =
            NaiveDateTime::parse_from_str("2099-06-15 12:00:00", "%Y-%m-%d %H:%M:%S").unwrap();

        let mut edited_commits: Vec<CommitEdit> = commits
            .iter()
            .enumerate()
            .map(|(i, c)| CommitEdit {
                index: i,
                original: c.clone(),
                author_name: c.author_name.clone(),
                author_email: c.author_email.clone(),
                timestamp: c.timestamp,
                offset_minutes: c.author_offset_min,
                message: c.message.clone(),
                is_modified: false,
                modifications: ModificationFlags::default(),
            })
            .collect();

        // Mark only index 0 (newest = "Commit 5") as modified
        edited_commits[0].timestamp = new_timestamp;
        edited_commits[0].is_modified = true;
        edited_commits[0].modifications.timestamp_changed = true;

        // Apply changes
        let original_ids: Vec<_> = commits.iter().map(|c| c.oid).collect();
        apply_interactive_range_changes(&args, &edited_commits, commits[0].oid).unwrap();

        // Re-read and verify
        let updated_commits = get_commit_history(&args, false).unwrap();
        assert_eq!(updated_commits.len(), 5);

        // The newest commit (index 0, "Commit 5") should have the new timestamp
        assert_eq!(
            updated_commits[0].timestamp, new_timestamp,
            "Newest commit should have the edited timestamp"
        );

        // The oldest commit (index 4, "Commit 1") should NOT have the new timestamp
        assert_ne!(
            updated_commits[4].timestamp, new_timestamp,
            "Oldest commit should NOT have the edited timestamp"
        );

        // All older commits are reused untouched: same ids, same timestamps.
        for (i, commit) in updated_commits.iter().enumerate().skip(1) {
            assert_eq!(commit.oid, original_ids[i], "commit {i} must keep its id");
            assert_eq!(commit.timestamp, commits[i].timestamp);
        }
    }

    #[test]
    fn test_editing_middle_commit_keeps_older_commit_ids() {
        let (_temp_dir, repo_path) = create_test_repo_with_commits();
        let args = Args {
            repo_path: Some(repo_path.clone()),
            range: true,
            ..Default::default()
        };
        let commits = get_commit_history(&args, false).unwrap();
        let mut edits: Vec<CommitEdit> = commits
            .iter()
            .enumerate()
            .map(|(i, c)| CommitEdit {
                index: i,
                original: c.clone(),
                author_name: c.author_name.clone(),
                author_email: c.author_email.clone(),
                timestamp: c.timestamp,
                offset_minutes: c.author_offset_min,
                message: c.message.clone(),
                is_modified: false,
                modifications: ModificationFlags::default(),
            })
            .collect();
        // Display index 2 = "Commit 3"; commits 1 and 2 are older.
        edits[2].timestamp += chrono::Duration::hours(1);
        edits[2].is_modified = true;
        edits[2].modifications.timestamp_changed = true;

        apply_interactive_range_changes(&args, &edits, commits[0].oid).unwrap();

        let updated = get_commit_history(&args, false).unwrap();
        assert_eq!(updated[3].oid, commits[3].oid);
        assert_eq!(updated[4].oid, commits[4].oid);
        assert_ne!(updated[2].oid, commits[2].oid);
        assert_eq!(updated[2].timestamp, edits[2].timestamp);
        assert_eq!(updated[0].message, "Commit 5");
    }
}