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
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
//! Process our event log.
//!
//! We use Git hooks to record the actions that the user takes over time, and put
//! them in persistent storage. Later, we play back the actions in order to
//! determine what actions the user took on the repository, and which commits
//! they're still working on.

use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::convert::{TryFrom, TryInto};

use std::str::FromStr;
use std::time::{Duration, SystemTime};

use eyre::Context;
use tracing::{error, instrument};

use crate::core::effects::{Effects, OperationType};
use crate::core::repo_ext::RepoExt;
use crate::git::{CategorizedReferenceName, MaybeZeroOid, NonZeroOid, ReferenceName, Repo};

use super::repo_ext::RepoReferencesSnapshot;

/// When this environment variable is set, we reuse the ID for the transaction
/// which the caller has already started.
pub const BRANCHLESS_TRANSACTION_ID_ENV_VAR: &str = "BRANCHLESS_TRANSACTION_ID";

// Wrapper around the row stored directly in the database.
#[derive(Clone, Debug)]
struct Row {
    timestamp: f64,
    type_: String,
    event_tx_id: isize,
    ref1: Option<ReferenceName>,
    ref2: Option<ReferenceName>,
    ref_name: Option<ReferenceName>,
    message: Option<ReferenceName>,
}

/// The ID associated with the transactions that created an event.
///
/// A "event transaction" is a group of logically-related events. For example,
/// during a rebase operation, all of the rebased commits have different
/// `CommitEvent`s, but should belong to the same transaction. This improves the
/// experience for `git undo`, since the user probably wants to see or undo all
/// of the logically-related events at once, rather than individually.
///
/// Note that some logically-related events may not be included together in the
/// same transaction. For example, if a rebase is interrupted due to a merge
/// conflict, then the commits applied due to `git rebase` and the commits
/// applied due to `git rebase --continue` may not share the same transaction.
/// In this sense, a transaction is "best-effort".
///
/// Unlike in a database, there is no specific guarantee that an event
/// transaction is an atomic unit of work.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EventTransactionId(isize);

impl ToString for EventTransactionId {
    fn to_string(&self) -> String {
        let EventTransactionId(event_id) = self;
        event_id.to_string()
    }
}

impl FromStr for EventTransactionId {
    type Err = <isize as FromStr>::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let event_id = s.parse()?;
        Ok(EventTransactionId(event_id))
    }
}

/// An event that occurred to one of the commits in the repository.
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
    /// Indicates that the commit was rewritten.
    ///
    /// Examples of rewriting include rebases and amended commits.
    ///
    /// We typically want to mark the new version of the commit as active and
    /// the old version of the commit as obsolete.
    RewriteEvent {
        /// The timestamp of the event.
        timestamp: f64,

        /// The transaction ID of the event.
        event_tx_id: EventTransactionId,

        /// The OID of the commit before the rewrite.
        old_commit_oid: MaybeZeroOid,

        /// The OID of the commit after the rewrite.
        new_commit_oid: MaybeZeroOid,
    },

    /// Indicates that a reference was updated.
    ///
    /// The most important reference we track is HEAD. In principle, we can also
    /// track branch moves in this way, but Git doesn't support the appropriate
    /// hook until v2.29 (`reference-transaction`).
    RefUpdateEvent {
        /// The timestamp of the event.
        timestamp: f64,

        /// The transaction ID of the event.
        event_tx_id: EventTransactionId,

        /// The full name of the reference that was updated.
        ///
        /// For example, `HEAD` or `refs/heads/master`.
        ref_name: ReferenceName,

        /// The old referent OID.
        old_oid: MaybeZeroOid,

        /// The updated referent OID.
        new_oid: MaybeZeroOid,

        /// A message associated with the rewrite, if any.
        message: Option<ReferenceName>,
    },

    /// Indicate that the user made a commit.
    ///
    /// User commits should be marked as active.
    CommitEvent {
        /// The timestamp of the event.
        timestamp: f64,

        /// The transaction ID of the event.
        event_tx_id: EventTransactionId,

        /// The new commit OID.
        commit_oid: NonZeroOid,
    },

    /// Indicates that a commit was explicitly obsoleted by the user.
    ///
    /// If the commit in question was not already active, then this has no
    /// practical effect.
    ObsoleteEvent {
        /// The timestamp of the event.
        timestamp: f64,

        /// The transaction ID of the event.
        event_tx_id: EventTransactionId,

        /// The OID of the commit that was obsoleted.
        commit_oid: NonZeroOid,
    },

    /// Indicates that a commit was explicitly un-obsoleted by the user.
    ///
    /// If the commit in question was not already obsolete, then this has no
    /// practical effect.
    UnobsoleteEvent {
        /// The timestamp of the event.
        timestamp: f64,

        /// The transaction ID of the event.
        event_tx_id: EventTransactionId,

        /// The OID of the commit that was unobsoleted.
        commit_oid: NonZeroOid,
    },

    /// Represents a snapshot of the working copy made at a certain time,
    /// typically before a potentially-destructive operation.
    WorkingCopySnapshot {
        /// The timestamp of the event.
        timestamp: f64,

        /// The transaction ID of the event.
        event_tx_id: EventTransactionId,

        /// The OID of the current HEAD commit.
        head_oid: MaybeZeroOid,

        /// The OID of the commit containing metadata about the working copy
        /// snapshot.
        commit_oid: NonZeroOid,

        /// The name of the checked-out branch, if any. This should be a full
        /// reference name like `refs/heads/foo`.
        ref_name: Option<ReferenceName>,
    },
}

impl Event {
    /// Get the timestamp associated with this event.
    pub fn get_timestamp(&self) -> SystemTime {
        let timestamp = match self {
            Event::RewriteEvent { timestamp, .. } => timestamp,
            Event::RefUpdateEvent { timestamp, .. } => timestamp,
            Event::CommitEvent { timestamp, .. } => timestamp,
            Event::ObsoleteEvent { timestamp, .. } => timestamp,
            Event::UnobsoleteEvent { timestamp, .. } => timestamp,
            Event::WorkingCopySnapshot { timestamp, .. } => timestamp,
        };
        SystemTime::UNIX_EPOCH + Duration::from_secs_f64(*timestamp)
    }

    /// Get the event transaction ID associated with this event.
    pub fn get_event_tx_id(&self) -> EventTransactionId {
        match self {
            Event::RewriteEvent { event_tx_id, .. } => *event_tx_id,
            Event::RefUpdateEvent { event_tx_id, .. } => *event_tx_id,
            Event::CommitEvent { event_tx_id, .. } => *event_tx_id,
            Event::ObsoleteEvent { event_tx_id, .. } => *event_tx_id,
            Event::UnobsoleteEvent { event_tx_id, .. } => *event_tx_id,
            Event::WorkingCopySnapshot { event_tx_id, .. } => *event_tx_id,
        }
    }
}

impl From<Event> for Row {
    fn from(event: Event) -> Row {
        match event {
            Event::RewriteEvent {
                timestamp,
                event_tx_id: EventTransactionId(event_tx_id),
                old_commit_oid,
                new_commit_oid,
            } => Row {
                timestamp,
                event_tx_id,
                type_: String::from("rewrite"),
                ref1: Some(old_commit_oid.into()),
                ref2: Some(new_commit_oid.into()),
                ref_name: None,
                message: None,
            },

            Event::RefUpdateEvent {
                timestamp,
                event_tx_id: EventTransactionId(event_tx_id),
                ref_name,
                old_oid,
                new_oid,
                message,
            } => Row {
                timestamp,
                event_tx_id,
                type_: String::from("ref-move"),
                ref1: Some(old_oid.into()),
                ref2: Some(new_oid.into()),
                ref_name: Some(ref_name),
                message,
            },

            Event::CommitEvent {
                timestamp,
                event_tx_id: EventTransactionId(event_tx_id),
                commit_oid,
            } => Row {
                timestamp,
                event_tx_id,
                type_: String::from("commit"),
                ref1: Some(commit_oid.into()),
                ref2: None,
                ref_name: None,
                message: None,
            },

            Event::ObsoleteEvent {
                timestamp,
                event_tx_id: EventTransactionId(event_tx_id),
                commit_oid,
            } => Row {
                timestamp,
                event_tx_id,
                type_: String::from("hide"), // historical name
                ref1: Some(commit_oid.into()),
                ref2: None,
                ref_name: None,
                message: None,
            },

            Event::UnobsoleteEvent {
                timestamp,
                event_tx_id: EventTransactionId(event_tx_id),
                commit_oid,
            } => Row {
                timestamp,
                event_tx_id,
                type_: String::from("unhide"), // historical name
                ref1: Some(commit_oid.into()),
                ref2: None,
                ref_name: None,
                message: None,
            },

            Event::WorkingCopySnapshot {
                timestamp,
                event_tx_id: EventTransactionId(event_tx_id),
                head_oid,
                commit_oid,
                ref_name,
            } => Row {
                timestamp,
                event_tx_id,
                type_: String::from("snapshot"),
                ref1: Some(head_oid.to_string().into()),
                ref2: Some(commit_oid.into()),
                ref_name,
                message: None,
            },
        }
    }
}

fn try_from_row_helper(row: &Row) -> Result<Event, eyre::Error> {
    let row: Row = row.clone();
    let Row {
        timestamp,
        event_tx_id,
        type_,
        ref_name,
        ref1,
        ref2,
        message,
    } = row;
    let event_tx_id = EventTransactionId(event_tx_id);

    let get_oid =
        |reference_name: &Option<ReferenceName>, oid_name: &str| -> eyre::Result<MaybeZeroOid> {
            match reference_name {
                Some(reference_name) => {
                    let oid: MaybeZeroOid = reference_name.as_str().parse()?;
                    Ok(oid)
                }
                None => Err(eyre::eyre!(
                    "OID '{}' was `None` for event type '{}'",
                    oid_name,
                    type_
                )),
            }
        };

    let event = match type_.as_str() {
        "rewrite" => {
            let old_commit_oid = get_oid(&ref1, "old commit OID")?;
            let new_commit_oid = get_oid(&ref2, "new commit OID")?;
            Event::RewriteEvent {
                timestamp,
                event_tx_id,
                old_commit_oid,
                new_commit_oid,
            }
        }

        "ref-move" => {
            let ref_name =
                ref_name.ok_or_else(|| eyre::eyre!("ref-move event missing ref name"))?;
            let ref1 = ref1.ok_or_else(|| eyre::eyre!("ref-move event missing ref1"))?;
            let ref2 = ref2.ok_or_else(|| eyre::eyre!("ref-move event missing ref2"))?;
            Event::RefUpdateEvent {
                timestamp,
                event_tx_id,
                ref_name,
                old_oid: ref1.as_str().parse()?,
                new_oid: ref2.as_str().parse()?,
                message,
            }
        }

        "commit" => {
            let commit_oid: NonZeroOid = get_oid(&ref1, "commit OID")?.try_into()?;
            Event::CommitEvent {
                timestamp,
                event_tx_id,
                commit_oid,
            }
        }

        "hide" => {
            let commit_oid: NonZeroOid = get_oid(&ref1, "commit OID")?.try_into()?;
            Event::ObsoleteEvent {
                timestamp,
                event_tx_id,
                commit_oid,
            }
        }

        "unhide" => {
            let commit_oid: NonZeroOid = get_oid(&ref1, "commit OID")?.try_into()?;
            Event::UnobsoleteEvent {
                timestamp,
                event_tx_id,
                commit_oid,
            }
        }

        "snapshot" => {
            let head_oid: MaybeZeroOid = get_oid(&ref1, "head OID")?;
            let commit_oid: NonZeroOid = get_oid(&ref2, "commit OID")?.try_into()?;
            Event::WorkingCopySnapshot {
                timestamp,
                event_tx_id,
                head_oid,
                commit_oid,
                ref_name,
            }
        }

        other => eyre::bail!("Unknown event type {}", other),
    };
    Ok(event)
}

impl TryFrom<Row> for Event {
    type Error = eyre::Error;

    fn try_from(row: Row) -> Result<Self, Self::Error> {
        match try_from_row_helper(&row) {
            Ok(event) => Ok(event),
            Err(err) => {
                error!(?row, "Could not convert row into event");
                Err(err)
            }
        }
    }
}

/// Stores `Event`s on disk.
pub struct EventLogDb<'conn> {
    conn: &'conn rusqlite::Connection,
}

impl std::fmt::Debug for EventLogDb<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "<EventLogDb>")
    }
}

#[instrument]
fn init_tables(conn: &rusqlite::Connection) -> eyre::Result<()> {
    conn.execute(
        "
CREATE TABLE IF NOT EXISTS event_log (
    timestamp REAL NOT NULL,
    type TEXT NOT NULL,
    event_tx_id INTEGER NOT NULL,
    old_ref TEXT,
    new_ref TEXT,
    ref_name TEXT,
    message TEXT
)
",
        rusqlite::params![],
    )
    .wrap_err("Creating `event_log` table")?;

    conn.execute(
        "
CREATE TABLE IF NOT EXISTS event_transactions (
    timestamp REAL NOT NULL,

    -- Set as `PRIMARY KEY` to have SQLite select a value automatically. Set as
    -- `AUTOINCREMENT` to ensure that SQLite doesn't reuse the value later if a
    -- row is deleted. (We don't plan to delete rows right now, but maybe
    -- later?)
    event_tx_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,

    message TEXT
)
",
        rusqlite::params![],
    )
    .wrap_err("Creating `event_transactions` table")?;

    Ok(())
}

impl<'conn> EventLogDb<'conn> {
    /// Constructor.
    #[instrument]
    pub fn new(conn: &'conn rusqlite::Connection) -> eyre::Result<Self> {
        init_tables(conn)?;
        Ok(EventLogDb { conn })
    }

    /// Add events in the given order to the database, in a transaction.
    ///
    /// Args:
    /// * events: The events to add.
    #[instrument]
    pub fn add_events(&self, events: Vec<Event>) -> eyre::Result<()> {
        let tx = self.conn.unchecked_transaction()?;
        for event in events {
            let Row {
                timestamp,
                type_,
                event_tx_id,
                ref1,
                ref2,
                ref_name,
                message,
            } = Row::from(event);

            let ref1 = ref1.as_ref().map(|x| x.as_str());
            let ref2 = ref2.as_ref().map(|x| x.as_str());
            let ref_name = ref_name.as_ref().map(|x| x.as_str());
            let message = message.as_ref().map(|x| x.as_str());

            tx.execute(
                "
INSERT INTO event_log VALUES (
    :timestamp,
    :type,
    :event_tx_id,
    :old_ref,
    :new_ref,
    :ref_name,
    :message
)
            ",
                rusqlite::named_params! {
                    ":timestamp": timestamp,
                    ":type": &type_,
                    ":event_tx_id": event_tx_id,
                    ":old_ref": &ref1,
                    ":new_ref": &ref2,
                    ":ref_name": &ref_name,
                    ":message": &message,
                },
            )?;
        }
        tx.commit()?;
        Ok(())
    }

    /// Get all the events in the database.
    ///
    /// Returns: All the events in the database, ordered from oldest to newest.
    #[instrument]

    pub fn get_events(&self) -> eyre::Result<Vec<Event>> {
        let mut stmt = self.conn.prepare(
            "
SELECT timestamp, type, event_tx_id, old_ref, new_ref, ref_name, message
FROM event_log
ORDER BY rowid ASC
",
        )?;
        let rows: rusqlite::Result<Vec<Row>> = stmt
            .query_map(rusqlite::params![], |row| {
                let timestamp: f64 = row.get("timestamp")?;
                let event_tx_id: isize = row.get("event_tx_id")?;
                let type_: String = row.get("type")?;
                let ref_name: Option<String> = row.get("ref_name")?;
                let old_ref: Option<String> = row.get("old_ref")?;
                let new_ref: Option<String> = row.get("new_ref")?;
                let message: Option<String> = row.get("message")?;

                Ok(Row {
                    timestamp,
                    event_tx_id,
                    type_,
                    ref_name: ref_name.map(ReferenceName::from),
                    ref1: old_ref.map(ReferenceName::from),
                    ref2: new_ref.map(ReferenceName::from),
                    message: message.map(ReferenceName::from),
                })
            })?
            .collect();
        let rows = rows?;
        rows.into_iter().map(Event::try_from).collect()
    }

    #[instrument]
    fn make_transaction_id_inner(
        &self,
        now: SystemTime,
        message: &str,
    ) -> eyre::Result<EventTransactionId> {
        if let Ok(transaction_id) = std::env::var(BRANCHLESS_TRANSACTION_ID_ENV_VAR) {
            if let Ok(transaction_id) = transaction_id.parse::<EventTransactionId>() {
                return Ok(transaction_id);
            }
        }

        let tx = self.conn.unchecked_transaction()?;

        let timestamp = now
            .duration_since(SystemTime::UNIX_EPOCH)
            .wrap_err("Calculating event transaction timestamp")?
            .as_secs_f64();
        self.conn
            .execute(
                "
            INSERT INTO event_transactions
            (timestamp, message)
            VALUES
            (:timestamp, :message)
        ",
                rusqlite::named_params! {
                    ":timestamp": timestamp,
                    ":message": message,
                },
            )
            .wrap_err("Creating event transaction")?;

        // Ensure that we query `last_insert_rowid` in a transaction, in case
        // there's another thread in this process making queries with the same
        // SQLite connection.
        let event_tx_id: isize = self.conn.last_insert_rowid().try_into()?;
        tx.commit()?;
        Ok(EventTransactionId(event_tx_id))
    }

    /// Create a new event transaction ID to be used to insert subsequent
    /// `Event`s into the database.
    pub fn make_transaction_id(
        &self,
        now: SystemTime,
        message: impl AsRef<str>,
    ) -> eyre::Result<EventTransactionId> {
        self.make_transaction_id_inner(now, message.as_ref())
    }

    /// Get the message associated with the given transaction.
    pub fn get_transaction_message(&self, event_tx_id: EventTransactionId) -> eyre::Result<String> {
        let EventTransactionId(event_tx_id) = event_tx_id;
        let mut stmt = self.conn.prepare(
            "
SELECT message
FROM event_transactions
WHERE event_tx_id = :event_tx_id
",
        )?;
        let result: String = stmt.query_row(
            rusqlite::named_params![":event_tx_id": event_tx_id,],
            |row| {
                let message: String = row.get("message")?;
                Ok(message)
            },
        )?;
        Ok(result)
    }
}

/// Determine whether a given reference is used to keep a commit alive.
///
/// Returns: Whether or not the given reference is used internally to keep the
/// commit alive, so that it's not collected by Git's garbage collection
/// mechanism.
pub fn is_gc_ref(reference_name: &ReferenceName) -> bool {
    reference_name.as_str().starts_with("refs/branchless/")
}

/// Determines whether or not updates to the given reference should be ignored.
///
/// Returns: Whether or not updates to the given reference should be ignored.
pub fn should_ignore_ref_updates(reference_name: &ReferenceName) -> bool {
    if is_gc_ref(reference_name) {
        return true;
    }

    matches!(
        reference_name.as_str(),
        "ORIG_HEAD" | "CHERRY_PICK" | "REBASE_HEAD" | "CHERRY_PICK_HEAD" | "FETCH_HEAD"
    )
}

#[derive(Debug)]
enum EventClassification {
    Show,
    Hide,
}

/// Whether or not a commit is considered active.
///
/// This is determined by the last `Event` that affected the commit. If no
/// activity has been observed for a commit, it's considered inactive.
#[derive(Debug)]
pub enum CommitActivityStatus {
    /// The commit is active, and should be rendered as part of the commit graph.
    Active,

    /// No history has been observed for this commit, so it's inactive, and
    /// should not be rendered as part of the commit graph (unless a descendant
    /// commit is visible).
    Inactive,

    /// The commit has been obsoleted by a user event (rewriting or an explicit
    /// request to obsolete the commit), and should be hidden from the commit
    /// graph (unless a descendant commit is visible).
    Obsolete,
}

#[derive(Debug)]
struct EventInfo {
    id: isize,
    event: Event,
    event_classification: EventClassification,
}

/// Events up to this cursor (exclusive) are available to the caller.
///
/// The "event cursor" is used to move the event replayer forward or
/// backward in time, so as to show the state of the repository at that
/// time.
///
/// The cursor is a position in between two events in the event log.
/// Thus, all events before to the cursor are considered to be in effect,
/// and all events after the cursor are considered to not have happened
/// yet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EventCursor {
    event_id: isize,
}

/// Processes events in order and determine the repo's visible commits.
pub struct EventReplayer {
    /// Events are numbered starting from zero.
    id_counter: isize,

    /// The list of observed events.
    events: Vec<Event>,

    /// The name of the reference representing the main branch.
    main_branch_reference_name: ReferenceName,

    /// The events that have affected each commit.
    commit_history: HashMap<NonZeroOid, Vec<EventInfo>>,

    /// Map from ref names to ref locations (an OID or another ref name). Works
    /// around <https://github.com/arxanas/git-branchless/issues/7>.
    ///
    /// If an entry is not present, it was either never observed, or it most
    /// recently changed to point to the zero hash (i.e. it was deleted).
    ref_locations: HashMap<ReferenceName, NonZeroOid>,
}

impl std::fmt::Debug for EventReplayer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "<EventReplayer events.len={:?} ref_locations.len={:?}>",
            self.events.len(),
            self.ref_locations.len()
        )
    }
}

impl EventReplayer {
    fn new(main_branch_reference_name: ReferenceName) -> Self {
        EventReplayer {
            id_counter: 0,
            events: vec![],
            main_branch_reference_name,
            commit_history: HashMap::new(),
            ref_locations: HashMap::new(),
        }
    }

    /// Construct the replayer from all the events in the database.
    ///
    /// Args:
    /// * `event_log_db`: The database to query events from.
    ///
    /// Returns: The constructed replayer.
    pub fn from_event_log_db(
        effects: &Effects,
        repo: &Repo,
        event_log_db: &EventLogDb,
    ) -> eyre::Result<Self> {
        let (_effects, _progress) = effects.start_operation(OperationType::ProcessEvents);

        let main_branch_reference_name = repo.get_main_branch()?.get_reference_name()?;
        let mut result = EventReplayer::new(main_branch_reference_name);
        for event in event_log_db.get_events()? {
            result.process_event(&event);
        }
        Ok(result)
    }

    /// Process the given event.
    ///
    /// This also sets the event cursor to point to immediately after the event
    /// that was just processed.
    ///
    /// Args:
    /// * `event`: The next event to process. Events should be passed to the
    /// * `replayer` in order from oldest to newest.
    pub fn process_event(&mut self, event: &Event) {
        // Drop non-meaningful ref-update events.
        if let Event::RefUpdateEvent { ref_name, .. } = event {
            if should_ignore_ref_updates(ref_name) {
                return;
            }
        }

        let event = match self.fix_event_git_v2_31(event.clone()) {
            None => {
                return;
            }
            Some(event) => {
                self.events.push(event);
                self.events.last().unwrap()
            }
        };
        let id = self.id_counter;
        self.id_counter += 1;

        match &event {
            Event::RewriteEvent {
                timestamp: _,
                event_tx_id: _,
                old_commit_oid,
                new_commit_oid,
            } => {
                if let MaybeZeroOid::NonZero(old_commit_oid) = old_commit_oid {
                    self.commit_history
                        .entry(*old_commit_oid)
                        .or_insert_with(Vec::new)
                        .push(EventInfo {
                            id,
                            event: event.clone(),
                            event_classification: EventClassification::Hide,
                        });
                }
                if let MaybeZeroOid::NonZero(new_commit_oid) = new_commit_oid {
                    self.commit_history
                        .entry(*new_commit_oid)
                        .or_insert_with(Vec::new)
                        .push(EventInfo {
                            id,
                            event: event.clone(),
                            event_classification: EventClassification::Show,
                        });
                }
            }

            // A reference update doesn't indicate a change to a commit, so we
            // don't include it in the `commit_history`. We'll traverse the
            // history later to find historical locations of references when
            // needed.
            Event::RefUpdateEvent {
                ref_name, new_oid, ..
            } => match new_oid {
                MaybeZeroOid::NonZero(new_oid) => {
                    self.ref_locations.insert(ref_name.clone(), *new_oid);
                }
                MaybeZeroOid::Zero => {
                    self.ref_locations.remove(ref_name);
                }
            },

            Event::CommitEvent {
                timestamp: _,
                event_tx_id: _,
                commit_oid,
            } => self
                .commit_history
                .entry(*commit_oid)
                .or_insert_with(Vec::new)
                .push(EventInfo {
                    id,
                    event: event.clone(),
                    event_classification: EventClassification::Show,
                }),

            Event::ObsoleteEvent {
                timestamp: _,
                event_tx_id: _,
                commit_oid,
            } => self
                .commit_history
                .entry(*commit_oid)
                .or_insert_with(Vec::new)
                .push(EventInfo {
                    id,
                    event: event.clone(),
                    event_classification: EventClassification::Hide,
                }),

            Event::UnobsoleteEvent {
                timestamp: _,
                event_tx_id: _,
                commit_oid,
            } => self
                .commit_history
                .entry(*commit_oid)
                .or_insert_with(Vec::new)
                .push(EventInfo {
                    id,
                    event: event.clone(),
                    event_classification: EventClassification::Show,
                }),

            Event::WorkingCopySnapshot { .. } => {
                // Do nothing. A working copy snapshot doesn't imply that the
                // commit has become active or inactive.
            }
        };
    }

    /// See https://github.com/arxanas/git-branchless/issues/7.
    fn fix_event_git_v2_31(&self, event: Event) -> Option<Event> {
        let event = match event {
            // Git v2.31 will sometimes fail to set the `old_ref` field when
            // deleting refs. This means that undoing the operation later
            // becomes incorrect, as we just swap the `old_ref` and `new_ref`
            // values.
            Event::RefUpdateEvent {
                timestamp,
                event_tx_id,
                ref_name,
                old_oid: MaybeZeroOid::Zero,
                new_oid: MaybeZeroOid::Zero,
                message,
            } => {
                let old_oid: MaybeZeroOid = self.ref_locations.get(&ref_name).copied().into();
                Event::RefUpdateEvent {
                    timestamp,
                    event_tx_id,
                    ref_name,
                    old_oid,
                    new_oid: MaybeZeroOid::Zero,
                    message,
                }
            }

            _ => event,
        };

        match (event, self.events.last()) {
            // Sometimes, Git v2.31 will issue multiple delete reference
            // transactions (one for the unpacked refs, and one for the packed
            // refs). Ignore the duplicate second one, for determinism in
            // testing. See https://lore.kernel.org/git/YFMCLSdImkW3B1rM@ncase/
            // for more details.
            (
                Event::RefUpdateEvent {
                    timestamp: _,
                    event_tx_id: _,
                    ref ref_name,
                    old_oid: _,
                    new_oid: MaybeZeroOid::Zero,
                    ref message,
                },
                Some(Event::RefUpdateEvent {
                    timestamp: _,
                    event_tx_id: _,
                    ref_name: last_ref_name,
                    old_oid: _,
                    new_oid: MaybeZeroOid::Zero,
                    message: last_message,
                }),
            ) if ref_name == last_ref_name && message == last_message => None,

            (event, _) => Some(event),
        }
    }

    fn get_cursor_commit_history(&self, cursor: EventCursor, oid: NonZeroOid) -> Vec<&EventInfo> {
        match self.commit_history.get(&oid) {
            None => vec![],
            Some(history) => history
                .iter()
                .filter(|event_info| event_info.id < cursor.event_id)
                .collect(),
        }
    }

    /// Determines whether a commit is considered "active" at the cursor's point
    /// in time.
    pub fn get_cursor_commit_activity_status(
        &self,
        cursor: EventCursor,
        oid: NonZeroOid,
    ) -> CommitActivityStatus {
        let history = self.get_cursor_commit_history(cursor, oid);
        match history.last() {
            Some(EventInfo {
                id: _,
                event: _,
                event_classification: EventClassification::Show,
            }) => CommitActivityStatus::Active,

            Some(EventInfo {
                id: _,
                event: _,
                event_classification: EventClassification::Hide,
            }) => CommitActivityStatus::Obsolete,

            None => CommitActivityStatus::Inactive,
        }
    }

    /// Get the latest event affecting a given commit, as of the cursor's point
    /// in time.
    ///
    /// Args:
    /// * `oid`: The OID of the commit to check.
    ///
    /// Returns: The most recent event that affected that commit. If this commit
    /// was not observed by the replayer, returns `None`.
    pub fn get_cursor_commit_latest_event(
        &self,
        cursor: EventCursor,
        oid: NonZeroOid,
    ) -> Option<&Event> {
        let history = self.get_cursor_commit_history(cursor, oid);
        let event_info = *history.last()?;
        Some(&event_info.event)
    }

    /// Get all OIDs which have been observed so far. This should be the set of
    /// non-inactive commits.
    pub fn get_cursor_oids(&self, cursor: EventCursor) -> HashSet<NonZeroOid> {
        self.commit_history
            .iter()
            .filter_map(|(oid, history)| {
                if history.iter().any(|event| event.id < cursor.event_id) {
                    Some(*oid)
                } else {
                    None
                }
            })
            .collect()
    }

    /// Create an event cursor pointing to immediately after the last event.
    pub fn make_default_cursor(&self) -> EventCursor {
        self.make_cursor(self.events.len().try_into().unwrap())
    }

    /// Create an event cursor pointing to immediately after the provided event ID.
    ///
    /// If the event ID is too low or too high, it will be clamped to the valid
    /// range for event IDs.
    pub fn make_cursor(&self, event_id: isize) -> EventCursor {
        let event_id = if event_id < 0 { 0 } else { event_id };
        let num_events: isize = self.events.len().try_into().unwrap();
        let event_id = if event_id > num_events {
            num_events
        } else {
            event_id
        };
        EventCursor { event_id }
    }

    /// Advance the event cursor by the specified number of events.
    ///
    /// Args:
    /// * `num_events`: The number of events to advance by. Can be positive,
    /// zero, or negative. If out of bounds, the cursor is set to the first or
    /// last valid position, as appropriate.
    pub fn advance_cursor(&self, cursor: EventCursor, num_events: isize) -> EventCursor {
        self.make_cursor(cursor.event_id + num_events)
    }

    fn get_event_tx_id_before_cursor(&self, cursor: EventCursor) -> Option<EventTransactionId> {
        self.get_event_before_cursor(cursor)
            .map(|(_event_id, event)| event.get_event_tx_id())
    }

    /// The event cursor may not be between two events with different transaction
    /// IDs (that is, it may not be perfectly in between transactions). Move the
    /// cursor forward until it is at the boundary of two transactions
    fn snap_to_transaction_boundary(&self, cursor: EventCursor) -> EventCursor {
        let next_cursor = self.advance_cursor(cursor, 1);
        if cursor == next_cursor {
            return cursor;
        }
        let current_tx_id = self.get_event_tx_id_before_cursor(cursor);
        let next_tx_id = self.get_event_tx_id_before_cursor(next_cursor);
        if current_tx_id == next_tx_id {
            self.snap_to_transaction_boundary(next_cursor)
        } else {
            cursor
        }
    }

    fn advance_cursor_by_transaction_helper(
        &self,
        cursor: EventCursor,
        num_transactions: isize,
    ) -> EventCursor {
        match num_transactions.cmp(&0) {
            Ordering::Equal => self.snap_to_transaction_boundary(cursor),
            Ordering::Greater => {
                let next_cursor = self.advance_cursor(cursor, 1);
                if cursor == next_cursor {
                    return next_cursor;
                }
                let current_tx_id = self.get_event_tx_id_before_cursor(cursor);
                let next_tx_id = self.get_event_tx_id_before_cursor(next_cursor);
                let num_transactions = if current_tx_id == next_tx_id {
                    num_transactions
                } else {
                    num_transactions - 1
                };
                self.advance_cursor_by_transaction_helper(next_cursor, num_transactions)
            }
            Ordering::Less => {
                let prev_cursor = self.advance_cursor(cursor, -1);
                if cursor == prev_cursor {
                    return prev_cursor;
                }
                let current_tx_id = self.get_event_tx_id_before_cursor(cursor);
                let prev_tx_id = self.get_event_tx_id_before_cursor(prev_cursor);
                let num_transactions = if current_tx_id == prev_tx_id {
                    num_transactions
                } else {
                    num_transactions + 1
                };
                self.advance_cursor_by_transaction_helper(prev_cursor, num_transactions)
            }
        }
    }

    /// Advance the cursor to the transaction which is `num_transactions` after
    /// the current cursor. `num_transactions` can be negative.
    ///
    /// The returned cursor will point to the position immediately after the last
    /// event in the subsequent transaction.
    pub fn advance_cursor_by_transaction(
        &self,
        cursor: EventCursor,
        num_transactions: isize,
    ) -> EventCursor {
        if self.events.is_empty() {
            cursor
        } else {
            let cursor = self.snap_to_transaction_boundary(cursor);
            self.advance_cursor_by_transaction_helper(cursor, num_transactions)
        }
    }

    /// Get the OID of `HEAD` at the cursor's point in time.
    ///
    /// Returns: The OID pointed to by `HEAD` at that time, or `None` if `HEAD`
    /// was never observed.
    fn get_cursor_head_oid(&self, cursor: EventCursor) -> Option<NonZeroOid> {
        let cursor_event_id: usize = cursor.event_id.try_into().unwrap();
        self.events[0..cursor_event_id]
            .iter()
            .rev()
            .find_map(|event| {
                match &event {
                    Event::RefUpdateEvent {
                        ref_name,
                        new_oid: MaybeZeroOid::NonZero(new_oid),
                        ..
                    } if ref_name.as_str() == "HEAD" => Some(*new_oid),
                    Event::RefUpdateEvent { .. } => None,

                    // Not strictly necessary, but helps to compensate in case
                    // the user is not running Git v2.29 or above, and therefore
                    // doesn't have the corresponding `RefUpdateEvent`.
                    Event::CommitEvent { commit_oid, .. } => Some(*commit_oid),

                    Event::WorkingCopySnapshot {
                        head_oid: MaybeZeroOid::NonZero(head_oid),
                        ..
                    } => Some(*head_oid),
                    Event::WorkingCopySnapshot {
                        head_oid: MaybeZeroOid::Zero,
                        ..
                    } => None,

                    Event::RewriteEvent { .. }
                    | Event::ObsoleteEvent { .. }
                    | Event::UnobsoleteEvent { .. } => None,
                }
            })
    }

    fn get_cursor_branch_oid(
        &self,
        cursor: EventCursor,
        reference_name: &ReferenceName,
    ) -> eyre::Result<Option<NonZeroOid>> {
        let cursor_event_id: usize = cursor.event_id.try_into().unwrap();
        let oid = self.events[0..cursor_event_id]
            .iter()
            .rev()
            .find_map(|event| match &event {
                Event::RefUpdateEvent {
                    ref_name,
                    new_oid: MaybeZeroOid::NonZero(new_oid),
                    ..
                } if ref_name == reference_name => Some(*new_oid),
                _ => None,
            });
        Ok(oid)
    }

    /// Get the OID of the main branch at the cursor's point in time.
    ///
    /// Note that this doesn't handle the case of the user having changed their
    /// main branch configuration. That is, if it was previously `master`, and
    /// then changed to `main`, we will show only the historical locations of
    /// `main`, and never `master`.
    ///
    /// Args:
    /// * `repo`: The Git repository.
    ///
    /// Returns: A mapping from an OID to the names of branches pointing to that
    /// OID.
    fn get_cursor_main_branch_oid(
        &self,
        cursor: EventCursor,
        repo: &Repo,
    ) -> eyre::Result<NonZeroOid> {
        let main_branch_reference_name = repo.get_main_branch()?.get_reference_name()?;
        let main_branch_oid = self.get_cursor_branch_oid(cursor, &main_branch_reference_name)?;
        match main_branch_oid {
            Some(main_branch_oid) => Ok(main_branch_oid),
            None => {
                // Assume the main branch just hasn't been observed moving yet,
                // so its value at the current time is fine to use.
                repo.get_main_branch_oid()
            }
        }
    }

    /// Get the mapping of branch OIDs to names at the cursor's point in
    /// time.
    ///
    /// Same as `get_branch_oid_to_names`, but for a previous point in time.
    ///
    /// Args:
    /// * `repo`: The Git repository.
    ///
    /// Returns: A mapping from an OID to the names of branches pointing to that
    /// OID.
    fn get_cursor_branch_oid_to_names(
        &self,
        cursor: EventCursor,
        repo: &Repo,
    ) -> eyre::Result<HashMap<NonZeroOid, HashSet<ReferenceName>>> {
        let mut ref_name_to_oid: HashMap<&ReferenceName, NonZeroOid> = HashMap::new();
        let cursor_event_id: usize = cursor.event_id.try_into().unwrap();
        for event in self.events[..cursor_event_id].iter() {
            match event {
                Event::RefUpdateEvent {
                    new_oid: MaybeZeroOid::NonZero(new_oid),
                    ref_name,
                    ..
                } => {
                    ref_name_to_oid.insert(ref_name, *new_oid);
                }
                Event::RefUpdateEvent {
                    new_oid: MaybeZeroOid::Zero,
                    ref_name,
                    ..
                } => {
                    ref_name_to_oid.remove(ref_name);
                }
                _ => {}
            }
        }

        let mut result: HashMap<NonZeroOid, HashSet<ReferenceName>> = HashMap::new();
        for (ref_name, ref_oid) in ref_name_to_oid.iter() {
            if let CategorizedReferenceName::LocalBranch { .. } =
                CategorizedReferenceName::new(ref_name)
            {
                result
                    .entry(*ref_oid)
                    .or_insert_with(HashSet::new)
                    .insert((*ref_name).clone());
            }
        }

        let main_branch_oid = self.get_cursor_main_branch_oid(cursor, repo)?;
        result
            .entry(main_branch_oid)
            .or_insert_with(HashSet::new)
            .insert(self.main_branch_reference_name.clone());
        Ok(result)
    }

    /// Get the `RepoReferencesSnapshot` at the cursor's point in time.
    pub fn get_references_snapshot(
        &self,
        repo: &Repo,
        cursor: EventCursor,
    ) -> eyre::Result<RepoReferencesSnapshot> {
        let head_oid = self.get_cursor_head_oid(cursor);
        let main_branch_oid = self.get_cursor_main_branch_oid(cursor, repo)?;
        let branch_oid_to_names = self.get_cursor_branch_oid_to_names(cursor, repo)?;
        Ok(RepoReferencesSnapshot {
            head_oid,
            main_branch_oid,
            branch_oid_to_names,
        })
    }

    /// Get the event immediately before the cursor.
    ///
    /// Returns: A tuple of event ID and the event that most recently happened.
    /// If no event was before the event cursor, returns `None` instead.
    pub fn get_event_before_cursor(&self, cursor: EventCursor) -> Option<(isize, &Event)> {
        if cursor.event_id == 0 {
            None
        } else {
            let previous_cursor_event_id: usize = (cursor.event_id - 1).try_into().unwrap();
            Some((cursor.event_id, &self.events[previous_cursor_event_id]))
        }
    }

    /// Get all the events in the transaction immediately before the cursor.
    ///
    /// Returns: A tuple of event ID and the events that happened in the most
    /// recent transaction. The event ID corresponds to the ID of the first event
    /// in the returned list of events. If there were no events before the event
    /// cursor (and therefore no transactions), returns `None` instead.
    pub fn get_tx_events_before_cursor(&self, cursor: EventCursor) -> Option<(isize, &[Event])> {
        let prev_tx_cursor = self.advance_cursor_by_transaction(cursor, -1);
        let EventCursor {
            event_id: prev_event_id,
        } = prev_tx_cursor;
        let EventCursor {
            event_id: curr_event_id,
        } = cursor;
        let tx_events =
            &self.events[prev_event_id.try_into().unwrap()..curr_event_id.try_into().unwrap()];
        match tx_events {
            [] => None,
            events => Some((prev_event_id + 1, events)),
        }
    }

    /// Get all the events that have happened since the event cursor.
    ///
    /// Returns: An ordered list of events that have happened since the event
    /// cursor, from least recent to most recent.
    pub fn get_events_since_cursor(&self, cursor: EventCursor) -> &[Event] {
        let cursor_event_id: usize = cursor.event_id.try_into().unwrap();
        &self.events[cursor_event_id..]
    }
}

/// Testing helpers.
pub mod testing {
    use super::*;

    /// Make a dummy transaction ID, for testing.
    pub fn make_dummy_transaction_id(id: isize) -> EventTransactionId {
        EventTransactionId(id)
    }

    /// Remove the timestamp for the event, for determinism in testing.
    pub fn redact_event_timestamp(mut event: Event) -> Event {
        match event {
            Event::RewriteEvent {
                ref mut timestamp, ..
            }
            | Event::RefUpdateEvent {
                ref mut timestamp, ..
            }
            | Event::CommitEvent {
                ref mut timestamp, ..
            }
            | Event::ObsoleteEvent {
                ref mut timestamp, ..
            }
            | Event::UnobsoleteEvent {
                ref mut timestamp, ..
            }
            | Event::WorkingCopySnapshot {
                ref mut timestamp, ..
            } => *timestamp = 0.0,
        }
        event
    }

    /// Get the events stored inside an `EventReplayer`.
    pub fn get_event_replayer_events(event_replayer: &EventReplayer) -> &Vec<Event> {
        &event_replayer.events
    }
}

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

    use crate::testing::make_git;
    use testing::make_dummy_transaction_id;

    #[test]
    fn test_drop_non_meaningful_events() -> eyre::Result<()> {
        let event_tx_id = make_dummy_transaction_id(123);
        let meaningful_event = Event::CommitEvent {
            timestamp: 0.0,
            event_tx_id,
            commit_oid: NonZeroOid::from_str("abc")?,
        };
        let mut replayer = EventReplayer::new("refs/heads/master".into());
        replayer.process_event(&meaningful_event);
        replayer.process_event(&Event::RefUpdateEvent {
            timestamp: 0.0,
            event_tx_id,
            ref_name: ReferenceName::from("ORIG_HEAD"),
            old_oid: MaybeZeroOid::from_str("abc")?,
            new_oid: MaybeZeroOid::from_str("def")?,
            message: None,
        });
        replayer.process_event(&Event::RefUpdateEvent {
            timestamp: 0.0,
            event_tx_id,
            ref_name: ReferenceName::from("CHERRY_PICK_HEAD"),
            old_oid: MaybeZeroOid::Zero,
            new_oid: MaybeZeroOid::Zero,
            message: None,
        });

        let cursor = replayer.make_default_cursor();
        assert_eq!(
            replayer.get_event_before_cursor(cursor),
            Some((1, &meaningful_event))
        );
        Ok(())
    }

    #[test]
    fn test_different_event_transaction_ids() -> eyre::Result<()> {
        let git = make_git()?;

        git.init_repo()?;
        git.commit_file("test1", 1)?;
        git.run(&["hide", "HEAD"])?;

        let repo = git.get_repo()?;
        let conn = repo.get_db_conn()?;
        let event_log_db = EventLogDb::new(&conn)?;
        let events = event_log_db.get_events()?;
        let event_tx_ids: Vec<EventTransactionId> =
            events.iter().map(|event| event.get_event_tx_id()).collect();
        if git.supports_reference_transactions()? {
            insta::assert_debug_snapshot!(event_tx_ids, @r###"
                [
                    EventTransactionId(
                        1,
                    ),
                    EventTransactionId(
                        1,
                    ),
                    EventTransactionId(
                        2,
                    ),
                    EventTransactionId(
                        3,
                    ),
                ]
                "###);
        } else {
            insta::assert_debug_snapshot!(event_tx_ids, @r###"
                [
                    EventTransactionId(
                        1,
                    ),
                    EventTransactionId(
                        2,
                    ),
                ]
                "###);
        }
        Ok(())
    }

    #[test]
    fn test_advance_cursor_by_transaction() -> eyre::Result<()> {
        let mut event_replayer = EventReplayer::new("refs/heads/master".into());
        for (timestamp, event_tx_id) in (0..).zip(&[1, 1, 2, 2, 3, 4]) {
            let timestamp: f64 = timestamp.try_into()?;
            event_replayer.process_event(&Event::UnobsoleteEvent {
                timestamp,
                event_tx_id: EventTransactionId(*event_tx_id),
                commit_oid: NonZeroOid::from_str("abc")?,
            });
        }

        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 0 }, 1),
            EventCursor { event_id: 2 },
        );
        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 1 }, 1),
            EventCursor { event_id: 4 },
        );
        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 2 }, 1),
            EventCursor { event_id: 4 },
        );
        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 3 }, 1),
            EventCursor { event_id: 5 },
        );
        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 4 }, 1),
            EventCursor { event_id: 5 },
        );
        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 5 }, 1),
            EventCursor { event_id: 6 },
        );
        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 6 }, 1),
            EventCursor { event_id: 6 },
        );

        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 6 }, -1),
            EventCursor { event_id: 5 },
        );
        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 5 }, -1),
            EventCursor { event_id: 4 },
        );
        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 4 }, -1),
            EventCursor { event_id: 2 },
        );
        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 3 }, -1),
            EventCursor { event_id: 2 },
        );
        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 2 }, -1),
            EventCursor { event_id: 0 },
        );
        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 1 }, -1),
            EventCursor { event_id: 0 },
        );
        assert_eq!(
            event_replayer.advance_cursor_by_transaction(EventCursor { event_id: 0 }, -1),
            EventCursor { event_id: 0 },
        );

        Ok(())
    }
}