girt 0.11.0

An incremental, idiomatic Rust implementation of Git
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
#![warn(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::unreachable,
    clippy::indexing_slicing,
    reason = "parses untrusted repository or network input (#103)"
)]
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};

use thiserror::Error;

use super::{Entry, Error, Index, Limits, Timestamp};
use crate::{ObjectFormat, Repository};

/// Prepublication policy for an index lock file.
///
/// Defaults preserve ordinary umask behavior and do not synchronize. Synchronization uses macOS
/// full file flush or `File::sync_all` elsewhere; directory entries are not synchronized.
///
/// Pass these options to [`IndexEdit::commit_with_options`].
///
/// ```
/// use girt::index::IndexCommitOptions;
/// let options = IndexCommitOptions::default().with_sync(true);
/// assert!(options.sync);
/// // This flushes the file, not its parent directory.
/// ```
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct IndexCommitOptions {
    /// Permissions applied to the owned lock before publication.
    pub shared_permissions: crate::SharedPermissions,
    /// Synchronize the complete lock file before its final snapshot checks and rename.
    pub sync: bool,
}

impl IndexCommitOptions {
    /// Sets [`Self::shared_permissions`].
    #[must_use]
    pub fn with_shared_permissions(mut self, shared_permissions: crate::SharedPermissions) -> Self {
        self.shared_permissions = shared_permissions;
        self
    }

    /// Sets [`Self::sync`].
    #[must_use]
    pub fn with_sync(mut self, sync: bool) -> Self {
        self.sync = sync;
        self
    }
}

/// Explicit storage admission for a caller-selected index edit.
///
/// Defaults retain standalone, regular-file-only admission. These options do not select an index
/// from environment or configuration, authorize directory replacement, or bypass snapshot checks.
///
/// ```
/// # #[cfg(unix)]
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use girt::index::{EditOptions, Version};
/// use girt::{InitKind, ObjectFormat, Repository};
/// let directory = tempfile::tempdir()?;
/// let repo = Repository::init(
///     ObjectFormat::Sha1,
///     directory.path().join("r"),
///     InitKind::Worktree,
/// )?;
/// let original = directory.path().join("original.index");
/// repo.edit_index_at(&original, Default::default())?
///     .commit()?;
/// let original_bytes = std::fs::read(&original)?;
/// let selected = directory.path().join("selected.index");
/// std::os::unix::fs::symlink(&original, &selected)?;
/// assert!(repo.edit_index_at(&selected, Default::default()).is_err());
/// let options = EditOptions::default().with_follow_symlink(true);
/// let mut edit = repo.edit_index_at_with_options(&selected, Default::default(), options)?;
/// edit.set_version(Version::V4)?;
/// edit.commit()?;
/// assert!(
///     !std::fs::symlink_metadata(&selected)?
///         .file_type()
///         .is_symlink()
/// );
/// assert_eq!(std::fs::read(&original)?, original_bytes);
/// assert_eq!(
///     repo.read_index_at(&selected, Default::default())?
///         .unwrap()
///         .version(),
///     Version::V4
/// );
/// # Ok(())
/// # }
/// # #[cfg(not(unix))]
/// # fn main() {}
/// ```
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct EditOptions {
    /// Resolve immutable split dependencies beside the selected lexical index path.
    pub resolve_split: bool,
    /// Read through a final symlink, then replace that selected leaf on publication.
    ///
    /// The referent is never written. The original leaf kind, symlink spelling, followed bytes
    /// and presence remain publication preconditions; Unix also checks the captured leaf inode.
    pub follow_symlink: bool,
}

impl EditOptions {
    /// Sets [`Self::resolve_split`].
    #[must_use]
    pub fn with_resolve_split(mut self, resolve_split: bool) -> Self {
        self.resolve_split = resolve_split;
        self
    }

    /// Sets [`Self::follow_symlink`].
    #[must_use]
    pub fn with_follow_symlink(mut self, follow_symlink: bool) -> Self {
        self.follow_symlink = follow_symlink;
        self
    }
}

#[derive(Debug)]
struct LeafSnapshot {
    metadata: Option<fs::Metadata>,
    target: Option<PathBuf>,
}

impl LeafSnapshot {
    fn read(path: &Path) -> Result<Self, StorageError> {
        let metadata = match fs::symlink_metadata(path) {
            Ok(metadata) => Some(metadata),
            Err(error) if error.kind() == io::ErrorKind::NotFound => None,
            Err(error) => return Err(io_error("inspect index leaf", path, error)),
        };
        let target = if metadata.as_ref().is_some_and(|value| value.is_symlink()) {
            Some(fs::read_link(path).map_err(|error| io_error("read index symlink", path, error))?)
        } else {
            None
        };
        Ok(Self { metadata, target })
    }

    fn check(&self, path: &Path) -> Result<(), StorageError> {
        let current = Self::read(path)?;
        let unchanged = match (&self.metadata, &current.metadata) {
            (None, None) => true,
            (Some(before), Some(after)) => {
                let same_kind = before.file_type() == after.file_type();
                #[cfg(unix)]
                {
                    use std::os::unix::fs::MetadataExt;
                    same_kind && before.dev() == after.dev() && before.ino() == after.ino()
                }
                #[cfg(not(unix))]
                {
                    same_kind
                }
            }
            _ => false,
        };
        if !unchanged || self.target != current.target {
            return Err(StorageError::Changed(path.into()));
        }
        Ok(())
    }
}

/// An exclusive `index.lock` held from snapshot read through publication or drop.
///
/// Obtain with [`Repository::edit_index`], [`Repository::edit_index_at`] or
/// [`Repository::edit_index_at_with_options`], derive edits from
/// [`Self::index`], and call [`Self::replace_entries`] then [`Self::commit`]. Missing storage
/// starts as an empty index. Dropping without committing abandons the edit and removes only the
/// acquired lock. Existing locks are never stolen. Drop performs blocking, best-effort filesystem
/// cleanup; a cleanup
/// failure can leave the owned lock for manual removal. [`Self::abort`] explicitly reports cleanup
/// errors; failed reads and commits retain both operation and cleanup causes. Unix
/// cleanup/publication rechecks the acquired lock inode, refusing an observed replacement.
/// Processes must honor Git's lock protocol; arbitrary directory, symlink or lock replacement is
/// outside this contract.
///
/// Publication uses a same-directory rename, with atomic replacement where the host filesystem
/// supports it. Default [`Self::commit`] uses ordinary OS creation modes and umask, without file
/// synchronization. [`Self::commit_with_options`] can adjust the lock's shared permissions and
/// synchronize it before rename, using full file flush on macOS or `File::sync_all` elsewhere.
/// Directory entries are not synchronized; no crash or power-loss durability is promised. No
/// worktree files or objects are written. Index storage does not depend on the reference backend.
///
/// # Synchronize the file before releasing the lock
///
/// Batch path changes into one edit: opening reads the whole index and committing encodes the
/// complete file. Separate edits for each of many paths repeatedly do that work. The
/// [`Repository::edit_index`] example stages a blob; this example selects file synchronization.
///
/// ```
/// use girt::index::IndexCommitOptions;
/// use girt::{InitKind, ObjectFormat, Repository};
/// let directory = tempfile::tempdir()?;
/// let repository = Repository::init(
///     ObjectFormat::Sha1,
///     directory.path().join("repo"),
///     InitKind::Worktree,
/// )?;
/// let edit = repository.edit_index(Default::default())?;
/// edit.commit_with_options(IndexCommitOptions::default().with_sync(true))?;
/// assert!(repository.read_index(Default::default())?.is_some());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
pub struct IndexEdit {
    destination: PathBuf,
    lock_path: PathBuf,
    file: Option<crate::locks::SharedFile>,
    original: Option<Vec<u8>>,
    leaf: Option<LeafSnapshot>,
    shared: Option<(PathBuf, Vec<u8>)>,
    lock_identity: fs::Metadata,
    cleanup: crate::locks::Guard,
    index: Index,
    limits: Limits,
    published: bool,
}

/// Synchronous index storage failure, retaining path and underlying causes.
///
/// Treat [`StorageError::Locked`] as contention or a recovery task; never delete a lock just
/// because this call could not acquire it. [`StorageError::Changed`] requires a fresh locked
/// snapshot. Inspect both causes of [`StorageError::Cleanup`], and distinguish
/// [`StorageError::PublishedCleanup`], where publication already succeeded, before retrying.
///
/// ```
/// use girt::{InitKind, ObjectFormat, Repository};
/// let directory = tempfile::tempdir()?;
/// let repository = Repository::init(
///     ObjectFormat::Sha1,
///     directory.path().join("repo"),
///     InitKind::Worktree,
/// )?;
///
/// use girt::index::StorageError;
/// let edit = repository.edit_index(Default::default())?;
/// assert!(matches!(
///     repository.edit_index(Default::default()),
///     Err(StorageError::Locked(_))
/// ));
/// edit.abort()?; // Explicit abort reports cleanup failure; Drop can only make a best effort.
///
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum StorageError {
    /// The operation failed and its owned lock could not be removed. Both causes are retained;
    /// the cleanup cause identifies the lock requiring manual recovery.
    #[error("operation failed and lock cleanup also failed: {cleanup}")]
    Cleanup {
        /// Primary failure.
        #[source]
        operation: Box<StorageError>,
        /// Failed removal of the acquired lock.
        cleanup: Box<StorageError>,
    },
    /// Read, lock write, metadata update or rename failed. Original index bytes are unchanged
    /// by a failed publication; a concurrent writer's changes are never rolled back.
    #[error("cannot {operation} {path}")]
    Io {
        /// Operation that failed.
        operation: &'static str,
        /// Affected filesystem path.
        path: PathBuf,
        /// Original OS error.
        #[source]
        source: io::Error,
    },
    /// An existing lock belongs to another writer or requires explicit stale-lock recovery.
    #[error("index lock already exists: {0}")]
    Locked(PathBuf),
    /// Original index bytes or presence changed despite the held lock.
    #[error("index changed while locked: {0}")]
    Changed(PathBuf),
    /// The required immutable shared file is absent. Restore it before retrying.
    #[error("missing shared index: {0}")]
    MissingShared(PathBuf),
    /// The destination is a symlink, directory or other non-regular file.
    #[error("index is not a regular file: {0}")]
    NotRegular(PathBuf),
    /// Format or limit validation failed before publication.
    #[error("invalid index at {path}")]
    Format {
        /// Index destination path.
        path: PathBuf,
        /// Underlying parser/encoder error.
        #[source]
        source: Error,
    },
    /// The new index was published, but its owned lock could not be removed.
    #[error("new index published at {path}, but cannot remove owned lock {lock}")]
    PublishedCleanup {
        /// Published index path.
        path: PathBuf,
        /// Owned lock requiring manual cleanup.
        lock: PathBuf,
        /// Original OS error.
        #[source]
        source: io::Error,
    },
}

impl Repository {
    /// Reads this worktree's `git_dir()/index`, returning `None` when missing.
    ///
    /// An existing empty index is `Some(Index)` with zero entries. Bare and separate-gitdir
    /// repositories use their Git directory; linked worktrees use the per-worktree directory,
    /// with split dependencies resolved beside that index. Environment/config index-path overrides
    /// are not consulted. The returned read-only snapshot has no authority to replace a later
    /// index; start an [`Self::edit_index`] lifecycle before deriving changes that will be
    /// published.
    ///
    /// # Errors
    ///
    /// Returns contextual I/O, non-regular-file, format and limit errors. Reads are bounded and
    /// synchronous; nothing is written. Split dependencies share the aggregate byte budget.
    /// Concurrent cooperating writers publish whole files by rename. In-place writes by
    /// noncooperating processes may instead produce a parse error.
    ///
    /// An absent index and a published empty index are distinct observations:
    ///
    /// ```
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let repository = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("repo"),
    ///     InitKind::Worktree,
    /// )?;
    ///
    /// assert!(repository.read_index(Default::default())?.is_none());
    /// repository.edit_index(Default::default())?.commit()?;
    /// assert!(
    ///     repository
    ///         .read_index(Default::default())?
    ///         .unwrap()
    ///         .entries()
    ///         .is_empty()
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn read_index(&self, limits: Limits) -> Result<Option<Index>, StorageError> {
        self.read_index_path(self.git_dir().join("index"), limits, true)
    }

    /// Reads a caller-selected standalone index, returning `None` when absent.
    ///
    /// Relative paths resolve once against the process current directory, not the Git directory.
    /// No environment or configuration override is read. Symlink ancestors retain their spelling;
    /// the final component must be a regular file. Unlike Git, this API rejects leaf symlinks.
    /// The repository selects the object format. No other index path is read or changed.
    ///
    /// # Errors
    ///
    /// Returns [`Self::read_index`]'s bounded I/O, format and non-regular-file errors. Split `link`
    /// extensions are rejected as [`Error::MandatoryExtension`] without reading a shared file,
    /// even when `path` names the default index. Nothing is written.
    ///
    /// # Inspect a temporary index independently of the worktree index
    ///
    /// ```
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("r"),
    ///     InitKind::Worktree,
    /// )?;
    ///
    /// let path = directory.path().join("preview.index");
    /// repo.edit_index_at(&path, Default::default())?.commit()?;
    /// assert!(repo.read_index_at(&path, Default::default())?.is_some());
    /// assert!(repo.read_index(Default::default())?.is_none());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn read_index_at(
        &self,
        path: impl AsRef<Path>,
        limits: Limits,
    ) -> Result<Option<Index>, StorageError> {
        let path = absolute_index_path(path.as_ref())?;
        self.read_index_path(path, limits, false)
    }

    fn read_index_path(
        &self,
        path: PathBuf,
        limits: Limits,
        resolve_split: bool,
    ) -> Result<Option<Index>, StorageError> {
        #[cfg(feature = "tracing")]
        let span = tracing::debug_span!(
            target: "girt",
            "index.read_index",
            outcome = "incomplete",
            failure_class = tracing::field::Empty,
            effects = tracing::field::Empty,
        );

        let operation = || {
            read_bytes(&path, limits)?
                .map(|bytes| {
                    parse_storage(self.object_format(), &path, &bytes, limits, resolve_split)
                        .map(|(index, _)| index)
                })
                .transpose()
        };
        #[cfg(feature = "tracing")]
        let result = span.in_scope(operation);
        #[cfg(not(feature = "tracing"))]
        let result = { operation }();
        #[cfg(feature = "tracing")]
        crate::trace::finish(&span, &result, |error| crate::trace::index(error, &span));

        result
    }

    /// Exclusively locks the per-worktree index, then reads and validates its current bytes.
    ///
    /// The repository selects SHA-1 or SHA-256; existing bytes never override its format.
    /// Derive drafts from the returned guard rather than a previously read snapshot. Absence
    /// becomes an empty editable index, but does not create `index` until commit. Existing locks
    /// are preserved. Parse/read failure releases the newly acquired lock.
    ///
    /// # Errors
    ///
    /// Returns lock contention, I/O, unsupported/malformed index or resource errors. No existing
    /// index bytes are modified. See [`IndexEdit`] for filesystem and cleanup assumptions.
    ///
    /// ```
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let repository = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("repo"),
    ///     InitKind::Worktree,
    /// )?;
    ///
    /// use girt::index::{Entry, Mode};
    /// let id = repository.loose_objects().write_blob(b"staged content\n")?;
    /// let mut edit = repository.edit_index(Default::default())?;
    /// // Derive the full replacement from the locked snapshot, retaining other paths.
    /// let mut entries = edit.index().entries().to_vec();
    /// entries.retain(|entry| entry.path != b"hello.txt");
    /// entries.push(Entry::new(b"hello.txt".to_vec(), Mode::Regular, id));
    /// edit.replace_entries(entries)?;
    /// edit.commit()?;
    /// assert_eq!(
    ///     repository
    ///         .read_index(Default::default())?
    ///         .unwrap()
    ///         .entries()[0]
    ///         .id,
    ///     id
    /// );
    /// assert!(!repository.worktree().unwrap().join("hello.txt").exists());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn edit_index(&self, limits: Limits) -> Result<IndexEdit, StorageError> {
        self.edit_index_path(
            self.git_dir().join("index"),
            limits,
            EditOptions {
                resolve_split: true,
                ..EditOptions::default()
            },
        )
    }

    /// Locks and edits a caller-selected standalone index.
    ///
    /// Uses [`Self::read_index_at`]'s path, format and symlink policy. Relative paths are made
    /// absolute before acquiring the lock and remain fixed throughout the edit. The adjacent lock
    /// name appends `.lock` to the complete filename, including any extension. Parent directories
    /// must already exist. Missing storage starts empty and is created only by explicit commit.
    /// Existing locks are never stolen. Publication uses [`IndexEdit`]'s unchanged snapshot and
    /// lock-identity checks; it never retries through another index path.
    ///
    /// # Errors
    ///
    /// Returns [`Self::edit_index`]'s lock, I/O, format and resource failures. Split `link`
    /// extensions are rejected without reading shared dependencies. Failure releases only the
    /// acquired lock; cleanup failures are retained. No other index path is read or changed.
    ///
    /// # Examples
    ///
    /// ```
    /// # use girt::{Repository, index::Limits};
    /// # let directory = tempfile::tempdir()?;
    /// # let repository = Repository::init(girt::ObjectFormat::Sha1, directory.path().join("r"), girt::InitKind::Worktree)?;
    /// let mut edit = repository.edit_index_at(directory.path().join("temporary.index"), Limits::default())?;
    /// edit.replace_entries(Vec::new())?;
    /// edit.commit()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn edit_index_at(
        &self,
        path: impl AsRef<Path>,
        limits: Limits,
    ) -> Result<IndexEdit, StorageError> {
        self.edit_index_at_with_options(path, limits, EditOptions::default())
    }

    /// Locks a selected index with explicit split and symlink admission.
    ///
    /// Paths are fixed lexically before locking. Split dependencies are read beside that path,
    /// including when its final leaf is a symlink; the referent's parent is never used for lookup.
    /// A followed missing target starts an empty draft. Publication replaces the selected symlink,
    /// never its referent. Leaf identity/spelling and followed bytes are rechecked before rename.
    /// See [`IndexEdit`] for cooperating-writer, cleanup and durability requirements.
    ///
    /// # Errors
    ///
    /// Returns the lock, bounded-read, format and cleanup errors of [`Self::edit_index_at`]. A
    /// required absent shared file is [`StorageError::MissingShared`], never an empty replacement.
    ///
    /// ```
    /// # use girt::{Repository, index::{EditOptions, Limits}};
    /// # let directory = tempfile::tempdir()?;
    /// # let repository = Repository::init(girt::ObjectFormat::Sha1, directory.path().join("r"), girt::InitKind::Worktree)?;
    /// let options = EditOptions::default()
    ///     .with_resolve_split(true)
    ///     .with_follow_symlink(true);
    /// let mut edit =
    ///     repository.edit_index_at_with_options(directory.path().join("alternate.index"), Limits::default(), options)?;
    /// edit.discard_optional_extensions(&[*b"REUC"])?;
    /// edit.commit()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn edit_index_at_with_options(
        &self,
        path: impl AsRef<Path>,
        limits: Limits,
        options: EditOptions,
    ) -> Result<IndexEdit, StorageError> {
        self.edit_index_path(absolute_index_path(path.as_ref())?, limits, options)
    }

    fn edit_index_path(
        &self,
        destination: PathBuf,
        limits: Limits,
        options: EditOptions,
    ) -> Result<IndexEdit, StorageError> {
        IndexEdit::acquire(self.object_format(), destination, limits, options)
    }
}

impl IndexEdit {
    pub(crate) fn acquire(
        format: ObjectFormat,
        destination: PathBuf,
        limits: Limits,
        options: EditOptions,
    ) -> Result<IndexEdit, StorageError> {
        let _lock_operation = crate::locks::operation();
        let destination = absolute_index_path(&destination)?;
        #[cfg(feature = "tracing")]
        let span = tracing::debug_span!(
            target: "girt",
            "index.edit_index",
            outcome = "incomplete",
            failure_class = tracing::field::Empty,
            effects = tracing::field::Empty,
        );

        let operation = || {
            let mut lock_name = destination.as_os_str().to_os_string();
            lock_name.push(".lock");
            let lock_path = PathBuf::from(lock_name);
            let file = OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&lock_path)
                .map_err(|source| {
                    if source.kind() == io::ErrorKind::AlreadyExists {
                        StorageError::Locked(lock_path.clone())
                    } else {
                        io_error("create lock", &lock_path, source)
                    }
                })?;
            let lock_identity = file.metadata().map_err(|source| StorageError::Cleanup {
                operation: Box::new(io_error("inspect acquired lock", &lock_path, source)),
                cleanup: Box::new(io_error(
                    "identify lock for cleanup",
                    &lock_path,
                    io::Error::other("cannot safely remove lock without its file identity"),
                )),
            })?;
            let file = crate::locks::SharedFile::from(file);
            let cleanup = crate::locks::Guard::new(&lock_path, &file, lock_identity.clone());
            let mut edit = IndexEdit {
                destination,
                lock_path,
                lock_identity,
                cleanup,
                file: Some(file),
                original: None,
                leaf: None,
                shared: None,
                index: Index::empty(format),
                limits,
                published: false,
            };
            let result = (|| {
                if options.follow_symlink {
                    edit.leaf = Some(LeafSnapshot::read(&edit.destination)?);
                }
                edit.original =
                    read_selected_bytes(&edit.destination, limits, options.follow_symlink)?;
                if let Some(bytes) = &edit.original {
                    (edit.index, edit.shared) = parse_storage(
                        format,
                        &edit.destination,
                        bytes,
                        limits,
                        options.resolve_split,
                    )?;
                }
                if let Some(leaf) = &edit.leaf {
                    leaf.check(&edit.destination)?;
                }
                Ok(())
            })();
            if let Err(operation) = result {
                return Err(with_cleanup(operation, edit.abort()));
            }
            Ok(edit)
        };
        #[cfg(feature = "tracing")]
        let result = span.in_scope(operation);
        #[cfg(not(feature = "tracing"))]
        let result = { operation }();
        #[cfg(feature = "tracing")]
        crate::trace::finish(&span, &result, |error| crate::trace::index(error, &span));

        result
    }
}

impl IndexEdit {
    /// Borrows the snapshot read after acquiring the lock, including accepted edits.
    pub fn index(&self) -> &Index {
        &self.index
    }

    pub(crate) fn original_missing(&self) -> bool {
        self.original.is_none()
            && self
                .leaf
                .as_ref()
                .is_none_or(|leaf| leaf.metadata.is_none())
    }

    /// Validates and replaces drafts under the guard's resource and extension policy.
    ///
    /// # Errors
    ///
    /// Propagates [`Index::replace_entries`] errors and preserves the previous in-memory index.
    /// No bytes are written; the guard continues to own the lock after failure.
    ///
    /// # Examples
    ///
    /// ```
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("r"),
    ///     InitKind::Worktree,
    /// )?;
    ///
    /// use girt::index::{Entry, Mode};
    /// let id = repo.loose_objects().write_blob(b"staged")?;
    /// let mut edit = repo.edit_index(Default::default())?;
    /// edit.replace_entries(vec![Entry::new(b"file".to_vec(), Mode::Regular, id)])?;
    /// edit.commit()?;
    /// let mut edit = repo.edit_index(Default::default())?;
    /// edit.replace_entries(Vec::new())?;
    /// edit.commit()?;
    /// assert!(
    ///     repo.read_index(Default::default())?
    ///         .unwrap()
    ///         .entries()
    ///         .is_empty()
    /// );
    /// assert_eq!(repo.loose_objects().read_blob(id, 1024)?, b"staged");
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn replace_entries(&mut self, entries: Vec<Entry>) -> Result<(), Error> {
        self.index.replace_entries(entries, self.limits)
    }

    /// Replaces the complete draft with a caller-supplied standalone index.
    ///
    /// The held object format and limits are validated before mutation. Original primary/shared
    /// snapshots and lock ownership remain unchanged; only explicit commit publishes the draft.
    ///
    /// # Errors
    ///
    /// Foreign formats, limit failures and any `link` extension leave the previous draft intact.
    /// A replacement cannot introduce a shared dependency that this guard has not captured.
    ///
    /// Use this when a consumer has built a complete replacement with its own framing choice, while
    /// retaining the original guard's publication preconditions.
    ///
    /// # Examples
    ///
    /// ```
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("r"),
    ///     InitKind::Worktree,
    /// )?;
    ///
    /// use girt::index::{Entry, Index, Mode, Version};
    /// let id = repo.loose_objects().write_blob(b"replacement")?;
    /// let mut replacement = Index::new(
    ///     ObjectFormat::Sha1,
    ///     vec![Entry::new(b"file".to_vec(), Mode::Regular, id)],
    ///     Default::default(),
    /// )?;
    /// replacement.set_version(Version::V4, Default::default())?;
    /// let mut edit = repo.edit_index(Default::default())?;
    /// edit.replace_index(replacement)?;
    /// edit.commit()?;
    /// assert_eq!(
    ///     repo.read_index(Default::default())?.unwrap().version(),
    ///     Version::V4
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn replace_index(&mut self, index: Index) -> Result<(), Error> {
        crate::ObjectId::null(index.object_format()).require_format(self.index.object_format())?;
        if index
            .extensions()
            .iter()
            .any(|extension| extension.signature() == *b"link")
        {
            return Err(Error::ExtensionPreventsEdit(*b"link"));
        }
        index.encoded_len(self.limits)?;
        self.index = index;
        Ok(())
    }

    /// Explicitly discards selected optional extensions from the held draft.
    ///
    /// Only uppercase-leading signatures are accepted. An actual removal also drops `EOIE` and
    /// `IEOT`, whose offsets can change during encoding. Split drafts become standalone at the
    /// same version, dropping `link` and derived caches while retaining unselected `REUC` and
    /// the original shared-file publication check. Standalone sparse markers are retained.
    ///
    /// # Errors
    ///
    /// Mandatory signatures, retained unknown extensions during split conversion and resource
    /// failures leave the entire draft unchanged. No matching extension is a byte-preserving no-op.
    pub fn discard_optional_extensions(&mut self, signatures: &[[u8; 4]]) -> Result<(), Error> {
        self.index
            .discard_optional_extensions(signatures, self.limits)
    }

    /// Expands sparse directories in the held draft, leaving publication to `commit`.
    ///
    /// # Errors
    ///
    /// See [`Index::expand_sparse`]. Failure preserves both draft and storage; the lock stays held.
    pub fn expand_sparse(
        &mut self,
        objects: &crate::Objects,
        limits: super::SparseLimits,
        cancelled: &std::sync::atomic::AtomicBool,
    ) -> Result<(), super::SparseError> {
        self.index
            .expand_sparse(objects, self.limits, limits, cancelled)
    }

    /// Reuses locked cached stat words for unchanged draft entries, then validates replacement.
    ///
    /// Matches path, stage, mode, object ID and all flags. Changed/new entries retain the caller's
    /// supplied stat words; no filesystem verification occurs. The caller still owns staging and
    /// skip-worktree/intent-to-add choices. Derived cache extensions are invalidated exactly as in
    /// [`Self::replace_entries`]. Publication smudges racily clean entries; see [`Self::commit`].
    ///
    /// # Errors
    ///
    /// Returns validation/extension errors without changing the draft index or storage.
    ///
    /// Batch a consumer's reconstructed entry list without throwing away useful stat words for
    /// identical entries. This is cache preservation, not worktree verification; an identity or
    /// mode change must not inherit the old entry's stat evidence.
    ///
    /// # Examples
    ///
    /// ```
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("r"),
    ///     InitKind::Worktree,
    /// )?;
    ///
    /// use girt::index::{Entry, Mode, Stat};
    /// let id = repo.loose_objects().write_blob(b"original")?;
    /// let stat = Stat {
    ///     size: 8,
    ///     ..Stat::default()
    /// };
    /// let original = Entry::new(b"file".to_vec(), Mode::Regular, id).with_stat(stat);
    /// let mut edit = repo.edit_index(Default::default())?;
    /// edit.replace_entries(vec![original.clone()])?;
    /// let draft = Entry::new(b"file".to_vec(), Mode::Regular, id);
    /// edit.replace_entries_reusing_stat(vec![draft])?;
    /// assert_eq!(edit.index().entries()[0].stat, stat);
    /// let mut changed = original.with_stat(Stat::default());
    /// changed.id = repo.loose_objects().write_blob(b"replacement")?;
    /// edit.replace_entries_reusing_stat(vec![changed])?;
    /// assert_eq!(edit.index().entries()[0].stat, Stat::default());
    /// edit.abort()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn replace_entries_reusing_stat(&mut self, mut entries: Vec<Entry>) -> Result<(), Error> {
        let old = self.index.entries();
        for entry in &mut entries {
            let found = old.binary_search_by(|candidate| {
                candidate
                    .path
                    .cmp(&entry.path)
                    .then(candidate.stage.cmp(&entry.stage))
            });
            if let Ok(position) = found
                && let Some(previous) = old.get(position)
                && previous.id == entry.id
                && previous.mode == entry.mode
                && previous.assume_valid == entry.assume_valid
                && previous.intent_to_add == entry.intent_to_add
                && previous.skip_worktree == entry.skip_worktree
            {
                entry.stat = previous.stat;
            }
        }
        self.replace_entries(entries)
    }

    /// Selects framing under the guard's extension and resource policy.
    ///
    /// # Errors
    ///
    /// See [`Index::set_version`]; failures leave the snapshot and storage unchanged.
    pub fn set_version(&mut self, version: super::Version) -> Result<(), Error> {
        self.index.set_version(version, self.limits)
    }

    /// Converts a resolved split index to standalone storage without changing its entries or
    /// version.
    ///
    /// Preserves paths, IDs, stages, flags and stat words, even when the logical entries and
    /// framing version are unchanged. Removes `link` and the derived `TREE`, `UNTR`, `FSMN`,
    /// `EOIE` and `IEOT` caches. Resolve-undo (`REUC`) bytes are retained. An already
    /// standalone supported index retains its exact encoding, including caches.
    ///
    /// This only changes the held draft. The shared file is never written or removed; its original
    /// bytes remain a publication precondition alongside the primary index. Call [`Self::commit`]
    /// to publish, or drop the guard to discard the draft. The existing lock stays held throughout.
    ///
    /// # Errors
    ///
    /// Sparse (`sdir`) and unknown extensions are rejected, including on standalone input. Resource
    /// or extension errors preserve the draft and storage. Shared-file resolution errors are
    /// reported earlier by [`Repository::edit_index`]. Explicit alternate indexes with split
    /// dependencies remain unsupported by [`Repository::edit_index_at`].
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let directory = tempfile::tempdir()?;
    /// let repository = girt::Repository::init(
    ///     girt::ObjectFormat::Sha1,
    ///     directory.path().join("r"),
    ///     girt::InitKind::Worktree,
    /// )?;
    /// let mut edit = repository.edit_index(girt::index::Limits::default())?;
    /// edit.make_standalone()?;
    /// edit.commit()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn make_standalone(&mut self) -> Result<(), Error> {
        self.index.make_standalone(self.limits)
    }

    /// Discards standalone entry-offset accelerators (`EOIE` and `IEOT`) under the held lock.
    ///
    /// Preserves entries, stat words, flags, framing version and opaque `TREE`/`REUC`/`sdir`
    /// payloads. Both offset caches must be removed: canonical re-encoding can change entry byte
    /// boundaries even when version and logical entries are unchanged. Also drops fsmonitor
    /// (`FSMN`) and untracked (`UNTR`) caches. With no derived cache present, the original
    /// encoding is retained. Publication remains explicit through [`Self::commit`].
    ///
    /// # Errors
    ///
    /// Extensions other than `TREE`, `REUC`, `sdir` and these four caches, including split-index
    /// `link`, prevent this bounded rewrite. Extension or output-limit failures leave the snapshot
    /// and storage unchanged. Cache payloads are not interpreted or repaired; they are
    /// discarded.
    pub fn invalidate_entry_offsets(&mut self) -> Result<(), Error> {
        self.index.invalidate_entry_offsets(self.limits)
    }

    /// Discards a standalone index's resolve-undo (`REUC`) information under the held lock.
    ///
    /// Preserves entries, stat words, flags, version and `TREE` payloads. A removal also drops
    /// `FSMN`, `UNTR`, `EOIE` and `IEOT` caches. Resolve-undo payloads are discarded opaquely,
    /// without interpreting or repairing them. Use this only when the caller's operation
    /// intentionally forgets previous conflict resolutions. An absent `REUC` retains the
    /// original encoding. Publication remains explicit through [`Self::commit`].
    ///
    /// # Errors
    ///
    /// Unknown extensions, sparse `sdir` and split `link` prevent this edit. Extension and
    /// output-limit errors preserve the draft and storage; the lock remains held. This does
    /// not relax the extension policies of entry replacement or tree-cache invalidation.
    ///
    /// # Examples
    ///
    /// ```
    /// # use girt::{Repository, index::Limits};
    /// # let directory = tempfile::tempdir()?;
    /// # let repository = Repository::init(girt::ObjectFormat::Sha1, directory.path().join("r"), girt::InitKind::Worktree)?;
    /// let mut edit = repository.edit_index(Limits::default())?;
    /// edit.invalidate_entry_offsets()?;
    /// edit.discard_resolve_undo()?;
    /// edit.commit()?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn discard_resolve_undo(&mut self) -> Result<(), Error> {
        self.index.discard_resolve_undo(self.limits)
    }

    /// Discards a standalone index's `TREE` cache under the held lock.
    ///
    /// Entry replacement already discards `TREE` when entries change. Use this method when the
    /// cached tree must be removed even though the entries are unchanged. Also drops derived
    /// `FSMN`, `UNTR`, `EOIE` and `IEOT` caches, which Git can rebuild. No bytes are written
    /// until [`Self::commit`]. An index without extensions is accepted as a no-op.
    ///
    /// # Errors
    ///
    /// Any extension other than these five derived caches, including `REUC`, `sdir` and split
    /// `link`, prevents this edit. Resource-limit failure also leaves the draft and stored index
    /// unchanged. The lock remains held after either failure.
    pub fn invalidate_tree_cache(&mut self) -> Result<(), Error> {
        self.index.invalidate_tree_cache(self.limits)
    }

    /// Encodes, rechecks the original bytes, writes the owned lock and renames it over `index`.
    ///
    /// Consumes the guard on success or failure. A final exact-byte/presence comparison detects
    /// noncooperating changes observed before rename, but cannot exclude a noncooperating writer
    /// racing after that comparison. Cooperating writers remain excluded for the entire lifecycle.
    ///
    /// Like Git, entries that could be racily clean have their cached size zeroed so readers
    /// recheck their contents: those modified at or after the earlier of the previous index's
    /// modification time and the time of writing. This keeps a previously racy entry from
    /// appearing clean merely because the index was rewritten later. Other stat words remain
    /// exact. Callers supplying new stat data still own its correctness.
    ///
    /// # Errors
    ///
    /// Encoding, precondition, write, timestamp and rename failures preserve the destination's
    /// bytes, apart from independent concurrent changes. The acquired lock is cleaned on failure
    /// where possible. Successful return reports publication, not crash durability.
    pub fn commit(self) -> Result<(), StorageError> {
        self.commit_with_options(IndexCommitOptions::default())
    }

    /// Publishes with explicit lock-file permissions and optional file synchronization.
    ///
    /// Permission and synchronization failures occur before rename and preserve the selected
    /// destination. Existing snapshot/lock checks and cleanup behavior remain in force. Successful
    /// file synchronization does not promise directory-entry or power-loss durability.
    ///
    /// # Errors
    ///
    /// Returns [`Self::commit`]'s errors plus invalid/unsupported mode and file-sync failures.
    /// Exact modes are validated before writing the lock. No synchronization failure is ignored.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[cfg(unix)]
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let repo = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("r"),
    ///     InitKind::Worktree,
    /// )?;
    ///
    /// use girt::index::IndexCommitOptions;
    /// let edit = repo.edit_index(Default::default())?;
    /// edit.commit_with_options(
    ///     IndexCommitOptions::default()
    ///         .with_shared_permissions(girt::SharedPermissions::Group)
    ///         .with_sync(true),
    /// )?;
    /// use std::os::unix::fs::PermissionsExt;
    /// let mode = std::fs::metadata(repo.git_dir().join("index"))?
    ///     .permissions()
    ///     .mode();
    /// assert_eq!(mode & 0o660, 0o660);
    /// // The lock file was flushed; the parent directory was not synchronized.
    /// # Ok(())
    /// # }
    /// # #[cfg(not(unix))]
    /// # fn main() {}
    /// ```
    pub fn commit_with_options(mut self, options: IndexCommitOptions) -> Result<(), StorageError> {
        #[cfg(feature = "tracing")]
        let span = tracing::debug_span!(
            target: "girt",
            "index.commit",
            outcome = "incomplete",
            failure_class = tracing::field::Empty,
            effects = tracing::field::Empty,
        );

        let operation = || {
            if let Err(operation) = self.publish_with_options(options) {
                return Err(with_cleanup(operation, self.abort()));
            }
            Ok(())
        };
        #[cfg(feature = "tracing")]
        let result = span.in_scope(operation);
        #[cfg(not(feature = "tracing"))]
        let result = { operation }();
        #[cfg(feature = "tracing")]
        crate::trace::finish(&span, &result, |error| crate::trace::index(error, &span));

        result
    }

    /// Publishes a missing index without replacing a concurrently created path.
    ///
    /// The owned lock is linked to the destination atomically, then removed. A competing path
    /// makes publication fail without changing its bytes. This operation requires an absent
    /// snapshot; callers with existing indexes must use the ordinary guarded commit.
    ///
    /// # Errors
    ///
    /// Returns [`StorageError::Changed`] if the acquired snapshot already had a destination,
    /// an I/O error if conditional publication fails, or
    /// [`StorageError::PublishedCleanup`] if the destination was installed but lock cleanup
    /// failed. The last case requires inspection before retrying.
    pub(crate) fn commit_new_with_options(
        self,
        options: IndexCommitOptions,
    ) -> Result<(), StorageError> {
        self.commit_new_with_cleanup(options, |path| fs::remove_file(path))
    }

    fn commit_new_with_cleanup(
        mut self,
        options: IndexCommitOptions,
        remove_lock: impl FnOnce(&Path) -> io::Result<()>,
    ) -> Result<(), StorageError> {
        let _lock_operation = crate::locks::operation();
        let operation = (|| {
            if !self.original_missing() {
                return Err(StorageError::Changed(self.destination.clone()));
            }
            self.publish_with_policy(options, crate::file_policy::sync_file, |from, to| {
                fs::hard_link(from, to)
            })?;
            remove_lock(&self.lock_path).map_err(|source| StorageError::PublishedCleanup {
                path: self.destination.clone(),
                lock: self.lock_path.clone(),
                source,
            })
        })();
        match operation {
            Ok(()) => Ok(()),
            Err(operation) if self.published => Err(operation),
            Err(operation) => Err(with_cleanup(operation, self.abort())),
        }
    }

    /// Releases the owned lock without publishing and reports cleanup failure.
    ///
    /// # Errors
    ///
    /// Returns the lock path and I/O cause when removal fails. The lock may remain for manual
    /// recovery; no index or working-tree content is changed.
    /// An `Interrupted` I/O cause after caller cleanup means the guard was invalidated; consult
    /// cleanup's earlier report rather than inferring that an owned lock still needs recovery.
    ///
    /// ```
    /// use girt::{InitKind, ObjectFormat, Repository};
    /// let directory = tempfile::tempdir()?;
    /// let repository = Repository::init(
    ///     ObjectFormat::Sha1,
    ///     directory.path().join("repo"),
    ///     InitKind::Worktree,
    /// )?;
    ///
    /// let edit = repository.edit_index(Default::default())?;
    /// edit.abort()?;
    /// assert!(repository.read_index(Default::default())?.is_none());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn abort(mut self) -> Result<(), StorageError> {
        let _lock_operation = crate::locks::operation();
        #[cfg(feature = "tracing")]
        let span = tracing::debug_span!(
            target: "girt",
            "index.abort",
            outcome = "incomplete",
            failure_class = tracing::field::Empty,
            effects = tracing::field::Empty,
        );

        let operation = || {
            self.published = true; // Do not silently retry an explicitly reported cleanup failure.
            self.check_lock_identity()?;
            drop(self.file.take());
            fs::remove_file(&self.lock_path)
                .map_err(|source| io_error("remove owned index lock", &self.lock_path, source))
        };
        #[cfg(feature = "tracing")]
        let result = span.in_scope(operation);
        #[cfg(not(feature = "tracing"))]
        let result = { operation }();
        #[cfg(feature = "tracing")]
        crate::trace::finish(&span, &result, |error| crate::trace::index(error, &span));

        result
    }

    #[cfg(any(target_os = "linux", target_os = "macos"))]
    pub(crate) fn discard_checkout_caches(&mut self) {
        self.index.discard_checkout_caches();
    }

    // Used by worktree checkout, which is available only on Linux and macOS.
    #[cfg(any(target_os = "linux", target_os = "macos"))]
    pub(crate) fn publish(&mut self) -> Result<(), StorageError> {
        self.publish_with_options(IndexCommitOptions::default())
    }

    fn publish_with_options(&mut self, options: IndexCommitOptions) -> Result<(), StorageError> {
        self.publish_with_policy(options, crate::file_policy::sync_file, |from, to| {
            fs::rename(from, to)
        })
    }

    #[cfg(test)]
    fn publish_with_rename(
        &mut self,
        rename: impl FnOnce(&Path, &Path) -> io::Result<()>,
    ) -> Result<(), StorageError> {
        self.publish_with_policy(
            IndexCommitOptions::default(),
            crate::file_policy::sync_file,
            rename,
        )
    }

    fn publish_with_policy(
        &mut self,
        options: IndexCommitOptions,
        sync: impl FnOnce(&File) -> io::Result<()>,
        rename: impl FnOnce(&Path, &Path) -> io::Result<()>,
    ) -> Result<(), StorageError> {
        let _lock_operation = crate::locks::operation();
        options
            .shared_permissions
            .validate()
            .map_err(|source| io_error("validate index permissions", &self.lock_path, source))?;
        // Racily clean entries: cached stat data isn't trustworthy for files modified at or after
        // the time the stat was recorded relative to an index. Entries may carry stat data from
        // the previous index, so the earlier of its modification time and now is the threshold.
        let now = std::time::SystemTime::now();
        let previous = fs::metadata(&self.destination)
            .and_then(|metadata| metadata.modified())
            .ok();
        let threshold = previous.map_or(now, |previous| previous.min(now));
        let threshold = threshold.duration_since(std::time::UNIX_EPOCH).map_or(
            Timestamp::default(),
            |duration| Timestamp {
                seconds: u32::try_from(duration.as_secs()).unwrap_or(u32::MAX),
                nanoseconds: duration.subsec_nanos(),
            },
        );
        self.index.smudge_racy_entries(threshold);
        let bytes = self
            .index
            .encode(self.limits)
            .map_err(|source| StorageError::Format {
                path: self.destination.clone(),
                source,
            })?;
        self.check_original()?;
        self.write_lock(&bytes)?;
        #[expect(
            clippy::expect_used,
            reason = "the guard holds its file until publication"
        )]
        let file = self.file.as_ref().expect("unpublished guard owns its file");
        options
            .shared_permissions
            .apply_file(file)
            .map_err(|source| io_error("set index permissions", &self.lock_path, source))?;
        if options.sync {
            sync(file)
                .map_err(|source| io_error("synchronize index lock", &self.lock_path, source))?;
        }
        self.check_original()?;
        self.check_lock_identity()?;
        drop(self.file.take());
        rename(&self.lock_path, &self.destination)
            .map_err(|source| io_error("replace index", &self.destination, source))?;
        self.published = true;
        Ok(())
    }

    fn check_lock_identity(&self) -> Result<(), StorageError> {
        self.cleanup
            .check()
            .map_err(|source| io_error("check lock registration", &self.lock_path, source))?;
        let current = fs::symlink_metadata(&self.lock_path)
            .map_err(|source| io_error("inspect owned index lock", &self.lock_path, source))?;
        if !current.is_file() {
            return Err(StorageError::Changed(self.lock_path.clone()));
        }
        #[cfg(unix)]
        {
            use std::os::unix::fs::MetadataExt;
            let owned = &self.lock_identity;
            if current.dev() != owned.dev() || current.ino() != owned.ino() {
                return Err(StorageError::Changed(self.lock_path.clone()));
            }
        }
        #[cfg(not(unix))]
        let _ = &self.lock_identity;
        Ok(())
    }

    fn check_original(&self) -> Result<(), StorageError> {
        if let Some(leaf) = &self.leaf {
            leaf.check(&self.destination)?;
        }
        if read_selected_bytes(&self.destination, self.limits, self.leaf.is_some())?
            != self.original
        {
            return Err(StorageError::Changed(self.destination.clone()));
        }
        if let Some((path, bytes)) = &self.shared
            && read_bytes(path, self.limits)?.as_ref() != Some(bytes)
        {
            return Err(StorageError::Changed(path.clone()));
        }
        Ok(())
    }

    fn write_lock(&mut self, bytes: &[u8]) -> Result<(), StorageError> {
        #[expect(
            clippy::expect_used,
            reason = "the guard holds its file until publication"
        )]
        let file = self.file.as_mut().expect("unpublished guard owns its file");
        file.write_all(bytes)
            .map_err(|source| io_error("write lock", &self.lock_path, source))?;
        file.flush()
            .map_err(|source| io_error("flush lock", &self.lock_path, source))?;
        Ok(())
    }
}
impl Drop for IndexEdit {
    fn drop(&mut self) {
        let _lock_operation = crate::locks::operation();
        if !self.published && self.check_lock_identity().is_ok() {
            drop(self.file.take());
            let _ = fs::remove_file(&self.lock_path);
        }
    }
}
fn absolute_index_path(path: &Path) -> Result<PathBuf, StorageError> {
    std::path::absolute(path).map_err(|source| io_error("resolve index path", path, source))
}

fn read_bytes(path: &Path, limits: Limits) -> Result<Option<Vec<u8>>, StorageError> {
    read_selected_bytes(path, limits, false)
}

fn read_selected_bytes(
    path: &Path,
    limits: Limits,
    follow_symlink: bool,
) -> Result<Option<Vec<u8>>, StorageError> {
    let metadata = match if follow_symlink {
        fs::metadata(path)
    } else {
        fs::symlink_metadata(path)
    } {
        Ok(metadata) => metadata,
        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(source) => return Err(io_error("inspect index", path, source)),
    };
    if !metadata.is_file() {
        return Err(StorageError::NotRegular(path.into()));
    }
    let file = File::open(path).map_err(|source| io_error("open index", path, source))?;
    let mut bytes = Vec::new();
    let limit = (limits.max_bytes as u64).saturating_add(1);
    file.take(limit)
        .read_to_end(&mut bytes)
        .map_err(|source| io_error("read index", path, source))?;
    if bytes.len() > limits.max_bytes {
        return Err(StorageError::Format {
            path: path.into(),
            source: Error::Limit("bytes"),
        });
    }
    Ok(Some(bytes))
}
type SharedFile = Option<(PathBuf, Vec<u8>)>;
fn parse_storage(
    format: crate::ObjectFormat,
    path: &Path,
    bytes: &[u8],
    limits: Limits,
    resolve_split: bool,
) -> Result<(Index, SharedFile), StorageError> {
    let contextual = |source| StorageError::Format {
        path: path.into(),
        source,
    };
    let index = Index::parse_file(format, bytes, limits).map_err(contextual)?;
    if !resolve_split
        && index
            .extensions()
            .iter()
            .any(|extension| extension.signature() == *b"link")
    {
        return Err(contextual(Error::MandatoryExtension(*b"link")));
    }
    let shared = if let Some(id) = index.shared_index_id() {
        let shared_path = path.with_file_name(format!("sharedindex.{id}"));
        let remaining = Limits {
            max_bytes: limits.max_bytes.saturating_sub(bytes.len()),
            ..limits
        };
        let shared_bytes = read_bytes(&shared_path, remaining)?
            .ok_or_else(|| StorageError::MissingShared(shared_path.clone()))?;
        Some((shared_path, shared_bytes))
    } else {
        None
    };
    let index = index
        .resolve_shared(shared.as_ref().map(|(_, bytes)| bytes.as_slice()), limits)
        .map_err(contextual)?;
    Ok((index, shared))
}
fn io_error(operation: &'static str, path: &Path, source: io::Error) -> StorageError {
    StorageError::Io {
        operation,
        path: path.into(),
        source,
    }
}

#[cfg(test)]
#[allow(clippy::unreachable, reason = "tests assert on unexpected variants")]
mod tests;

fn with_cleanup(operation: StorageError, cleanup: Result<(), StorageError>) -> StorageError {
    match cleanup {
        Ok(()) => operation,
        Err(cleanup) => StorageError::Cleanup {
            operation: Box::new(operation),
            cleanup: Box::new(cleanup),
        },
    }
}

#[cfg(test)]
#[allow(clippy::unreachable, reason = "tests assert on unexpected variants")]
mod options_tests;